p5.js-web-editor/dist/static/assets/ml5.js
Ruben van de Ven 8ebe30af90 fix console log
2020-09-28 13:25:45 +02:00

125828 lines
No EOL
5.7 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["ml5"] = factory();
else
root["ml5"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 693);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global, process, Buffer, setImmediate) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdadeltaOptimizer", function() { return Yd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdagradOptimizer", function() { return $d; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdamOptimizer", function() { return Qd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdamaxOptimizer", function() { return Jd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Add", function() { return xr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddN", function() { return br; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BroadcastTo", function() { return Sr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataStorage", function() { return ca; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Div", function() { return wr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ENV", function() { return s; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Environment", function() { return o; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FromPixels", function() { return Fr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FusedBatchNorm", function() { return Cr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Identity", function() { return Tr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KernelBackend", function() { return la; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaxPoolWithArgmax", function() { return _r; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MomentumOptimizer", function() { return tp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NonMaxSuppressionV5", function() { return kr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneHot", function() { return Ar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Optimizer", function() { return Xd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PadV2", function() { return Nr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RMSPropOptimizer", function() { return ep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rank", function() { return Ct; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Reduction", function() { return Nh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SGDOptimizer", function() { return Zd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Square", function() { return Rr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SquaredDifference", function() { return Er; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tensor", function() { return wt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TensorBuffer", function() { return mt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tile", function() { return Dr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Transpose", function() { return Ir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Variable", function() { return St; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "abs", function() { return Lr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "acos", function() { return Wr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "acosh", function() { return Ur; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "add", function() { return Or; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addN", function() { return $u; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addStrict", function() { return xo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return ql; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return Kl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argMax", function() { return jl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argMin", function() { return Xl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asin", function() { return Vr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asinh", function() { return zr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atan", function() { return Gr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atan2", function() { return bo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atanh", function() { return Hr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avgPool", function() { return Ol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avgPool3d", function() { return Pl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backend", function() { return hn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backend_util", function() { return Sa; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "basicLSTMCell", function() { return lh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm", function() { return nc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm2d", function() { return ac; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm3d", function() { return uc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm4d", function() { return hc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization", function() { return ec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization2d", function() { return oc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization3d", function() { return sc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization4d", function() { return lc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchToSpaceND", function() { return rr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "booleanMaskAsync", function() { return ul; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "broadcastTo", function() { return fc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "browser", function() { return Vd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return er; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cast", function() { return or; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ceil", function() { return qr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clipByValue", function() { return Kr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return dc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "complex", function() { return Tn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return Yn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat1d", function() { return $n; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat2d", function() { return Qn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat3d", function() { return Jn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat4d", function() { return Zn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv1d", function() { return fl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv2d", function() { return dl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv2dTranspose", function() { return wl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv3d", function() { return pl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv3dTranspose", function() { return Cl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cos", function() { return jr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cosh", function() { return Xr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cumsum", function() { return ar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "customGrad", function() { return oa; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deprecationWarn", function() { return Xe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "depthToSpace", function() { return ir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "depthwiseConv2d", function() { return ml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "diag", function() { return Eh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disableDeprecationWarnings", function() { return je; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispose", function() { return tn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disposeVariables", function() { return Ye; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "div", function() { return Bo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "divNoNan", function() { return bc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "divStrict", function() { return wo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dot", function() { return Rl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dropout", function() { return Rh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elu", function() { return nh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableDebugMode", function() { return Ke; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableProdMode", function() { return qe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "engine", function() { return $e; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "env", function() { return i; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equal", function() { return Kc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equalStrict", function() { return jc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "erf", function() { return Yr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exp", function() { return $r; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expandDims", function() { return sr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expm1", function() { return Qr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eye", function() { return Cc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fft", function() { return gh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fill", function() { return Hn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBackend", function() { return un; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBackendFactory", function() { return cn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "floor", function() { return Jr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "floorDiv", function() { return Co; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frame", function() { return Ah; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fused", function() { return hf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gather", function() { return il; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gatherND", function() { return Ch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gather_util", function() { return Lo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBackend", function() { return an; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getGradient", function() { return h; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getKernel", function() { return l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getKernelsForBackend", function() { return f; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grad", function() { return Zo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grads", function() { return ta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greater", function() { return Xc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterEqual", function() { return Yc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterEqualStrict", function() { return $c; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterStrict", function() { return Qc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hammingWindow", function() { return Sh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hannWindow", function() { return kh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ifft", function() { return mh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "imag", function() { return Nn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "image", function() { return nf; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inTopKAsync", function() { return Fh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "io", function() { return Bd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "irfft", function() { return xh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return lo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInf", function() { return co; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return uo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keep", function() { return en; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "leakyRelu", function() { return rh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "less", function() { return Jc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessEqual", function() { return Zc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessEqualStrict", function() { return tl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessStrict", function() { return el; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linalg", function() { return jh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linspace", function() { return qn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "localResponseNormalization", function() { return uh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return Zr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log1p", function() { return to; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSigmoid", function() { return eo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSoftmax", function() { return sa; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSumExp", function() { return Yl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalAnd", function() { return pc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalNot", function() { return vc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalOr", function() { return gc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalXor", function() { return mc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "losses", function() { return zh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "matMul", function() { return El; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "math", function() { return Wd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return $l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPool", function() { return _l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPool3d", function() { return Bl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPoolWithArgmax", function() { return Ll; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maximum", function() { return Eo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maximumStrict", function() { return Ro; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mean", function() { return Ql; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "memory", function() { return Qe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return Jl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minimum", function() { return Io; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minimumStrict", function() { return ko; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mod", function() { return So; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modStrict", function() { return Ao; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moments", function() { return Zl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "movingAverage", function() { return fh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mul", function() { return To; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mulStrict", function() { return Do; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multiRNNCell", function() { return hh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multinomial", function() { return Ec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "neg", function() { return no; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nextFrame", function() { return ap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "norm", function() { return ch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notEqual", function() { return nl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notEqualStrict", function() { return rl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "oneHot", function() { return Rc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ones", function() { return zn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onesLike", function() { return jn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "op", function() { return An; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "outerProduct", function() { return Il; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad", function() { return Ic; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad1d", function() { return kc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad2d", function() { return Sc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad3d", function() { return Ac; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad4d", function() { return Tc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pool", function() { return Ml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pow", function() { return No; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "powStrict", function() { return Fo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prelu", function() { return oh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "print", function() { return nr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prod", function() { return eh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "profile", function() { return Je; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rand", function() { return Dc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomGamma", function() { return Uc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomNormal", function() { return Vc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomUniform", function() { return zc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return Kn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ready", function() { return on; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "real", function() { return Dn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reciprocal", function() { return ro; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerBackend", function() { return ln; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerGradient", function() { return p; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerKernel", function() { return d; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relu", function() { return ah; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relu6", function() { return ih; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeBackend", function() { return sn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reshape", function() { return ur; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse", function() { return kl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse1d", function() { return Sl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse2d", function() { return Al; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse3d", function() { return Tl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse4d", function() { return Dl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rfft", function() { return yh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "round", function() { return oo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rsqrt", function() { return ao; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scalar", function() { return On; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scatterND", function() { return vh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scatter_util", function() { return Ho; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selu", function() { return sh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "separableConv2d", function() { return bl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serialization", function() { return qd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBackend", function() { return rn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPlatform", function() { return fn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setdiff1dAsync", function() { return dr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sigmoid", function() { return io; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sign", function() { return so; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "signal", function() { return Dh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sin", function() { return ho; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sinh", function() { return fo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice", function() { return Wl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice1d", function() { return Ul; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice2d", function() { return Vl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice3d", function() { return zl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice4d", function() { return Gl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice_util", function() { return Jo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "softmax", function() { return ia; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "softplus", function() { return po; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spaceToBatchND", function() { return cr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sparseToDense", function() { return wh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spectral", function() { return bh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "split", function() { return tr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sqrt", function() { return vo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "square", function() { return Gc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squaredDifference", function() { return Hc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squaredDifferenceStrict", function() { return _o; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squeeze", function() { return lr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stack", function() { return hr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "step", function() { return go; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stft", function() { return Th; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stridedSlice", function() { return dh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sub", function() { return Oo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subStrict", function() { return Mo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sum", function() { return th; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sumOutType", function() { return Dt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tan", function() { return mo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tanh", function() { return yo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor", function() { return Fn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor1d", function() { return Mn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor2d", function() { return Bn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor3d", function() { return Pn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor4d", function() { return Ln; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor5d", function() { return Wn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor6d", function() { return Un; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor_util", function() { return Mt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "test_util", function() { return Bc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tidy", function() { return Ze; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tile", function() { return wc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "time", function() { return nn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "topk", function() { return ph; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "train", function() { return rp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return ua; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "truncatedNormal", function() { return qc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregisterGradient", function() { return g; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregisterKernel", function() { return v; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unsortedSegmentSum", function() { return sl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unstack", function() { return fr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "util", function() { return st; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueAndGrad", function() { return ea; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueAndGrads", function() { return na; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variable", function() { return Vn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variableGrads", function() { return ra; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version_core", function() { return Kd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "webgl", function() { return jd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "where", function() { return yc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "whereAsync", function() { return xc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zeros", function() { return Gn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zerosLike", function() { return Xn; });
/**
* @license
* Copyright 2020 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 t=function(e,n){return(t=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])})(e,n)};function e(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function n(t,e,n,r){return new(n||(n=Promise))((function(o,a){function i(t){try{u(r.next(t))}catch(t){a(t)}}function s(t){try{u(r.throw(t))}catch(t){a(t)}}function u(t){t.done?o(t.value):new n((function(e){e(t.value)})).then(i,s)}u((r=r.apply(t,e||[])).next())}))}function r(t,e){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}var o=function(){function t(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return t.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},t.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r)}},t.prototype.get=function(t){return t in this.flags?this.flags[t]:(this.flags[t]=this.evaluateFlag(t),this.flags[t])},t.prototype.getNumber=function(t){return this.get(t)},t.prototype.getBool=function(t){return this.get(t)},t.prototype.getFlags=function(){return this.flags},Object.defineProperty(t.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),t.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)},t.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},t.prototype.setFlags=function(t){this.flags=Object.assign({},t)},t.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},t.prototype.populateURLFlags=function(){var t=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var e,n,r=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return a(n,e[0],e[1]),e.join("=")})),n);if("tfjsflags"in r)r.tfjsflags.split(",").forEach((function(e){var n=e.split(":"),r=n[0],o=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(r,o)}))}},t}();function a(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}function i(){return s}var s=null;var u=new Map,c=new Map;function l(t,e){var n=m(t,e);return u.get(n)}function h(t){return c.get(t)}function f(t){for(var e=u.entries(),n=[];;){var r=e.next(),o=r.done,a=r.value;if(o)break;var i=a[0],s=a[1];i.split("_")[0]===t&&n.push(s)}return n}function d(t){var e=t.kernelName,n=t.backendName,r=m(e,n);if(u.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");u.set(r,t)}function p(t){var e=t.kernelName;c.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),c.set(e,t)}function v(t,e){var n=m(t,e);if(!u.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is not registered");u.delete(n)}function g(t){if(!c.has(t))throw new Error("The gradient '"+t+"' for backend is not registered");c.delete(t)}function m(t,e){return e+"_"+t}function y(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function x(t,e,n){return Math.max(t,Math.min(e,n))}function b(t){return t%2==0?t:t+1}function w(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function C(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function E(t,e,n){void 0===n&&(n=""),C(S(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))}function R(t){C(null!=t,(function(){return"The input to the tensor constructor must be a non-null value."}))}function I(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||V(t)&&!n)for(var r=0;r<t.length;++r)I(t[r],e,n);else e.push(t);return e}function k(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function S(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function A(t){return t%1==0}function T(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function D(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function N(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function F(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise((function(r,o){var a=0,i=function(){if(t())r();else{a++;var s=e(a);null!=n&&a>=n?o():setTimeout(i,s)}};i()}))}function _(t,e){for(var n=1,r=-1,o=0;o<t.length;++o)if(t[o]>=0)n*=t[o];else if(-1===t[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o}else if(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);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 a=t.slice();return a[r]=e/n,a}function O(t,e){var n=e.length;return C((t=null==t?e.map((function(t,e){return e})):[].concat(t)).every((function(t){return t>=-n&&t<n})),(function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t})),C(t.every((function(t){return A(t)})),(function(){return"All values in axis param must be integers but got axis "+t})),t.map((function(t){return t<0?n+t:t}))}function M(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,a=null==e||o?null:O(e,t).sort(),i=0,s=0;s<t.length;++s){if(null!=a){if(a[i]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==a[i]||a[i]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[i]<=s&&i++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function B(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 P(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 L(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function W(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function U(t,e){return"complex64"!==e&&(("float32"!==e||"complex64"===t)&&(("int32"!==e||"float32"===t||"complex64"===t)&&("bool"!==e||"bool"!==t)))}function V(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function z(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function G(t){if(null==t)return 0;var e=0;return t.forEach((function(t){return e+=t.length})),e}function H(t){return"string"==typeof t||t instanceof String}function q(t){return"boolean"==typeof t}function K(t){return"number"==typeof t}function j(t){return Array.isArray(t)?j(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":K(t)?"float32":H(t)?"string":q(t)?"bool":"float32"}function X(t){return!!(t&&t.constructor&&t.call&&t.apply)}function Y(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function $(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}function Q(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=I(t)),n&&L(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),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+e)}function J(t,e){if(0===t.length)return e[0];var n=t.reduce((function(t,e){return t*e}));if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var o=new Array;if(1===n.length)for(var a=n[0],i=0;i<a;i++)o[i]=r[e+i];else{a=n[0];var s=n.slice(1),u=s.reduce((function(t,e){return t*e}));for(i=0;i<a;i++)o[i]=t(e+i*u,s,r)}return o}(0,t,e)}function Z(t,e){for(var n=tt(t,e),r=0;r<n.length;r++)n[r]=1;return n}function tt(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function et(){return i().platform.now()}function nt(t){t.forEach((function(e){C(Number.isInteger(e)&&e>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function rt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",i().platform.encode(t,e)}function ot(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",i().platform.decode(t,e)}function at(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var r=t[t.length-1],o=0;o<t.length-1;++o)r+=n[o]*t[o];return r}function it(t,e,n){if(0===e)return[];if(1===e)return[t];for(var r=new Array(e),o=0;o<r.length-1;++o)r[o]=Math.floor(t/n[o]),t-=r[o]*n[o];return r[r.length-1]=t,r}var st=Object.freeze({shuffle:y,clamp:x,nearestLargerEven:b,sum:w,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<t.length;r++){var o=Number(t[r])-Number(e[r]);n+=o*o}return n},assert:C,assertShapesMatch:E,assertNonNull:R,flatten:I,sizeFromShape:k,isScalarShape:function(t){return 0===t.length},arraysEqual:S,isInt:A,tanh:T,sizeToSquarishShape:D,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return y(e),e},rightPad:N,repeatedTry:F,inferFromImplicitShape:_,parseAxisParam:O,squeezeShape:M,getTypedArrayFromDType:B,getArrayFromDType:P,checkConversionForErrors:L,isValidDtype:W,hasEncodingLoss:U,isTypedArray:V,bytesPerElement:z,bytesFromStringArray:G,isString:H,isBoolean:q,isNumber:K,inferDtype:j,isFunction:X,nearestDivisor:Y,computeStrides:$,toTypedArray:Q,toNestedArray:J,makeOnesTypedArray:Z,makeZerosTypedArray:tt,now:et,assertNonNegativeIntegerDimensions:nt,fetch:function(t,e){return i().platform.fetch(t,e)},encodeString:rt,decodeString:ot,locToIndex:at,indexToLoc:it}),ut=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new ct)}return t.prototype.profileKernel=function(t,e,n){var r,o=this,a=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var o=t[r];if(isNaN(o)||!isFinite(o))return console.warn("Found "+o+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),a.then((function(a){var i="";null!=a.getExtraProfileInfo&&(i=a.getExtraProfileInfo()),o.logger.logKernelProfile(t,n,r,a.kernelMs,e,i)}))}))})),r},t}();var ct=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o,a){var i="number"==typeof r?N(r+"ms",9):r.error,s=N(t,25),u=e.rank,c=e.size,l=N(e.shape.toString(),14),h="";for(var f in o){var d=o[f].shape||e.shape,p=d.length;h+=f+": "+p+"D "+(p>0?d:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+h+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();var lt=20,ht=3,ft=7;function dt(t,e,n,r){var o=$(e),a=function(t,e,n,r){var o=k(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?gt(t):t;if(s>1)for(var c=0;c<o/a;c++)for(var l=c*a,h=0;h<a;h++)i[h]=Math.max(i[h],pt(u[l+h],0,n).length);return i}(t,e,n,o),i=e.length,s=function t(e,n,r,o,a,i){void 0===i&&(i=!0);var s="complex64"===r?2:1,u=n[0],c=n.length;if(0===c){return"complex64"===r?[pt(gt(e)[0],0,r)]:"bool"===r?[vt(e[0])]:[e[0].toString()]}if(1===c){if(u>lt){var l=ht*s,h=Array.from(e.slice(0,l)),f=Array.from(e.slice((u-ht)*s,u*s));return"complex64"===r&&(h=gt(h),f=gt(f)),["["+h.map((function(t,e){return pt(t,a[e],r)})).join(", ")+", ..., "+f.map((function(t,e){return pt(t,a[u-ht+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?gt(e):Array.from(e)).map((function(t,e){return pt(t,a[e],r)})).join(", ")+"]"]}var d=n.slice(1),p=o.slice(1),v=o[0]*s,g=[];if(u>lt){for(var m=0;m<ht;m++){var y=(x=m*v)+v;g.push.apply(g,t(e.slice(x,y),d,r,p,a,!1))}g.push("...");for(m=u-ht;m<u;m++){y=(x=m*v)+v;g.push.apply(g,t(e.slice(x,y),d,r,p,a,m===u-1))}}else for(m=0;m<u;m++){var x;y=(x=m*v)+v;g.push.apply(g,t(e.slice(x,y),d,r,p,a,m===u-1))}var b=2===c?",":"";g[0]="["+g[0]+b;for(m=1;m<g.length-1;m++)g[m]=" "+g[m]+b;var w=",\n";for(m=2;m<c;m++)w+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(i?"":w),g}(t,e,n,o,a),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+i),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map((function(t){return" "+t})).join("\n")),u.join("\n")}function pt(t,e,n){return N(Array.isArray(t)?parseFloat(t[0].toFixed(ft))+" + "+parseFloat(t[1].toFixed(ft))+"j":H(t)?"'"+t+"'":"bool"===n?vt(t):parseFloat(t.toFixed(ft)).toString(),e)}function vt(t){return 0===t?"false":"true"}function gt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var mt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=k(t),null!=n){var o=n.length;C(o===this.size,(function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+r.size+"'."}))}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||P(e,this.size),this.strides=$(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),C(n.length===this.rank,(function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"}));var o=this.locToIndex(n);this.values[o]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,o=t;r<o.length;r++){var a=o[r];if(a<0||a>=this.shape[n]){var i="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(i)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return yt().makeTensor(this.values,this.shape,this.dtype)},t}(),yt=null,xt=null,bt=null;var wt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=k(t),this.strides=$(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),C(1===this.size,(function(){return"The array must have only 1 element."})),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,o){return this.throwIfDisposed(),this.reshape([t,e,n,r,o])},t.prototype.asType=function(t){return this.throwIfDisposed(),xt.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return n(this,void 0,void 0,(function(){var t;return r(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,xt.buffer(this.shape,this.dtype,t)]}}))}))},t.prototype.bufferSync=function(){return xt.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return n(this,void 0,void 0,(function(){var t;return r(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,J(this.shape,t)]}}))}))},t.prototype.arraySync=function(){return J(this.shape,this.dataSync())},t.prototype.data=function(){return n(this,void 0,void 0,(function(){var t,e;return r(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=yt().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map((function(t){return ot(t)}))]}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}n.label=2;case 2:return[2,t]}}))}))},t.prototype.dataSync=function(){this.throwIfDisposed();var t=yt().readSync(this.dataId);if("string"===this.dtype)try{return t.map((function(t){return ot(t)}))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},t.prototype.bytes=function(){return n(this,void 0,void 0,(function(){var t;return r(this,(function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,yt().read(this.dataId)];case 1:return t=e.sent(),"string"===this.dtype?[2,t]:[2,new Uint8Array(t.buffer)]}}))}))},t.prototype.dispose=function(){this.isDisposed||(yt().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),xt.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),xt.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),xt.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),xt.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),xt.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),xt.clone(this)},t.prototype.toString=function(t){return void 0===t&&(t=!1),dt(this.dataSync(),this.shape,this.dtype,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),xt.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),xt.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),xt.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),xt.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),xt.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),xt.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),xt.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),xt.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),xt.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),xt.unstack(this,t)},t.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),bt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,o,r,n)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),xt.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),xt.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),xt.cast(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),xt.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),xt.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),xt.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),xt.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),xt.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),xt.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),xt.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),xt.mulStrict(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),xt.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),xt.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),xt.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),xt.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),xt.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),xt.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),xt.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),xt.modStrict(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),xt.squaredDifferenceStrict(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),xt.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),xt.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),xt.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),xt.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),xt.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),xt.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),xt.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),xt.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),xt.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),xt.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),xt.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),xt.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),xt.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),xt.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),xt.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),xt.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),xt.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),xt.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),xt.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),xt.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),xt.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),xt.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),xt.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),xt.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),xt.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),xt.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),xt.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),xt.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),xt.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),xt.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),xt.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),xt.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),xt.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),xt.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),xt.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),xt.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),xt.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),xt.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),xt.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),xt.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),xt.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),xt.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),xt.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),xt.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),xt.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),xt.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),xt.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),xt.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),xt.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),xt.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),xt.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),xt.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),xt.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),xt.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),xt.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),xt.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),xt.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),xt.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),xt.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),xt.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),xt.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),xt.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),xt.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),xt.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,o,a){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),xt.conv1d(this,t,e,n,r,o,a)},t.prototype.conv2d=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),xt.conv2d(this,t,e,n,r,o,a)},t.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),xt.conv2dTranspose(this,t,e,n,r,o)},t.prototype.depthwiseConv2D=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),xt.depthwiseConv2d(this,t,e,n,r,o,a)},t.prototype.separableConv2d=function(t,e,n,r,o,a){return void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC"),this.throwIfDisposed(),xt.separableConv2d(this,t,e,n,r,o,a)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),xt.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),xt.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),xt.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),xt.pool(this,t,e,n,r,o)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),yt().makeVariable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),xt.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),xt.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),xt.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),xt.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),xt.stridedSlice(this,t,e,n,r,o,a,i,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),xt.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),xt.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),xt.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),xt.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),xt.spectral.irfft(this)},t}();Object.defineProperty(wt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var Ct,Et,Rt,It,kt,St=function(t){function n(e,n,r,o){var a=t.call(this,e.shape,e.dtype,e.dataId,o)||this;return a.trainable=n,a.name=r,a}return e(n,t),n.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!S(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");yt().disposeTensor(this),this.dataId=t.dataId,yt().incRef(this,null)},n.prototype.dispose=function(){yt().disposeVariable(this),this.isDisposedInternal=!0},n}(wt);Object.defineProperty(St,Symbol.hasInstance,{value:function(t){return t instanceof wt&&null!=t.assign&&t.assign instanceof Function}}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(Ct||(Ct={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(Et||(Et={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(Rt||(Rt={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(It||(It={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(kt||(kt={}));var At={float32:It,int32:Et,bool:Rt,complex64:kt};function Tt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return At[t][e]}function Dt(t){return Tt(t,"int32")}function Nt(t,e){if(t.dtype===e.dtype)return[t,e];var n=Tt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Ft(t,e){C(t.dtype===e.dtype,(function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"}))}function _t(t){var e=[];return function t(e,n,r){if(null==e)return;if(e instanceof wt)return void n.push(e);if(o=e,!Array.isArray(o)&&"object"!=typeof o)return;var o;var a=e;for(var i in a){var s=a[i];r.has(s)||(r.add(s),t(s,n,r))}}(t,e,new Set),e}var Ot,Mt=Object.freeze({makeTypesMatch:Nt,assertTypesMatch:Ft,isTensorInList:function(t,e){return e.some((function(e){return e.id===t.id}))},getTensorsInContainer:_t}),Bt=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},t}(),Pt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Bt}return t.prototype.ready=function(){return n(this,void 0,void 0,(function(){var t,e,n;return r(this,(function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then((function(){}))];if(null!=this.backendInstance)return[2];t=this.getSortedBackends(),e=0,r.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}}))}))},Object.defineProperty(t.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");if(null==this.backendInstance){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");this.setBackend(e)}return this.backendInstance},enumerable:!0,configurable:!0}),t.prototype.backendNames=function(){return Object.keys(this.registryFactory)},t.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null}return this.registry[t]},t.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},t.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0)},t.prototype.setBackend=function(t){return n(this,void 0,void 0,(function(){var e,n,o;return r(this,(function(r){switch(r.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return o=r.sent(),[3,3];case 2:o=n,r.label=3;case 3:if(!o)return[2,!1];r.label=4;case 4:return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new ut(this.backendInstance),[2,!0]}}))}))},t.prototype.setupRegisteredKernels=function(){var t=this;f(this.backendName).forEach((function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)}))},t.prototype.disposeRegisteredKernels=function(t){var e=this;f(t).forEach((function(n){null!=n.disposeFunc&&n.disposeFunc(e.registry[t])}))},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var o=++this.pendingBackendInitId,a=r.then((function(n){return!(o<e.pendingBackendInitId)&&(e.registry[t]=n,e.pendingBackendInit=null,!0)})).catch((function(n){return!(o<e.pendingBackendInitId)&&(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),!1)}));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}return this.registry[t]=r,{success:!0,asyncInit:!1}}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1}}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority}))},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),o=r.success,a=r.asyncInit;if(a||o)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")},t.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),r=n.backend,o=this.readSync(e);r.disposeData(e),n.backend=t,t.move(e,o,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},t.prototype.tidy=function(t,e){var n,r=this,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t}return this.scopedRun((function(){return r.startScope(o)}),(function(){return r.endScope(n)}),(function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n}))},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.clone=function(t){var e=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],(function(t){return{x:function(){return t.toFloat()}}}),[],{}),e},t.prototype.runKernel=function(t,e,n,r,o){return this.runKernelFunc(null,e,null,t,n,r,o)},t.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},t.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),o=0;n.forEach((function(t){o+="complex64"===t.dtype?3:1}));var a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-e-o-a;if(i>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+i+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,o,a,i){var s,u=this,c=[],h=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var f,d=this.state.numBytes,p=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var v,g=l(r,this.backendName);if(null!=g)f=function(){var t=u.backend.numDataIds();v=g.kernelFunc({inputs:e,attrs:o,backend:u.backend});var n=Array.isArray(v)?v:[v];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,t,n);var s=n.map((function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)}));if(h){var l=u.getTensorsForGradient(r,e,s);if(null==l){null==i&&(i=[]);var f=s.filter((function(t,e){return i[e]}));l=(a||[]).slice().concat(f)}c=u.saveTensorsForBackwardMode(l)}return s};else{var m=function(t){h&&(c=t.map((function(t){return u.keep(u.clone(t))})))};f=function(){var e=u.backend.numDataIds();v=u.tidy((function(){return t(u.backend,m)}));var n=Array.isArray(v)?v:[v];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,e,n),n}}return this.scopedRun((function(){return u.state.kernelDepth++}),(function(){return u.state.kernelDepth--}),(function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(r,e,(function(){return f()})):f()})),h&&this.addTapeNode(r,e,s,n,c,o),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-d,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-p,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(t){return e[t].shape})),outputShapes:s.map((function(t){return t.shape}))}),Array.isArray(v)?s:s[0]},t.prototype.saveTensorsForBackwardMode=function(t){var e=this;return t.map((function(t){return e.keep(e.clone(t))}))},t.prototype.getTensorsForGradient=function(t,e,n){var r=h(t);if(null!=r){var o=r.inputsToSave||[],a=r.outputsToSave||[],i=void 0;r.saveAllInputs?(C(Array.isArray(e),(function(){return"saveAllInputs is true, expected inputs to be an array."})),i=Object.keys(e).map((function(t){return e[t]}))):i=o.map((function(t){return e[t]}));var s=n.filter((function(t,e){return a[e]}));return i.concat(s)}return null},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var o=t;"string"===n&&H(t[0])&&(o=t.map((function(t){return rt(t)})));var a=r.write(o,e,n),i=new wt(e,n,a,this.nextTensorId());if(this.incRef(i,r),"string"===n){var s=this.state.tensorInfo.get(a),u=G(o);this.state.numBytes+=u-s.bytes,s.bytes=u}return i},t.prototype.makeTensorFromDataId=function(t,e,n,r){var o=new wt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(o,r),o},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var o=new St(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[o.name])throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*z(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof St||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(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 n(this,void 0,void 0,(function(){var e,n;return r(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,r,o,a){var i=this,s={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:o},u=h(t);null!=u&&(r=u.gradFunc),null!=r&&(s.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],o=tt(r.size,r.dtype);return i.makeTensor(o,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],o,a)}),this.state.activeTape.push(s)},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=_t(t),r=new Set(n.map((function(t){return t.id}))),o=0;o<this.state.activeScope.track.length;o++){var a=this.state.activeScope.track[o];a.kept||r.has(a.id)||a.dispose()}var i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(t){t.kept||t.scopeId!==i.id||e.track(t)}))},t.prototype.gradients=function(t,e,n,r){var o=this;if(void 0===r&&(r=!1),C(e.length>0,(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 a=this.scopedRun((function(){return o.startTape()}),(function(){return o.endTape()}),(function(){return o.tidy("forward",t)}));C(a instanceof wt,(function(){return"The result y returned by f() must be a tensor."}));var i=function(t,e,n){for(var r={},o={},a=0;a<e.length;a++)r[e[a].id]=!0;for(a=0;a<t.length;a++){var i=(p=t[a]).inputs;for(var s in i){for(var u=i[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){p.outputs.forEach((function(t){return r[t.id]=!0})),c=!0,o[p.id]=!0;break}if(c)break}}var h={};h[n.id]=!0;var f={};for(a=t.length-1;a>=0;a--)for(i=(p=t[a]).inputs,l=0;l<p.outputs.length;l++)if(h[p.outputs[l].id]){for(var s in i)h[i[s].id]=!0,f[p.id]=!0;break}var d=[];for(a=0;a<t.length;a++){var p;if(o[(p=t[a]).id]&&f[p.id]){var v={};for(var s in p.inputs){var g=p.inputs[s];r[g.id]&&(v[s]=g)}var m=Object.assign({},p);m.inputs=v,m.outputs=p.outputs,d.push(m)}}return d}(this.state.activeTape,e,a);if(!r&&0===i.length&&e.length>0)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[a.id]=null==n?(t=a.shape,r=Z(k(t),"float32"),Lt.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach((function(e){var n=t[e.id];null!=n?a.push(n):a.push(null)})),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.kernelName+".");var i=o.gradient(a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n((function(){return i[e]()}));if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!S(r.shape,a.shape))throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,i,(function(t){return o.tidy(t)}));var u=e.map((function(t){return s[t.id]}));return 0===o.state.gradientDepth&&(o.state.activeTape.forEach((function(t){for(var e=0,n=t.saved;e<n.length;e++){n[e].dispose()}})),o.state.activeTape=null),{value:a,grads:u}}))},t.prototype.customGrad=function(t){var e=this;return C(X(t),(function(){return"The f passed in customGrad(f) must be a function."})),function(){for(var n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];C(r.every((function(t){return t instanceof wt})),(function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}));var a={};return r.forEach((function(t,e){a[e]=t})),e.runKernelFunc((function(e,o){return C((n=t.apply(void 0,r.concat([o]))).value instanceof wt,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),C(X(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),a,(function(t,e){var o=n.gradFunc(t,e),a=Array.isArray(o)?o:[o];C(a.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),C(a.every((function(t){return t instanceof wt})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var i={};return a.forEach((function(t,e){i[e]=function(){return t}})),i}))}},t.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t)},t.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t)},t.prototype.time=function(t){return n(this,void 0,void 0,(function(){var e,n;return r(this,(function(r){switch(r.label){case 0:return e=et(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=et()-e,[2,n]}}))}))},t.prototype.track=function(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t},Object.defineProperty(t.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),t.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Bt,this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},t.nextTensorId=0,t.nextVariableId=0,t}();var Lt=function(){var t=function(){if(null==Ot){var t=void 0;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else if("undefined"!=typeof process)t=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self}Ot=t}return Ot}();if(null==t._tfengine){var e=new o(t);t._tfengine=new Pt(e)}return function(t){s=t}(t._tfengine.ENV),yt=function(){return t._tfengine},t._tfengine}();function Wt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Ut=i();Ut.registerFlag("DEBUG",(function(){return!1}),(function(t){t&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),Ut.registerFlag("IS_BROWSER",(function(){return Wt()})),Ut.registerFlag("IS_NODE",(function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node})),Ut.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Ut.registerFlag("PROD",(function(){return!1})),Ut.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Ut.getBool("DEBUG")})),Ut.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Ut.registerFlag("IS_TEST",(function(){return!1}));var Vt,zt,Gt,Ht={},qt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Kt(t,e){Ht[t]=e}function jt(t){t in Ht||(Ht[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=function(t){if("undefined"!=typeof OffscreenCanvas&&2===t)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(t);if(e.addEventListener("webglcontextlost",(function(e){e.preventDefault(),delete Ht[t]}),!1),1===t)return e.getContext("webgl",qt)||e.getContext("experimental-webgl",qt);return e.getContext("webgl2",qt)}(t));var e=Ht[t];return e.isContextLost()?(delete Ht[t],jt(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Ht[t])}function Xt(t,e){return[e,t]}function Yt(t){var e=k(t);return D(Math.ceil(e/4))}function $t(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Qt(t,e){var n,r,o,a,s,u,c,l,h,f=t;return 2===i().getNumber("WEBGL_VERSION")?(n=f.R32F,r=f.R16F,o=f.RGBA16F,a=f.RGBA32F,s=f.RED,u=4,c=1,l=f.HALF_FLOAT,h=f.FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,a=f.RGBA,s=t.RGBA,u=4,c=4,l=null!=e?e.HALF_FLOAT_OES:null,h=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:s,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:l,textureTypeFloat:h}}function Jt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+ne(t,e))}(t),r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(Vt||(Vt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(zt||(zt={})),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"}(Gt||(Gt={}));var Zt=5.96e-8,te=65504;function ee(t){return!!(i().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Zt<Math.abs(t)&&Math.abs(t)<te)}function ne(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e}}function re(t,e,n){return ke(t,e,(function(){return t.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function oe(t,e,n){var r=ke(t,e,(function(){return t.createShader(t.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if(Jt(t,e,(function(){return t.shaderSource(r,n)})),Jt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function ae(t,e,n){var r=ke(t,e,(function(){return t.createShader(t.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if(Jt(t,e,(function(){return t.shaderSource(r,n)})),Jt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=ue.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],o=t.split("\n"),a=o.length.toString().length+2,i=o.map((function(t,e){return N((e+1).toString(),a)+t})),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var c=i.slice(0,r-1),l=i.slice(r-1,r),h=i.slice(r);console.log(c.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+N(l[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join("\n"))}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var ie,se,ue=/ERROR: [0-9]+:([0-9]+):/g;function ce(t,e){return ke(t,e,(function(){return t.createProgram()}),"Unable to create WebGLProgram.")}function le(t,e,n){if(Jt(t,e,(function(){return t.linkProgram(n)})),!1===t.getProgramParameter(n,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.")}function he(t,e,n){if(Jt(t,e,(function(){return t.validateProgram(n)})),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function fe(t,e,n){var r=ke(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),Jt(t,e,(function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function de(t,e,n){var r=ke(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Jt(t,e,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)})),Jt(t,e,(function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function pe(t,e){return ke(t,e,(function(){return t.createTexture()}),"Unable to create WebGLTexture.")}function ve(t,e){var n=i().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n){r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+("["+n+"x"+n+"]")+".")}}function ge(t,e){return ke(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function me(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,o)})),Jt(t,e,(function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)})),Jt(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function ye(t,e,n,r){Se(t,r),Jt(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function xe(t,e,n,r){return ke(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function be(t,e,n){return t.getUniformLocation(e,n)}function we(t,e,n,r,o,a){Jt(t,e,(function(){return ye(t,e,r,a)})),Jt(t,e,(function(){return t.uniform1i(o,a)}))}function Ce(t,e,n,r){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),Jt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function Ee(t,e,n){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),Jt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function Re(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ie(t,e))}function Ie(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 ke(t,e,n,r){var o=Jt(t,e,(function(){return n()}));if(null==o)throw new Error(r);return o}function Se(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+n+"]")+".")}function Ae(t,e){return void 0===e&&(e=2),k(t.slice(0,t.length-e))}function Te(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 De(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ae(t)].concat(Te(t))),e}function Ne(t,e){var n;void 0===e&&(e=!1);var r=i().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 o=M(t);t=o.newShape}var a=k(t);if(t.length<=1&&a<=r)return[1,a];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 s=Ae(t),u=2,c=2;return t.length&&(u=(n=Te(t))[0],c=n[1]),D(a=s*(u/2)*(c/2)).map((function(t){return 2*t}))}return D(a)}function Fe(t){return t%2==0}function _e(t,e){if(S(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(Fe(n)&&Fe(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Fe(t[0])&&Fe(e[0])}function Oe(t){if(null==ie){var e=jt(t);ie=e.getParameter(e.MAX_TEXTURE_SIZE)}return ie}function Me(t){if(null==se){var e=jt(t);se=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,se)}function Be(t){if(0===t)return 0;var e=jt(t);return Pe(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Pe(e,"EXT_disjoint_timer_query")?1:0}function Pe(t,e){return null!=t.getExtension(e)}function Le(t){try{if(null!=jt(t))return!0}catch(t){return!1}return!1}function We(t){if(0===t)return!1;var e=jt(t);if(1===t){if(!Pe(e,"OES_texture_float"))return!1}else if(!Pe(e,"EXT_color_buffer_float"))return!1;return Ve(e)}function Ue(t){if(0===t)return!1;var e=jt(t);if(1!==t){if(Pe(e,"EXT_color_buffer_float"))return Ve(e);if(Pe(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Qt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var o=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,o),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(o),a}(e,n)}return!1}return!!Pe(e,"OES_texture_float")&&(!!Pe(e,"WEBGL_color_buffer_float")&&Ve(e))}function Ve(t){var e=Qt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n);t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),o}function ze(t){return 2===t&&null!=jt(t).fenceSync}var Ge=Object.freeze({callAndCheck:Jt,canBeRepresented:ee,getWebGLErrorMessage:ne,getExtensionOrThrow:re,createVertexShader:oe,createFragmentShader:ae,createProgram:ce,linkProgram:le,validateProgram:he,createStaticVertexBuffer:fe,createStaticIndexBuffer:de,getNumChannels:function(){return 2===i().getNumber("WEBGL_VERSION")?1:4},createTexture:pe,validateTextureSize:ve,createFramebuffer:ge,bindVertexBufferToProgramAttribute:me,bindTextureUnit:ye,unbindTextureUnit:function(t,e,n){Se(t,n),Jt(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:xe,getProgramUniformLocation:be,bindTextureToProgramUniformSampler:we,bindCanvasToFramebuffer:function(t,e){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Jt(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),Jt(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:Ce,unbindColorTextureFromFramebuffer:Ee,validateFramebuffer:Re,getFramebufferErrorMessage:Ie,getBatchDim:Ae,getRowsCols:Te,getShapeAs3D:De,getTextureShapeFromLogicalShape:Ne,isReshapeFree:_e,getWebGLMaxTextureSize:Oe,resetMaxTextureSize:function(){ie=null},resetMaxTexturesInShader:function(){se=null},getMaxTexturesInShader:Me,getWebGLDisjointQueryTimerVersion:Be,hasExtension:Pe,isWebGLVersionEnabled:Le,isCapableOfRenderingToFloatTexture:We,isDownloadFloatTextureEnabled:Ue,isWebGLFenceEnabled:ze}),He=i();function qe(){i().set("PROD",!0)}function Ke(){i().set("DEBUG",!0)}function je(){i().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Xe(t){i().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ye(){Lt.disposeVariables()}function $e(){return Lt}function Qe(){return Lt.memory()}function Je(t){return Lt.profile(t)}function Ze(t,e){return Lt.tidy(t,e)}function tn(t){_t(t).forEach((function(t){return t.dispose()}))}function en(t){return Lt.keep(t)}function nn(t){return Lt.time(t)}function rn(t){return Lt.setBackend(t)}function on(){return Lt.ready()}function an(){return Lt.backendName}function sn(t){Lt.removeBackend(t)}function un(t){return Lt.findBackend(t)}function cn(t){return Lt.findBackendFactory(t)}function ln(t,e,n){return void 0===n&&(n=1),Lt.registerBackend(t,e,n)}function hn(){return Lt.backend}function fn(t,e){i().setPlatform(t,e)}function dn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];i().getBool("IS_TEST")||console.warn.apply(console,t)}function pn(t,e){var n=t;if(V(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||V(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&i().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],!Array.isArray(e)&&!V(e))return void C(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}));C(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),C(e.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"}));for(var o=n.slice(1),a=0;a<e.length;++a)t(e[a],o,r.concat(a))}(t,r,[]),r}function vn(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function gn(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof wt)return vn(r,t.dtype,e,n),t;var o=j(t);if("string"!==o&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),vn(r,o,e,n),null==t||!V(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var a=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+a+"'")}var s=pn(t,o);V(t)||Array.isArray(t)||(t=[t]);var u="string"!==o?Q(t,o,i().getBool("DEBUG")):I(t,[],!0);return Lt.makeTensor(u,s,o)}function mn(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 gn(t,e+"["+r+"]",n)}),r)}function yn(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function xn(t,e,n){for(var r=t.length+e.length,o=[],a=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(t[a++]):o.push(e[i++]);return o}function bn(t,e){for(var n=[],r=t.length,o=0;o<r;o++)-1===e.indexOf(o)&&n.push(t[o]);return[n,e.map((function(e){return t[e]}))]}function wn(t,e){return xn(t,e.map((function(t){return 1})),e)}function Cn(t,e,n){C(yn(e,n),(function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."}))}function En(t,e){if(yn(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach((function(t){return n.push(t)})),n}function Rn(t){return t.map((function(t,e){return[e,t]})).sort((function(t,e){return t[1]-e[1]})).map((function(t){return t[0]}))}function In(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function kn(t,e){var n=t[0].length;t.forEach((function(t,e){C(t.length===n,(function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"}))})),C(e>=0&&e<n,(function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."}));var r=t[0];t.forEach((function(t,o){for(var a=0;a<n;a++)C(a===e||t[a]===r[a],(function(){return"Error in concat"+n+"D: Shape of tensors["+o+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+o+"."}))}))}function Sn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function An(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var o=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Lt.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Lt.endScope(o),o}catch(t){throw Lt.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}He.registerFlag("HAS_WEBGL",(function(){return He.getNumber("WEBGL_VERSION")>0})),He.registerFlag("WEBGL_VERSION",(function(){return Le(2)?2:Le(1)?1:0})),He.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===He.get("WEBGL_VERSION")})),He.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),He.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),He.registerFlag("WEBGL_PACK",(function(){return He.getBool("HAS_WEBGL")})),He.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_CLIP",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),He.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_REDUCE",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_CONV_IM2COL",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Oe(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return Me(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=He.getNumber("WEBGL_VERSION");return 0===t?0:Be(t)})),He.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return He.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})),He.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return We(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!He.getBool("WEBGL_FORCE_F16_TEXTURES")&&He.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),He.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Ue(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return ze(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return He.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),bt=Xe;var Tn=An({complex_:function(t,e){var n=gn(t,"real","complex"),r=gn(e,"imag","complex");return E(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Lt.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),Dn=An({real_:function(t){var e=gn(t,"input","real");return Lt.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),Nn=An({imag_:function(t){var e=gn(t,"input","imag");return Lt.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function Fn(t,e,n){return _n(t,e,pn(t,n),n)}function _n(t,e,n,r){if(null==r&&(r=j(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!V(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){nt(e);var o=k(e),a=k(n);C(o===a,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+a}));for(var s=0;s<n.length;++s){var u=n[s],c=s!==n.length-1||u!==k(e.slice(s));C(n[s]===e[s]||!c,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "}))}}return V(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?Q(t,r,i().getBool("DEBUG")):I(t,[],!0),Lt.makeTensor(t,e,r)}function On(t,e){if((V(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&V(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return _n(t,[],[],e)}function Mn(t,e){R(t);var n=pn(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return _n(t,null,n,e)}function Bn(t,e,n){if(R(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=pn(t,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return _n(t,e,r,n)}function Pn(t,e,n){if(R(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=pn(t,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return _n(t,e,r,n)}function Ln(t,e,n){if(R(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=pn(t,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return _n(t,e,r,n)}function Wn(t,e,n){if(R(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=pn(t,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return _n(t,e,r,n)}function Un(t,e,n){if(R(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=pn(t,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return _n(t,e=e||r,r,n)}function Vn(t,e,n,r){return void 0===e&&(e=!0),Lt.makeVariable(t,e,n,r)}function zn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=zn(t,"float32"),r=Gn(t,"float32");return Tn(n,r)}var o=Z(k(t),e);return Lt.makeTensor(o,t,e)}function Gn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Gn(t,"float32"),r=Gn(t,"float32");return Tn(n,r)}var o=tt(k(t),e);return Lt.makeTensor(o,t,e)}function Hn(t,e,n){return Lt.runKernelFunc((function(r){return r.fill(t,e,n)}),{})}function qn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Lt.runKernelFunc((function(r){return r.linspace(t,e,n)}),{})}function Kn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return Gn([0],r);var o=tt(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+n;return Mn(o,r)}var jn=An({onesLike_:function(t){var e=gn(t,"x","onesLike");if("complex64"===e.dtype){var n=jn(Dn(e)),r=Xn(Nn(e));return Tn(n,r)}return Lt.runKernelFunc((function(t){return t.onesLike(e)}),{x:e},(function(t,e){return{x:function(){return Xn(t)}}}),"OnesLike")}}),Xn=An({zerosLike_:function(t){var e=gn(t,"x","zerosLike");return Lt.runKernelFunc((function(t){return t.zerosLike(e)}),{x:e},(function(t,e){return{x:function(){return Xn(t)}}}),"ZerosLike")}});var Yn=An({concat_:function(t,e){void 0===e&&(e=0),C(t.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=mn(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach((function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")})),e=O(e,n[0].shape)[0];var r=Sn(n.map((function(t){return t.shape})),e);if(0===k(r))return Fn([],r);if(1===(n=n.filter((function(t){return t.size>0}))).length)return n[0];var o=n.map((function(t){return t.shape}));kn(o,e);var a=n,i={axis:e};return Lt.runKernelFunc((function(t){return t.concat(n,e)}),a,(function(t){var n=o.map((function(t){return t[e]}));return tr(t,n,e).map((function(t){return function(){return t}}))}),"Concat",i)}}),$n=An({concat1d_:function(t){return Yn(t,0)}}),Qn=An({concat2d_:function(t,e){return Yn(t,e)}}),Jn=An({concat3d_:function(t,e){return Yn(t,e)}}),Zn=An({concat4d_:function(t,e){return Yn(t,e)}}),tr=An({split_:function(t,e,n){void 0===n&&(n=0);var r,o=gn(t,"x","split");return n=O(n,o.shape)[0],"number"==typeof e?(C(o.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(o.shape[n]/e)):(C(o.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),Lt.runKernelFunc((function(t){return t.split(o,r,n)}),{$x:o},(function(t){return{$x:function(){return Yn(t,n)}}}))}});function er(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",nt(t),new mt(t,e,n)}function nr(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var rr=An({batchToSpaceND_:function(t,e,n){var r=gn(t,"x","batchToSpaceND"),o=e.reduce((function(t,e){return t*e}));return C(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),C(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length})),C(r.shape[0]%o==0,(function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o})),Lt.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),or=An({cast_:function(t,e){var n=gn(t,"x","cast");if(!W(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");var r={dtype:e};return Lt.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),ar=An({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=gn(t,"x","cumsum"),a=En([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=In(1,o.rank)[0],u=Lt.runKernelFunc((function(t){return t.cumsum(i,s,n,r)}),{permutedX:i},(function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}}));return null!=a&&(u=u.transpose(a)),u}}),ir=An({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=gn(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return C(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})),C(a*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape})),C(i%(e*e)==0,(function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape})),Lt.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),sr=An({expandDims_:function(t,e){void 0===e&&(e=0);var n=gn(t,"x","expandDims",null);C(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(C(-(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),ur(n,r)}}),ur=An({reshape_:function(t,e){var n=gn(t,"x","reshape",null);e=_(e,n.size),C(n.size===k(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Lt.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),cr=An({spaceToBatchND_:function(t,e,n){var r=gn(t,"x","spaceToBatchND");return C(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),C(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),C(r.shape.reduce((function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t}),!0),(function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()})),Lt.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),lr=An({squeeze_:function(t,e){var n=gn(t,"x","squeeze");return ur(n,M(n.shape,e).newShape)}}),hr=An({stack_:function(t,e){void 0===e&&(e=0);var n=mn(t,"tensors","stack");if(C(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,o=n[0].shape,a=n[0].dtype;C(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){E(o,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){C(a===t.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var i=n.map((function(t){return t.expandDims(e)}));return Yn(i,e)}}),fr=An({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=gn(t,"x","unstack");C(e>=-n.shape.length&&e<n.shape.length,(function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")"})),e<0&&(e+=n.shape.length);var r={axis:e};return Lt.runKernelFunc((function(t){return t.unstack(n,e)}),{x:n},(function(t){return{x:function(){return hr(t,e)}}}),"Unpack",r)}}),dr=function(t,e){return n(this,void 0,void 0,(function(){var n,o,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return n=gn(t,"x","setdiff1d"),o=gn(e,"y","setdiff1d"),C(n.dtype===o.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+o.dtype+")."})),C(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),C(1===o.rank,(function(){return"y should be 1D tensor, but got y ("+o.shape+")."})),[4,n.data()];case 1:return a=r.sent(),[4,o.data()];case 2:for(i=r.sent(),s=new Set(i),u=0,h=0;h<a.length;h++)s.has(a[h])||u++;for(c=new mt([u],n.dtype),l=new mt([u],"int32"),h=0,f=0;h<a.length;h++)s.has(a[h])||(c.values[f]=a[h],l.values[f]=h,f++);return[2,[c.toTensor(),l.toTensor()]]}}))}))};function pr(t,e,n,r){void 0===r&&(r=!0);var o=[];if(r)(o=o.concat(e.slice(0))).push(t[0]/n),o=o.concat(t.slice(1));else{o=o.concat(t[0]);for(var a=e.length,i=0;i<a;++i)o=o.concat([t[i+1]/e[i],e[i]]);o=o.concat(t.slice(a+1))}return o}function vr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var o=e+1;o<t;++o)o<=2*e?(r.push(o),r.push(o-(e+1))):r.push(o)}else{var a=[],i=[];for(o=1;o<t;++o)o>=2*e+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i)}return r}function gr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;a<t.length;++a)a<=e.length?r?o.push(e[a-1]*t[a]):o.push(t[a]/e[a-1]):o.push(t[a]);return o}function mr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function yr(t,e,n){for(var r=t.slice(0,1),o=0;o<n;++o)r.push(t[o+1]-e[o][0]-e[o][1]);return r}var xr="Add",br="AddN",wr="Div",Cr="FusedBatchNorm",Er="SquaredDifference",Rr="Square",Ir="Transpose",kr="NonMaxSuppressionV5",Sr="BroadcastTo",Ar="OneHot",Tr="Identity",Dr="Tile",Nr="PadV2",Fr="FromPixels",_r="MaxPoolWithArgmax";var Or=An({add_:function(t,e){var n,r=gn(t,"a","add"),o=gn(e,"b","add");n=Nt(r,o),r=n[0],o=n[1];var a={a:r,b:o};return Lt.runKernelFunc((function(t,e){var n=t.add(r,o);return e([r,o]),n}),a,null,xr)}});function Mr(t,e){for(var n=t.length,r=[],o=0;o<n;o++){var a=n-1-o,i=t[a]||1;(e[e.length-1-o]||1)>1&&1===i&&r.unshift(a)}return r}function Br(t,e){for(var n=[],r=0;r<e.length;r++){var o=t[t.length-r-1],a=e.length-r-1,i=e[a];(null==o||1===o&&i>1)&&n.unshift(a)}return n}function Pr(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;o<r;o++){var a=t[t.length-o-1];null==a&&(a=1);var i=e[e.length-o-1];if(null==i&&(i=1),1===a)n.unshift(i);else if(1===i)n.unshift(a);else{if(a!==i)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(a)}}return n}var Lr=An({abs_:function(t){var e=gn(t,"x","abs");return"complex64"===e.dtype?Lt.runKernelFunc((function(t){return t.complexAbs(e)}),{$x:e}):Lt.runKernelFunc((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))}}}),"Abs")}}),Wr=An({acos_:function(t){var e=gn(t,"x","acos");return Lt.runKernelFunc((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(On(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),Ur=An({acosh_:function(t){var e=gn(t,"x","acosh");return Lt.runKernelFunc((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())}}}))}}),Vr=An({asin_:function(t){var e=gn(t,"x","asin");return Lt.runKernelFunc((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(On(1).sub(n.toFloat().square()).sqrt())}}}))}}),zr=An({asinh_:function(t){var e=gn(t,"x","asinh");return Lt.runKernelFunc((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(On(1).add(n.toFloat().square()).sqrt())}}}))}}),Gr=An({atan_:function(t){var e=gn(t,"x","atan");return Lt.runKernelFunc((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))}}}))}}),Hr=An({atanh_:function(t){var e=gn(t,"x","atanh");return Lt.runKernelFunc((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(On(1).sub(n.toFloat().square()))}}}))}}),qr=An({ceil_:function(t){var e=gn(t,"x","ceil");return Lt.runKernelFunc((function(t){return t.ceil(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Kr=An({clipByValue_:function(t,e,n){var r=gn(t,"x","clipByValue");C(e<=n,(function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}));var o=[r],a={min:e,max:n};return Lt.runKernelFunc((function(t,o){var a=t.clip(r,e,n);return o([r]),a}),{x:r},(function(t,r){var o=r[0];return{x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),Xn(t))}}}),"ClipByValue",a,o)}}),jr=An({cos_:function(t){var e=gn(t,"x","cos"),n=[e];return Lt.runKernelFunc((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)}}}),"Cos",{},n)}}),Xr=An({cosh_:function(t){var e=gn(t,"x","cosh");return Lt.runKernelFunc((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)}}}))}}),Yr=An({erf_:function(t){var e=gn(t,"x","erf");return C("int32"===e.dtype||"float32"===e.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===e.dtype&&(e=e.toFloat()),Lt.runKernelFunc((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)))}}}))}}),$r=An({exp_:function(t){var e=gn(t,"x","exp");return Lt.runKernelFunc((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])}}}),"Exp",{},[],[!0])}}),Qr=An({expm1_:function(t){var e=gn(t,"x","expm1");return Lt.runKernelFunc((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())}}}))}}),Jr=An({floor_:function(t){var e=gn(t,"x","floor");return Lt.runKernelFunc((function(t){return t.floor(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Zr=An({log_:function(t){var e=gn(t,"x","log"),n=[e];return Lt.runKernelFunc((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())}}}),"Log",{},n)}}),to=An({log1p_:function(t){var e=gn(t,"x","log1p");return Lt.runKernelFunc((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))}}}))}}),eo=An({logSigmoid_:function(t){var e=gn(t,"x","logSigmoid");return Lt.runKernelFunc((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())}}}))}}),no=An({neg_:function(t){var e=gn(t,"x","neg"),n=[e];return Lt.runKernelFunc((function(t){return t.neg(e)}),{x:e},(function(t){return{x:function(){return t.neg()}}}),"Neg",{},n)}}),ro=An({reciprocal_:function(t){var e=gn(t,"x","reciprocal");return Lt.runKernelFunc((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())}}}))}}),oo=An({round_:function(t){var e=gn(t,"x","round");return Lt.runKernelFunc((function(t){return t.round(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),ao=An({rsqrt_:function(t){var e=gn(t,"x","rsqrt"),n=[e];return Lt.runKernelFunc((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()}}}),"Rsqrt",{},n)}}),io=An({sigmoid_:function(t){var e=gn(t,"x","sigmoid");return Lt.runKernelFunc((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(On(1).sub(n)))}}}),"Sigmoid")}}),so=An({sign_:function(t){var e=gn(t,"x","sign");return Lt.runKernelFunc((function(t){return t.sign(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),uo=An({isNaN_:function(t){var e=gn(t,"x","isNaN");return Lt.runKernelFunc((function(t){return t.isNaN(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),co=An({isInf_:function(t){var e=gn(t,"x","isInf");return Lt.runKernelFunc((function(t){return t.isInf(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),lo=An({isFinite_:function(t){var e=gn(t,"x","isFinite");return Lt.runKernelFunc((function(t){return t.isFinite(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),ho=An({sin_:function(t){var e=gn(t,"x","sin"),n=[e];return Lt.runKernelFunc((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)}}}),"Sin",{},n)}}),fo=An({sinh_:function(t){var e=gn(t,"x","sinh");return Lt.runKernelFunc((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)}}}))}}),po=An({softplus_:function(t){var e=gn(t,"x","softplus");return Lt.runKernelFunc((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())}}}))}}),vo=An({sqrt_:function(t){var e=gn(t,"x","sqrt");return Lt.runKernelFunc((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))}}}))}}),go=An({step_:function(t,e){void 0===e&&(e=0);var n=gn(t,"x","step");return Lt.runKernelFunc((function(t){return t.step(n,e)}),{$x:n},(function(t){return{$x:function(){return Xn(t)}}}))}}),mo=An({tan_:function(t){var e=gn(t,"x","tan");return Lt.runKernelFunc((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())}}}))}}),yo=An({tanh_:function(t){var e=gn(t,"x","tanh");return Lt.runKernelFunc((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 On(1).sub(n.square()).mulStrict(t)}}}),"Tanh",{},null,[!0])}});var xo=An({addStrict_:function(t,e){var n=gn(t,"a","addStrict"),r=gn(e,"b","addStrict");return E(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),bo=An({atan2_:function(t,e){var n,r=gn(t,"a","atan2"),o=gn(e,"b","atan2");n=Nt(r,o),r=n[0],o=n[1];var a=Pr(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.atan2(r,o);return e([r,o]),n}),{$a:r,$b:o},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Or(n.square(),r.square()),o=t.mul(r.div(e)),i=Br(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$b:function(){var e=Or(n.square(),r.square()),o=no(t.mul(n.div(e))),i=Br(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}}))}}),wo=An({divStrict_:function(t,e){var n=gn(t,"a","div"),r=gn(e,"b","div");return E(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Co=An({floorDiv_:function(t,e){var n,r=gn(t,"a","floorDiv"),o=gn(e,"b","floorDiv");n=Nt(r,o),r=n[0],o=n[1];var a=Pr(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),o=Br(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Br(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"FloorDiv")}}),Eo=An({maximum_:function(t,e){var n,r=gn(t,"a","maximum"),o=gn(e,"b","maximum");return n=Nt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Pr(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.maximum(r,o);return e([r,o]),n}),{a:r,b:o},(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())}}}),"Maximum")}}),Ro=An({maximumStrict_:function(t,e){var n=gn(t,"a","maximumStrict"),r=gn(e,"b","maximumStrict");return E(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Io=An({minimum_:function(t,e){var n,r=gn(t,"a","minimum"),o=gn(e,"b","minimum");return n=Nt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Pr(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.minimum(r,o);return e([r,o]),n}),{a:r,b:o},(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())}}}),"Minimum")}}),ko=An({minimumStrict_:function(t,e){var n=gn(t,"a","minimumStrict"),r=gn(e,"b","minimumStrict");return E(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),So=An({mod_:function(t,e){var n,r=gn(t,"a","mod"),o=gn(e,"b","mod");n=Nt(r,o),r=n[0],o=n[1];var a=Pr(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.mod(r,o);return e([r,o]),n}),{$a:r,$b:o},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Br(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Br(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}}))}}),Ao=An({modStrict_:function(t,e){var n=gn(t,"a","modStrict"),r=gn(e,"b","modStrict");return E(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),To=An({mul_:function(t,e){var n,r=gn(t,"a","mul"),o=gn(e,"b","mul");n=Nt(r,o),r=n[0],o=n[1];var a=Pr(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.multiply(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.mul(r.toFloat()),o=Br(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Br(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}}),"Mul")}}),Do=An({mulStrict_:function(t,e){var n=gn(t,"a","mul"),r=gn(e,"b","mul");return E(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),No=An({pow_:function(t,e){var n,r=gn(t,"base","pow"),o=gn(e,"exp","pow");n=Nt(r,o),r=n[0],o=n[1];var a=Pr(r.shape,o.shape),i=[r,o];return Lt.runKernelFunc((function(t,e){var n=t.pow(r,o);return e([r,o,n]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1],o=e[2];return{a:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(On(1))))),i=Br(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},b:function(){var e=n.greater(0),i=n.log().where(e,Xn(n)),s=t.mul(o.mul(i)),u=Br(r.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}),"Pow",{},i,[!0])}}),Fo=An({powStrict_:function(t,e){return E(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),_o=An({squaredDifferenceStrict_:function(t,e){var n=gn(t,"a","squaredDifferenceStrict"),r=gn(e,"b","squaredDifferenceStrict");return E(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Oo=An({sub_:function(t,e){var n,r=gn(t,"a","sub"),o=gn(e,"b","sub");n=Nt(r,o),r=n[0],o=n[1];var a=Pr(r.shape,o.shape);return Lt.runKernelFunc((function(t){return t.subtract(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Br(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Br(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}}),"Sub")}}),Mo=An({subStrict_:function(t,e){var n=gn(t,"a","subStrict"),r=gn(e,"b","subStrict");return E(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var Bo=An({div_:function(t,e){var n,r=gn(t,"a","div"),o=gn(e,"b","div");if(n=Nt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return Co(r,o);var a={a:r,b:o};return Lt.runKernelFunc((function(t,e){var n=t.realDivide(r,o);return e([r,o]),n}),a,null,wr,{})}});function Po(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.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],o=1,a=0;a<n.length-1;++a)o*=n[a];var i=t.shape,s=n.slice();s.pop();var u=1;for(a=r;a<t.rank;++a)u*=i[a],s.push(i[a]);var c=$(t.shape).map((function(t){return t/u})).concat([1]).slice(0,r);return[s,o,u,c]}var Lo=Object.freeze({prepareAndValidate:Po}),Wo=30;function Uo(t){return t<=Wo?t:Y(t,Math.floor(Math.sqrt(t)))}function Vo(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rank<o)throw new Error(a+" update.rank < "+o+". ");if(t.length<r+(n.rank-o))throw new Error(a+" Output shape length < "+(r+(n.rank-o)));if(n.rank!==o+t.length-r)throw new Error(a+" update.rank != "+(o+t.length-r));for(var i=0;i<o;++i)if(n.shape[i]!==e.shape[i])throw new Error(a+" updates.shape["+i+"] ("+n.shape[i]+") != indices.shape["+i+"] ("+e.shape[i]+").");for(i=0;i<n.rank-o;++i)if(n.shape[i+o]!==t[i+r])throw new Error(a+" updates.shape["+(i+o)+"] ("+n.shape[i+o]+") != shape["+(i+o)+"] ("+t[i+o]+")")}function zo(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)}Vo(n,e,t)}function Go(t,e,n){for(var r=e.shape.length,o=r>1?e.shape[r-1]:1,a=n.length,i=1,s=o;s<a;++s)i*=n[s];var u=o<1?1:o;return{sliceRank:o,numUpdates:k(e.shape)/u,sliceSize:i,strides:$(n.slice(0,o)).concat([1]),outputSize:k(n)}}var Ho=Object.freeze({validateUpdateShape:Vo,validateInput:zo,calculateShapes:Go});function qo(t,e,n){C(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+")."})),C(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){C(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]+")"}))},o=0;o<t.rank;++o)r(o)}function Ko(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function jo(t,e,n){for(var r=[],o=0;o<t.length;o++)r[o]=Math.ceil((e[o]-t[o])/n[o]);return r}function Xo(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=x(0,a,s-1)}function Yo(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=i>0?x(0,a,s):x(-1,a,s-1)}function $o(t,e,n){for(var r=n.length,o=0;o<n.length;o++)if(n[o]>1){r=o;break}for(o=r+1;o<n.length;o++)if(e[o]>0||n[o]!==t[o])return!1;return!0}function Qo(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}var Jo=Object.freeze({assertParamsValid:qo,maskToAxes:Ko,computeOutShape:jo,startForAxis:Xo,stopForAxis:Yo,isSliceContinous:$o,computeFlatOffset:Qo});function Zo(t){return C(X(t),(function(){return"The f passed in grad(f) must be a function"})),function(e,n){var r=gn(e,"x","tf.grad",null),o=null!=n?gn(n,"dy","tf.grad"):null;return Lt.tidy((function(){var e=Lt.gradients((function(){return t(r)}),[r],o),n=e.value,a=e.grads;return null!=o&&E(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),aa(a),a[0]}))}}function ta(t){return C(X(t),(function(){return"The f passed in grads(f) must be a function"})),function(e,n){C(Array.isArray(e),(function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"}));var r=mn(e,"args","tf.grads",null),o=null!=n?gn(n,"dy","tf.grads"):null;return Lt.tidy((function(){var e=Lt.gradients((function(){return t.apply(void 0,r)}),r,o),n=e.value,a=e.grads;return null!=o&&E(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),aa(a),a}))}}function ea(t){return C(X(t),(function(){return"The f passed in valueAndGrad(f) must be a function"})),function(e,n){C(e instanceof wt,(function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"})),C(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"}));var r=Lt.gradients((function(){return t(e)}),[e],n),o=r.grads,a=r.value;return aa(o),{grad:o[0],value:a}}}function na(t){return C(X(t),(function(){return"The f passed in valueAndGrads(f) must be a function"})),function(e,n){C(Array.isArray(e)&&e.every((function(t){return t instanceof wt})),(function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"})),C(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"}));var r=Lt.gradients((function(){return t.apply(void 0,e)}),e,n);return null!=n&&E(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),aa(r.grads),r}}function ra(t,e){C(X(t),(function(){return"The f passed in variableGrads(f) must be a function"})),C(null==e||Array.isArray(e)&&e.every((function(t){return t instanceof St})),(function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}));var n=null!=e;if(!n)for(var r in e=[],Lt.registeredVariables)e.push(Lt.registeredVariables[r]);var o=n?e.filter((function(t){return!t.trainable})):null,a=e.length;C((e=e.filter((function(t){return t.trainable}))).length>0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."}));var i=Lt.gradients(t,e,null,!0),s=i.value,u=i.grads;C(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()."})),C(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!=o&&o.forEach((function(t){return c[t.name]=null})),{value:s,grads:c}}function oa(t){return Lt.customGrad(t)}function aa(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 ia=An({softmax_:function(t,e){void 0===e&&(e=-1);var n=gn(t,"logits","softmax","float32");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 Lt.runKernelFunc((function(t,r){var o=t.softmax(n,e);return r([o]),o}),{logits:n},(function(t,n){var r=n[0],o=t.mul(r);return{logits:function(){return o.sub(o.sum([e],!0).mul(r))}}}),"Softmax",{dim:e},[],[!0])}}),sa=An({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=gn(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 oa((function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());n([a]);return{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}});var ua=An({transpose_:function(t,e){var n=gn(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),C(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){C(t>=0&&t<n.rank,(function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e}))})),n.rank<=1)return n.clone();var r={perm:e};return Lt.runKernelFunc((function(t){return t.transpose(n,e)}),{x:n},null,"Transpose",r)}}),ca=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}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.dataIdsCount++,this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),la=function(){function t(){}return t.prototype.time=function(t){return ha("time")},t.prototype.read=function(t){return ha("read")},t.prototype.readSync=function(t){return ha("readSync")},t.prototype.numDataIds=function(){return ha("numDataIds")},t.prototype.disposeData=function(t){return ha("disposeData")},t.prototype.write=function(t,e,n){return ha("write")},t.prototype.move=function(t,e,n,r){return ha("move")},t.prototype.memory=function(){return ha("memory")},t.prototype.floatPrecision=function(){return ha("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return ha("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights;return ha("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return ha("slice")},t.prototype.stridedSlice=function(t,e,n,r){return ha("stridedSlice")},t.prototype.unstack=function(t,e){return ha("unstack")},t.prototype.reverse=function(t,e){return ha("reverse")},t.prototype.concat=function(t,e){return ha("concat")},t.prototype.neg=function(t){return ha("neg")},t.prototype.add=function(t,e){return ha("add")},t.prototype.addN=function(t){return ha("addN")},t.prototype.subtract=function(t,e){return ha("subtract")},t.prototype.multiply=function(t,e){return ha("multiply")},t.prototype.realDivide=function(t,e){return ha("realDivide")},t.prototype.floorDiv=function(t,e){return ha("floorDiv")},t.prototype.sum=function(t,e){return ha("sum")},t.prototype.prod=function(t,e){return ha("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return ha("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return ha("argMin")},t.prototype.argMax=function(t,e){return ha("argMax")},t.prototype.equal=function(t,e){return ha("equal")},t.prototype.notEqual=function(t,e){return ha("notEqual")},t.prototype.less=function(t,e){return ha("less")},t.prototype.lessEqual=function(t,e){return ha("lessEqual")},t.prototype.greater=function(t,e){return ha("greater")},t.prototype.greaterEqual=function(t,e){return ha("greaterEqual")},t.prototype.logicalNot=function(t){return ha("logicalNot")},t.prototype.logicalAnd=function(t,e){return ha("logicalAnd")},t.prototype.logicalOr=function(t,e){return ha("logicalOr")},t.prototype.where=function(t){return ha("where")},t.prototype.select=function(t,e,n){return ha("select")},t.prototype.topk=function(t,e,n){return ha("topk")},t.prototype.min=function(t,e){return ha("min")},t.prototype.minimum=function(t,e){return ha("minimum")},t.prototype.mod=function(t,e){return ha("mod")},t.prototype.max=function(t,e){return ha("max")},t.prototype.maximum=function(t,e){return ha("maximum")},t.prototype.all=function(t,e){return ha("all")},t.prototype.any=function(t,e){return ha("any")},t.prototype.squaredDifference=function(t,e){return ha("squaredDifference")},t.prototype.ceil=function(t){return ha("ceil")},t.prototype.floor=function(t){return ha("floor")},t.prototype.round=function(t){return ha("round")},t.prototype.sign=function(t){return ha("sign")},t.prototype.isNaN=function(t){return ha("isNaN")},t.prototype.isInf=function(t){return ha("isInf")},t.prototype.isFinite=function(t){return ha("isFinite")},t.prototype.pow=function(t,e){return ha("pow")},t.prototype.exp=function(t){return ha("exp")},t.prototype.expm1=function(t){return ha("expm1")},t.prototype.softmax=function(t,e){return ha("softmax")},t.prototype.log=function(t){return ha("log")},t.prototype.log1p=function(t){return ha("log1p")},t.prototype.sqrt=function(t){return ha("sqrt")},t.prototype.rsqrt=function(t){return ha("rsqrt")},t.prototype.square=function(t){return ha("square")},t.prototype.reciprocal=function(t){return ha("reciprocal")},t.prototype.relu=function(t){return ha("relu")},t.prototype.relu6=function(t){return ha("relu6")},t.prototype.prelu=function(t,e){return ha("prelu")},t.prototype.elu=function(t){return ha("elu")},t.prototype.eluDer=function(t,e){return ha("eluDer")},t.prototype.selu=function(t){return ha("selu")},t.prototype.int=function(t){return ha("int")},t.prototype.clip=function(t,e,n){return ha("clip")},t.prototype.abs=function(t){return ha("abs")},t.prototype.complexAbs=function(t){return ha("complexAbs")},t.prototype.sigmoid=function(t){return ha("sigmoid")},t.prototype.softplus=function(t){return ha("softplus")},t.prototype.sin=function(t){return ha("sin")},t.prototype.cos=function(t){return ha("cos")},t.prototype.tan=function(t){return ha("tan")},t.prototype.asin=function(t){return ha("asin")},t.prototype.acos=function(t){return ha("acos")},t.prototype.atan=function(t){return ha("atan")},t.prototype.atan2=function(t,e){return ha("atan2")},t.prototype.sinh=function(t){return ha("sinh")},t.prototype.cosh=function(t){return ha("cosh")},t.prototype.tanh=function(t){return ha("tanh")},t.prototype.asinh=function(t){return ha("asinh")},t.prototype.acosh=function(t){return ha("acosh")},t.prototype.atanh=function(t){return ha("atanh")},t.prototype.erf=function(t){return ha("erf")},t.prototype.step=function(t,e){return ha("step")},t.prototype.fusedConv2d=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;return ha("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return ha("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return ha("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return ha("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;return ha("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return ha("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return ha("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return ha("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return ha("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return ha("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return ha("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return ha("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return ha("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return ha("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return ha("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return ha("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return ha("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return ha("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return ha("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return ha("reshape")},t.prototype.cast=function(t,e){return ha("cast")},t.prototype.tile=function(t,e){return ha("tile")},t.prototype.pad=function(t,e,n){return ha("pad")},t.prototype.transpose=function(t,e){return ha("transpose")},t.prototype.gather=function(t,e,n){return ha("gather")},t.prototype.gatherND=function(t,e){return ha("gatherND")},t.prototype.scatterND=function(t,e,n){return ha("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return ha("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return ha("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return ha("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return ha("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return ha("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return ha("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,o,a){return ha("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){return ha("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){return ha("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return ha("multinomial")},t.prototype.oneHot=function(t,e,n,r){return ha("oneHot")},t.prototype.cumsum=function(t,e,n,r){return ha("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return ha("nonMaxSuppression")},t.prototype.fft=function(t){return ha("fft")},t.prototype.ifft=function(t){return ha("ifft")},t.prototype.complex=function(t,e){return ha("complex")},t.prototype.real=function(t){return ha("real")},t.prototype.imag=function(t){return ha("imag")},t.prototype.cropAndResize=function(t,e,n,r,o,a){return ha("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return ha("depthToSpace")},t.prototype.split=function(t,e,n){return ha("split")},t.prototype.sparseToDense=function(t,e,n,r){return ha("sparseToDense")},t.prototype.diag=function(t){return ha("diag")},t.prototype.fill=function(t,e,n){return ha("fill")},t.prototype.onesLike=function(t){return ha("onesLike")},t.prototype.zerosLike=function(t){return ha("zerosLike")},t.prototype.linspace=function(t,e,n){return ha("linspace")},t.prototype.dispose=function(){return ha("dispose")},t}();function ha(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function fa(t,e,n,r,o,a,i){void 0===i&&(i="channelsLast");var s,u=ma(e),c=u[0],l=u[1];if("channelsLast"===i)s=[c,l,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[c,l,t[1],t[1]]}return pa(t,s,n,r,o,a,!1,i)}function da(t,e,n,r,o,a,i){void 0===i&&(i="NDHWC");var s,u,c=ya(e),l=c[0],h=c[1],f=c[2];if("NDHWC"===i)u="channelsLast",s=[l,h,f,t[4],t[4]];else{if("NCDHW"!==i)throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[l,h,f,t[1],t[1]]}return va(t,s,n,r,o,!1,u,a)}function pa(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3];if("channelsLast"===s)c=t[0],l=t[1],h=t[2],f=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);c=t[0],f=t[1],l=t[2],h=t[3]}var d,p=e[0],v=e[1],g=e[3],m=ma(n),y=m[0],x=m[1],b=ma(r),w=b[0],E=b[1],R=xa(p,w),I=xa(v,E),k=function(t,e,n,r,o,a,i,s){var u,c,l;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var h=function(t,e,n,r,o){null==r&&(r=ga(t,e,n));var a=t[0],i=t[1],s=ba((a-e+2*r)/n+1,o);C(A(s),(function(){return"The output # of rows ("+s+") must be an integer. Change the stride and/or zero pad parameters"}));var u=ba((i-e+2*r)/n+1,o);return C(A(u),(function(){return"The output # of columns ("+u+") must be an integer. Change the stride and/or zero pad parameters"})),[s,u]}([e,n],a,r,t,s);c=h[0],l=h[1]}else if("same"===t){c=Math.ceil(e/r),l=Math.ceil(n/o);var f=Math.max(0,(c-1)*r+a-e),d=Math.max(0,(l-1)*o+i-n),p=Math.floor(f/2),v=f-p,g=Math.floor(d/2);u={top:p,bottom:v,left:g,right:d-g,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-a+1)/r),l=Math.ceil((n-i+1)/o)}return{padInfo:u,outHeight:c,outWidth:l}}(o,l,h,y,x,R,I,a),S=k.padInfo,T=k.outHeight,D=k.outWidth,N=i?g*f:g;return"channelsFirst"===s?d=[c,N,T,D]:"channelsLast"===s&&(d=[c,T,D,N]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:h,inChannels:f,outHeight:T,outWidth:D,outChannels:N,padInfo:S,strideHeight:y,strideWidth:x,filterHeight:p,filterWidth:v,effectiveFilterHeight:R,effectiveFilterWidth:I,dilationHeight:w,dilationWidth:E,inShape:t,outShape:d,filterShape:e}}function va(t,e,n,r,o,a,i,s){void 0===a&&(a=!1),void 0===i&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3],d=u[4];if("channelsLast"===i)c=t[0],l=t[1],h=t[2],f=t[3],d=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);c=t[0],d=t[1],l=t[2],h=t[3],f=t[4]}var p,v=e[0],g=e[1],m=e[2],y=e[4],x=ya(n),b=x[0],w=x[1],E=x[2],R=ya(r),I=R[0],k=R[1],S=R[2],T=xa(v,I),D=xa(g,k),N=xa(m,S),F=function(t,e,n,r,o,a,i,s,u,c,l){var h,f,d,p;if("number"==typeof t){h={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var v=function(t,e,n,r,o,a){null==o&&(o=ga(t,e,r));var i=t[0],s=t[1],u=t[2],c=ba((i-e+2*o)/r+1,a);C(A(c),(function(){return"The output # of depths ("+c+") must be an integer. Change the stride and/or zero pad parameters"}));var l=ba((s-e+2*o)/r+1,a);C(A(l),(function(){return"The output # of rows ("+l+") must be an integer. Change the stride and/or zero pad parameters"}));var h=ba((u-e+2*o)/r+1,a);return C(A(h),(function(){return"The output # of columns ("+h+") must be an integer. Change the stride and/or zero pad parameters"})),[c,l,h,n]}([e,n,r,1],s,1,o,t,l);f=v[0],d=v[1],p=v[2]}else if("same"===t){f=Math.ceil(e/o),d=Math.ceil(n/a),p=Math.ceil(r/i);var g=(f-1)*o+s-e,m=(d-1)*a+u-n,y=(p-1)*i+c-r,x=Math.floor(g/2),b=g-x,w=Math.floor(m/2),E=m-w,R=Math.floor(y/2);h={top:w,bottom:E,left:R,right:y-R,front:x,back:b,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},f=Math.ceil((e-s+1)/o),d=Math.ceil((n-u+1)/a),p=Math.ceil((r-c+1)/i)}return{padInfo:h,outDepth:f,outHeight:d,outWidth:p}}(o,l,h,f,b,w,E,T,D,N,s),_=F.padInfo,O=F.outDepth,M=F.outHeight,B=F.outWidth,P=a?y*d:y;return"channelsFirst"===i?p=[c,P,O,M,B]:"channelsLast"===i&&(p=[c,O,M,B,P]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:h,inWidth:f,inChannels:d,outDepth:O,outHeight:M,outWidth:B,outChannels:P,padInfo:_,strideDepth:b,strideHeight:w,strideWidth:E,filterDepth:v,filterHeight:g,filterWidth:m,effectiveFilterDepth:T,effectiveFilterHeight:D,effectiveFilterWidth:N,dilationDepth:I,dilationHeight:k,dilationWidth:S,inShape:t,outShape:p,filterShape:e}}function ga(t,e,n,r){void 0===r&&(r=1);var o=xa(e,r);return Math.floor((t[0]*(n-1)-n+o)/2)}function ma(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function ya(t){return"number"==typeof t?[t,t,t]:t}function xa(t,e){return e<=1?t:t+(t-1)*(e-1)}function ba(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e)}}function wa(t){var e=ma(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Ca(t,e){return wa(t)||wa(e)}function Ea(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function Ra(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=Gn(t.shape),o=t.toFloat(),a=n.complex(o,r);return r.dispose(),o.dispose(),a}if(!U(t.dtype,e))return Lt.makeTensorFromDataId(t.dataId,t.shape,e);if("complex64"===t.dtype){var i=n.real(t);a=i.cast(e);return i.dispose(),a}if("int32"===e)return n.int(t);if("bool"===e){var s=On(0,t.dtype);a=n.notEqual(t,s);return s.dispose(),a}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function Ia(t,e){return Lt.makeTensorFromDataId(t.dataId,e,t.dtype)}function ka(t,e,n){var r=(e-t)/(n-1),o=tt(n,"float32");o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+r;return Mn(o,"float32")}var Sa=Object.freeze({castTensor:Ra,reshapeTensor:Ia,linspaceImpl:ka,upcastType:Tt,axesAreInnerMostDims:yn,combineLocations:xn,computeOutAndReduceShapes:bn,expandShapeToKeepDim:wn,assertAxesAreInnerMostDims:Cn,getAxesPermutation:En,getUndoAxesPermutation:Rn,getInnerMostAxes:In,getBroadcastDims:Mr,getReductionAxes:Br,assertAndGetBroadcastShape:Pr,assertParamsConsistent:kn,computeOutShape:Sn,computePool2DInfo:fa,computePool3DInfo:da,computeConv2DInfo:pa,computeConv3DInfo:va,computeDefaultPad:ga,tupleValuesAreOne:wa,eitherStridesOrDilationsAreOne:Ca,convertConv2DDataFormat:Ea,PARALLELIZE_THRESHOLD:Wo,computeOptimalWindowSize:Uo});function Aa(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n}function Ta(t,e){return{real:t[2*e],imag:t[2*e+1]}}function Da(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function Na(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function Fa(t,e,n){var r=function(t,e,n){return function(t,e,n){var r=0,o=t.length,a=0,i=!1;for(;r<o;){var s=n(e,t[a=r+(o-r>>>1)]);s>0?r=a+1:(o=a,i=!s)}return i?r:-r-1}(t,e,n||_a)}(t,e,n),o=r<0?-(r+1):r;t.splice(o,0,e)}function _a(t,e){return t>e?1:t<e?-1:0}function Oa(t,e,n,r,o){return Ba(t,e,n,r,o,0).selectedIndices}function Ma(t,e,n,r,o,a){var i=Ba(t,e,n,r,o,a,!0);return i.numValidOutputs.dispose(),{selectedIndices:i.selectedIndices,selectedScores:i.selectedScores}}function Ba(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1);for(var u=Array.from(e).map((function(t,e){return{score:t,boxIndex:e,suppressBeginIndex:0}})).filter((function(t){return t.score>o})).sort(Wa),c=a>0?-.5/a:0,l=[],h=[];l.length<n&&u.length>0;){var f=u.pop(),d=f.score,p=f.boxIndex,v=f.suppressBeginIndex;if(d<o)break;for(var g=!1,m=l.length-1;m>=v;--m){var y=Pa(t,p,l[m]);if(y>=r){g=!0;break}if(f.score=f.score*La(r,c,y),f.score<=o)break}f.suppressBeginIndex=l.length,g||(f.score===d?(l.push(p),h.push(f.score)):f.score>o&&Fa(u,f,Wa))}var x=l.length;return s&&(l.fill(0,x),h.fill(0,x)),{selectedIndices:Mn(l,"int32"),selectedScores:Mn(h,"float32"),numValidOutputs:On(x,"int32")}}function Pa(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),f=Math.max(o[1],o[3]),d=(s-a)*(u-i),p=(h-c)*(f-l);if(d<=0||p<=0)return 0;var v=Math.max(a,c),g=Math.max(i,l),m=Math.min(s,h),y=Math.min(u,f),x=Math.max(m-v,0)*Math.max(y-g,0);return x/(d+p-x)}function La(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function Wa(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function Ua(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map((function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a}))}function Va(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=er(n,t.dtype);for(r=0;r<o.values.length;++r){for(var a=o.indexToLoc(r),i=new Array(t.rank),s=0;s<i.length;s++)i[s]=a[s]%t.shape[s];var u=t.locToIndex(i);o.values[r]=t.values[u]}return o.toTensor()}function za(t,e,n,r,o){for(var a=e[e.length-1],i=[t.length/a,a],s=i[0],u=i[1],c=B(n,s*r),l=B("int32",s*r),h=0;h<s;h++){for(var f=h*u,d=t.subarray(f,f+u),p=[],v=0;v<d.length;v++)p.push({value:d[v],index:v});p.sort((function(t,e){return e.value-t.value}));var g=h*r,m=c.subarray(g,g+r),y=l.subarray(g,g+r);for(v=0;v<r;v++)m[v]=p[v].value,y[v]=p[v].index}var x=e.slice();return x[x.length-1]=r,[Fn(c,x,n),Fn(l,x,"int32")]}function Ga(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=er(t,"int32"),a=er([n.length,t.length],"int32");for(r=0;r<n.length;r++){var i=o.indexToLoc(n[r]),s=r*t.length;a.values.set(i,s)}return a.toTensor()}var Ha=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 "},qa=function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!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 "},Ka=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,o=t.batchSize,a=t.inSize,i=Math.ceil(a/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[o,i];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 "};function ja(t,e){return["x","y","z","w","u","v"].slice(0,e).map((function(e){return t+"."+e}))}function Xa(t,e){return 1===e?[t]:ja(t,e)}function Ya(){var t,e,n,r,o,a,s,u,c,l;return 2===i().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",a="outputColor",s="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",c="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",o="texture2D",a="gl_FragColor",s="",u="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",c="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:a,defineOutput:s,defineSpecialNaN:u,defineSpecialInf:c,defineRound:l}}function $a(t,e,n){void 0===n&&(n="index");var r=$(e);return r.map((function(e,o){return"int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";"})).join("")}function Qa(t){var e=$(t).map((function(t){return t.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var Ja="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function Za(t,e,n,r){var o=[];t.forEach((function(t){var e=k(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"))}));var a,i,s=o.join("\n"),u=t.map((function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?ei(t):ti(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=Mr(t.shapeInfo.logicalShape,e.logicalShape),c=ui(s),l=s-i,h=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map((function(t){return"coords."+h[t+l]+" = 0;"})).join("\n");var f="";f=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+l]})).join(", ");var d="return outputValue;",p=1===k(t.shapeInfo.logicalShape),v=1===k(e.logicalShape);if(1!==i||p||v){if(p&&!v)d=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var g=i-2,m=i-1;u.indexOf(g)>-1&&u.indexOf(m)>-1?d="return vec4(outputValue.x);":u.indexOf(g)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(m)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+f+");\n "+d+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&S(i,a))return"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var c,l=ui(u),h=Mr(t.shapeInfo.logicalShape,e.logicalShape),f=u-s,d=["x","y","z","w","u","v"];c=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map((function(t){return"coords."+d[t+f]+" = 0;"})).join("\n");var p="";p=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+d[e+f]})).join(", ");return"\n float "+o+"() {\n "+l+" coords = getOutputCoords();\n "+c+"\n return get"+r+"("+p+");\n }\n "}(t,e));return r}(t,e,r)})).join("\n"),c=e.texShape,l=Ya(),h=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(l),f=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 "+t.defineSpecialNaN+"\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 "+ni+"\n "+ri+"\n "+oi+"\n "}(l);return e.isPacked?(a=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)];if(1===n[0])return"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ";if(1===n[1])return"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ";return"\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(S(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,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Math.ceil(n[2]/2),i=a*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+o[0]+", "+o[1]+"));\n int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 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),o=r*Math.ceil(t[t.length-2]/2),a=o,i="",s="b, r, c",u=2;u<t.length-1;u++)a*=t[t.length-u-1],i="\n int b"+u+" = index / "+a+";\n index -= b"+u+" * "+a+";\n "+i,s="b"+u+", "+s;return"\n ivec"+t.length+" getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n "+i+"\n\n int b = index / "+o+";\n index -= b * "+o+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec"+t.length+"("+s+");\n }\n "}(t,e)}var n,r,o,a,i}(e.logicalShape,c),i=function(t){return"\n void setOutput(vec4 val) {\n "+t.output+" = val;\n }\n "}(l)):(a=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){if(1===e[0])return"\n int getOutputCoords() {\n return int(resultUV.x * "+e[1]+".0);\n }\n ";if(1===e[1])return"\n int getOutputCoords() {\n return int(resultUV.y * "+e[0]+".0);\n }\n ";return"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n return resTexRC.x * "+e[1]+" + resTexRC.y;\n }\n "}(0,e);case 2:return function(t,e){if(S(t,e))return"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n }\n ";if(1===t[1])return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ";if(1===t[0])return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ";return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n int r = index / "+t[1]+";\n int c = index - r * "+t[1]+";\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=e,r=$a(["r","c","d"],t),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n "+r+"\n return ivec3(r, c, d);\n }\n ";case 4:return function(t,e){var n=$a(["r","c","d","d2"],t);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n "+n+"\n return ivec4(r, c, d, d2);\n }\n "}(t,e);case 5:return function(t,e){var n=$a(["r","c","d","d2","d3"],t);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n "+e[1]+"));\n\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(t,e);case 6:return function(t,e){var n=$a(["r","c","d","d2","d3","d4"],t);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}var n,r}(e.logicalShape,c),i=function(t){return"\n void setOutput(float val) {\n "+t.output+" = vec4(val, 0, 0, 0);\n }\n "}(l)),r&&(f+=ai),[f,h,i,s,a,u,n].join("\n")}function ti(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===o&&1===a)return"\n float "+n+"() {\n return sampleTexture("+e+", halfCR);\n }\n ";var i=t.shapeInfo.texShape,s=i[0],u=i[1],c=ii(e);return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+s+", "+u+", "+c+");\n return sampleTexture("+e+", uv);\n }\n "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n float "+n+"(int index) {\n "+si(t)+"\n }\n ";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===a&&1===o)return"\n float "+n+"(int index) {\n return sampleTexture("+e+", halfCR);\n }\n ";var i=ii(e);if(1===a)return"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+i+") + 0.5) / "+o+".0);\n return sampleTexture("+e+", uv);\n }\n ";if(1===o)return"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+i+") + 0.5) / "+a+".0, 0.5);\n return sampleTexture("+e+", uv);\n }\n ";return"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+o+", "+a+", index + "+i+");\n return sampleTexture("+e+", uv);\n }\n "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape;if(null!=o&&S(e,o)){var a=o[0],i=o[1];return"\n float "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n return sampleTexture("+n+", uv);\n }\n "}var s=M(e),u=s.newShape,c=s.keptDims,l=u;if(l.length<e.length){var h=ci(t,l);return"\n "+ti(h)+"\n float "+r+"(int row, int col) {\n return "+r+"("+li(["row","col"],c)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col) {\n int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n "+si(t)+"\n }\n ";var f=o[0],d=o[1],p=ii(n);if(1===d)return"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+p+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(1===f)return"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+p+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+d+".0, 0.5);\n return sampleTexture("+n+", uv);\n }\n ";return"\n float "+r+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+e[1]+" + col + "+p+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+n+", uv);\n }\n"}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[1]*e[2],a=e[2],i=M(e),s=i.newShape,u=i.keptDims,c=s;if(c.length<e.length){var l=ci(t,c);return"\n "+ti(l)+"\n float "+r+"(int row, int col, int depth) {\n return "+r+"("+li(["row","col","depth"],u)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3("+o+", "+a+", 1)));\n "+si(t)+"\n }\n ";var h=t.shapeInfo.texShape,f=h[0],d=h[1],p=t.shapeInfo.flatOffset;if(d===o&&null==p)return"\n float "+r+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+a+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+d+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(d===a&&null==p)return"\n float "+r+"(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+d+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ";var v=ii(n);return"\n float "+r+"(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+o+" + col * "+a+" + depth + "+v+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[3],a=e[2]*o,i=e[1]*a,s=M(e),u=s.newShape,c=s.keptDims;if(u.length<e.length){var l=ci(t,u);return"\n "+ti(l)+"\n float "+r+"(int row, int col, int depth, int depth2) {\n return "+r+"("+li(["row","col","depth","depth2"],c)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4("+i+", "+a+", "+o+", 1)));\n "+si(t)+"\n }\n ";var h=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,d=f[0],p=f[1];if(p===i&&null==h)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3("+a+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+p+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(p===o&&null==h)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3("+e[1]*e[2]+", "+e[2]+", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+p+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ";var v=ii(n);return"\n float "+r+"(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+i+" + col * "+a+" +\n depth * "+o+" + depth2;\n vec2 uv = uvFromFlat("+d+", "+p+", index + "+v+");\n return sampleTexture("+n+", uv);\n }\n "}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[4],a=e[3]*o,i=e[2]*a,s=e[1]*i,u=M(e),c=u.newShape,l=u.keptDims;if(c.length<e.length){var h=ci(t,c);return"\n "+ti(h)+"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n return "+r+"("+li(["row","col","depth","depth2","depth3"],l)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4("+s+", "+i+", "+a+", "+o+")) +\n depth3;\n "+si(t)+"\n }\n ";var f=t.shapeInfo.flatOffset,d=t.shapeInfo.texShape,p=d[0],v=d[1];if(v===s&&null==f)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+i+", "+a+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(v===o&&null==f)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4("+e[1]*e[2]*e[3]+",\n "+e[2]*e[3]+", "+e[3]+", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ";var g=ii(n);return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+s+" + col * "+i+" + depth * "+a+" +\n depth2 * "+o+" + depth3 + "+g+";\n vec2 uv = uvFromFlat("+p+", "+v+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=M(e),a=o.newShape,i=o.keptDims;if(a.length<e.length){var s=ci(t,a);return"\n "+ti(s)+"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+r+"("+li(["row","col","depth","depth2","depth3","depth4"],i)+");\n }\n "}var u=e[5],c=e[4]*u,l=e[3]*c,h=e[2]*l,f=e[1]*h;if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4("+f+", "+h+", "+l+", "+c+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+u+", 1)));\n "+si(t)+"\n }\n ";var d=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,v=p[0],g=p[1];if(g===f&&null==d)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+h+", "+l+", "+c+", "+u+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+g+".0, "+v+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(g===u&&null==d)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4("+e[1]*e[2]*e[3]*e[4]+",\n "+e[2]*e[3]*e[4]+",\n "+e[3]*e[4]+",\n "+e[4]+")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+g+".0, "+v+".0);\n return sampleTexture("+n+", uv);\n }\n ";var m=ii(n);return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+f+" + col * "+h+" + depth * "+l+" +\n depth2 * "+c+" + depth3 * "+u+" + depth4 + "+m+";\n vec2 uv = uvFromFlat("+v+", "+g+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function ei(t){var e,n,r;switch(t.shapeInfo.logicalShape.length){case 0:return e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=Ya(),"\n vec4 "+n+"() {\n return "+r.texture2D+"("+e+", 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,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Ya();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+o[0]+", "+o[1]+", index);\n return "+a.texture2D+"("+e+", uv);\n }\n "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=o[0],i=o[1],s=Ya();if(null!=o&&S(e,o))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=Math.ceil(e[1]/2);return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+c+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===e[0]){var i=e.slice(1),s=ci(t,i);return"\n "+ei(s)+"\n vec4 "+r+"(int b, int row, int col) {\n return "+r+"("+li(["b","row","col"],[1,2])+");\n }\n "}var u=a[0],c=a[1],l=Math.ceil(e[2]/2),h=l*Math.ceil(e[1]/2),f=Ya();return"\n vec4 "+r+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+u+", "+c+", "+h+", "+l+", b, row, col);\n return "+f.texture2D+"("+n+", uv);\n }\n "}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=i[0],u=i[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),h="int b, int row, int col",f="b * "+l+" + (row / 2) * "+c+" + (col / 2)",d=2;d<n-1;d++)h="int b"+d+", "+h,l*=e[n-d-1],f="b"+d+" * "+l+" + "+f;var p=Ya();return"\n vec4 "+o+"("+h+") {\n int index = "+f+";\n int texR = index / "+u+";\n int texC = index - texR * "+u+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n return "+p.texture2D+"("+r+", uv);\n }\n "}(t)}}var ni="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ri="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",oi="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ai="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function ii(t){return"offset"+t}function si(t){var e=t.name,n=k(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n for (int i = 0; i < "+n+"; i++) {\n if (i == index) {\n return "+e+"[i];\n }\n }\n "}function ui(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function ci(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function li(t,e){return e.map((function(e){return t[e]})).join(", ")}var hi=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,C(t.length>2,(function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."}));var o=t[t.length-1],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,l=ui(c),h=Xa("coords",c);if(1===a){var f=ui(s=c+1);i="\n "+f+" sourceLocR = "+f+"("+h.join()+", 0);\n ++"+h[c-1]+";\n "+f+" sourceLocG = "+f+"("+h.join()+", 0);\n ++"+h[c-2]+";\n "+f+" sourceLocA = "+f+"("+h.join()+", 0);\n --"+h[c-1]+";\n "+f+" sourceLocB = "+f+"("+h.join()+", 0);\n --"+h[c-2]+";"}else s=c,i="\n "+l+" sourceLocR = coords;\n ++"+h[c-1]+";\n "+l+" sourceLocG = coords;\n ++"+h[c-2]+";\n "+l+" sourceLocA = coords;\n --"+h[c-1]+";\n "+l+" sourceLocB = coords;\n --"+h[c-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),p="."+d[s-1],v=d.map((function(t){return"int "+t})),g=Xa("sourceLocR",s-1).concat("inIdx.r"),m=Xa("sourceLocG",s-1).concat("inIdx.g"),y=Xa("sourceLocB",s-1).concat("inIdx.b"),x=Xa("sourceLocA",s-1).concat("inIdx.a"),b="max"===n?"greaterThan":"lessThan",w=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+m.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+")));",E="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+m.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",R=r?"":"\n float getBestIndicesAChannel("+v.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+v.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+R+"\n void main() {\n "+l+" coords = getOutputCoords();\n bool hasNextCol = "+h[c-1]+" < "+(u[c-1]-1)+";\n bool hasNextRow = "+h[c-2]+" < "+(u[c-2]-1)+";\n "+i+"\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 = "+E+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+w+"\n vec4 candidate = "+E+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+b+"(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 "},fi=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+c+", "+l+");\n const float avgMultiplier = float("+h+");\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 += "+a+") {\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+= "+i+") {\n float dyC = float(dyCCorner + wC) / "+o+".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 "},di=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=l-1-t.padInfo.front,p=h-1-t.padInfo.top,v=f-1-t.padInfo.left,g=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+d+", "+p+", "+v+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+o+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+a+".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 for (int wC = 0; wC < "+f+";\n wC += "+c+") {\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(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},pi=function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Pr(t,e),Pr(t,n);var i="0.0";null!=r&&(Pr(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Pr(t,o),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 = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},vi=function(t,e,n,r,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Pr(t,e),Pr(t,n);var i="vec4(0.0)";null!=r&&(Pr(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Pr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+i+";\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("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},gi="return areal * breal - aimag * bimag;",mi="return areal * bimag + aimag * breal;",yi=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Pr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},xi="return a + b;",bi="return a - b;",wi="return a * b;",Ci="\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",Ei="return (a < 0.) ? b * a : a;",Ri=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Pr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},Ii="\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",ki="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Si=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Pr(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===k(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+ui(o)+" coords = getOutputCoords();\n ",1===o)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var i=Xa("coords",o);a+="\n bool nextRowOutOfBounds =\n ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+i[o-1]+" + 1) >= "+this.outputShape[o-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 "+a+"\n\n setOutput(result);\n }\n "},Ai=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ti=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\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(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Di=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 "},Ni=function(t){this.outputShape=[],this.outputShape=Sn(t,1),this.variableNames=t.map((function(t,e){return"T"+e}));var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var o=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+o+"));")}var a=e.length,i=e[e.length-1];r.push("else setOutput(getT"+a+"(yR, yC-"+i+"));"),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n "+r.join("\n ")+"\n }\n "},Fi=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Sn(t,e);var n=this.outputShape,r=n.length,o=ui(r),a=Xa("coords",r),i=["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;u<s.length;u++)s[u]=s[u-1]+t[u][e];var c=i[e],l=i.slice(-2),h=i.join(),f="if ("+c+" < "+s[0]+") {\n return getChannel(\n getT0("+h+"), vec2("+l.join()+"));\n }";for(u=1;u<s.length;u++){var d=s[u-1];f+="\n if ("+c+" < "+s[u]+" && "+c+" >= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+_i(i,c,d)+"),\n vec2("+_i(l,c,d)+"));\n }"}var p=s.length,v=s[s.length-1];f+="\n return getChannel(\n getT"+p+"("+_i(i,c,v)+"),\n vec2("+_i(l,c,v)+"));",this.userCode="\n float getValue("+i.map((function(t){return"int "+t}))+") {\n "+f+"\n }\n\n void main() {\n "+o+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n\n "+a[r-1]+" = "+a[r-1]+" + 1;\n if ("+a[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+a+");\n }\n\n "+a[r-2]+" = "+a[r-2]+" + 1;\n if ("+a[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+a+");\n }\n\n "+a[r-1]+" = "+a[r-1]+" - 1;\n if ("+a[r-2]+" < "+n[r-2]+" &&\n "+a[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+a+");\n }\n setOutput(result);\n }\n "};function _i(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var Oi=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a="channelsLast"===t.dataFormat;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+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Mi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a="channelsLast"===t.dataFormat,i=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,c=a?2:3,l=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+l+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+c+"]) - 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) / "+o+".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\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Bi=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=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+" - "+o+";\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+" - "+a+";\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+" - "+i+";\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 "},Pi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=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) / "+o+".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) / "+a+".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) / "+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 = "+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 "},Li=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a=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 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: 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+" - "+o+";\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 "},Wi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\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) / "+o+".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 // TO DO: 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 "},Ui=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.padInfo.top,a=t.padInfo.left,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4,p="channelsLast"===t.dataFormat,v=p?1:2,g=p?2:3,m=p?3:1,y="",x="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",x="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+m+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+v+"], coords["+g+"]) * 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 < "+l+"; 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 < "+h+"; 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 < "+f+"; d1 += 4) {\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 if ("+p+") {\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 dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===d)+") {\n\n if ("+p+") {\n dotProd +=\n getX(batch, xR, xC, "+f+") *\n getW(wR, wC, "+f+", d2);\n } else {\n dotProd +=\n getX(batch, "+f+", xR, xC) *\n getW(wR, wC, "+f+", d2);\n }\n\n } else if ("+(2===d)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2)\n );\n\n if ("+p+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===d)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2),\n getW(wR, wC, "+f+" + 2, d2)\n );\n\n if ("+p+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1),\n getX(batch, xR, xC, "+f+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC),\n getX(batch, "+f+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+b+"\n "+x+"\n setOutput(result);\n }\n "},Vi=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,h=t.filterHeight,f=t.filterWidth,d=4*Math.floor(t.inChannels/4),p=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+o+", "+a+", "+i+");\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 < "+h+"; 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 < "+f+"; 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 < "+d+"; 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, "+d+") *\n getW(wF, wR, wC, "+d+", d2);\n } else if ("+(2===p)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+d+"),\n getX(batch, xF, xR, xC, "+d+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+d+", d2),\n getW(wF, wR, wC, "+d+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===p)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+d+"),\n getX(batch, xF, xR, xC, "+d+" + 1),\n getX(batch, xF, xR, xC, "+d+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+d+", d2),\n getW(wF, wR, wC, "+d+" + 1, d2),\n getW(wF, wR, wC, "+d+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},zi=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,p=t.outChannels/t.inChannels,v="",g="";n&&(v=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",g="result = activation(result);");var m=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+v+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+p+";\n int q = d2 - d1 * "+p+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+f+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+o+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+h+";\n\n if (xC < 0 || xC >= "+a+") {\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\n float result = dotProd;\n "+m+"\n "+g+"\n setOutput(result);\n }\n "},Gi=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,p=d,v="int xR; int xC; int xCOffset;",g=0;g<f;g++)for(var m=0;m<d;m++)v+="\n vec4 xTexelR"+g+"C"+2*m+" = vec4(0.);\n vec4 wR"+g+"C"+m+" = vec4(0.);\n vec4 xR"+g+"C"+m+" = vec4(0.);";for(g=0;g<f;g++)for(var y=0;y<p;y++){if(v+="\n xR = xRCorner + "+g*l+";\n xC = xCCorner + "+(m=2*y)*h+";\n ",1===c){if(m<d&&(v+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+m+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+a+") {\n xTexelR"+g+"C"+m+".zw = vec2(0.);\n }\n } else {\n xTexelR"+g+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+a+") {\n previous.zw = vec2(0.);\n }\n\n xR"+g+"C"+m+" = vec4(previous.zw, xTexelR"+g+"C"+m+".xy);\n } else {\n xR"+g+"C"+m+" = vec4(0, 0, xTexelR"+g+"C"+m+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+o+" && xC >= 0 && xC < "+a+") {\n xTexelR"+g+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+m+" = vec4(0.);\n }\n\n xR"+g+"C"+m+" = xTexelR"+g+"C"+m+";\n ",m+1<d)){var x=s%2==0?b(h):h;h%2==0&&s%2==1||h%2!=0&&s%2!=1?(v+="\n xCOffset = xC + "+s%2+" + "+x+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",h>1&&(v+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+m+" = vec4(0.);\n }\n "),v+="\n xR"+g+"C"+(m+1)+" = vec4(\n xTexelR"+g+"C"+m+".zw, xTexelR"+g+"C"+(m+2)+".xy);\n "):v+="\n xCOffset = xC + "+x+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+g+"C"+(m+1)+" = xTexelR"+g+"C"+(m+2)+";\n "}}else m<d&&(v+="\n if(xR >= 0 && xR < "+o+") {\n ",s%2==1?(v+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+m+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+a+") {\n xTexelR"+g+"C"+(m+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+g+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+m+" = vec4(\n xTexelR"+g+"C"+m+".zw, xTexelR"+g+"C"+(m+2)+".zw);\n ",m+1<d&&(v+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+g+"C"+(m+1)+" = vec4(xTexelR"+g+"C"+(m+2)+".xy, final.xy);\n ")):(v+="\n if(xC >= 0 && xC < "+a+") {\n xTexelR"+g+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+g+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+g+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+g+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+g+"C"+m+" = vec4(\n xTexelR"+g+"C"+m+".xy, xTexelR"+g+"C"+(m+2)+".xy);\n ",m+1<d&&(v+="\n xR"+g+"C"+(m+1)+" = vec4(\n xTexelR"+g+"C"+m+".zw, xTexelR"+g+"C"+(m+2)+".zw);\n ")),v+="}");m<d&&(v+="\n vec4 wTexelR"+g+"C"+m+" = getW("+g+", "+m+", d1, q);\n wR"+g+"C"+m+" = vec4(wTexelR"+g+"C"+m+".xz, wTexelR"+g+"C"+m+".xz);\n ",m+1<d&&(v+="\n vec4 wTexelR"+g+"C"+(m+1)+" = getW("+g+", "+(m+1)+", d1, q);\n wR"+g+"C"+(m+1)+" =\n vec4(wTexelR"+g+"C"+(m+1)+".xz, wTexelR"+g+"C"+(m+1)+".xz);"))}for(g=0;g<f;g++)for(m=0;m<d;m++)v+="dotProd += xR"+g+"C"+m+" * wR"+g+"C"+m+";";var w="",C="";n&&(w=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",C="result = activation(result);");var E=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+w+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2;\n int q = 0;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n vec4 dotProd = vec4(0.);\n\n "+v+"\n\n vec4 result = dotProd;\n "+E+"\n "+C+"\n setOutput(result);\n }\n "},Hi=function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=t[0],i=t[1],s=t[2],u=t[3],c=e[0],l=n[0],h=n[1];this.outputShape=[c,l,h,u];var f="bilinear"===r?1:0,d=[i-1+".0",s-1+".0"],p=d[0],v=d[1],g=l>1?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],m=g[0],y=g[1],x=g[2],b=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n const float height_ratio = float("+m+");\n const float width_ratio = float("+w+");\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 >= "+a+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+x+";\n if( in_y < 0.0 || in_y > "+p+" ) {\n setOutput(float("+o+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+v+" ) {\n setOutput(float("+o+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+f+" == 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 "},qi=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+ui(r)+" coords = getOutputCoords();\n int end = "+Ki(r,"coords")+";\n float val = 0.0;\n for (int i = "+o+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+a+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+Ki(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 "};function Ki(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 ji=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=Ya();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+$a(["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 "},Xi=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=Ya();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+$a(["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 "},Yi=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}(),$i=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},Qi=function(t){this.variableNames=["A"],this.outTexUsage=zt.DOWNLOAD;var e=Ya();this.outputShape=t,this.userCode="\n "+Ja+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},Ji=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=zt.DOWNLOAD;var e=Ya();this.outputShape=t,this.userCode="\n "+Ja+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},Zi=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=Ya(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n "+Qa(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".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("+i+", 0., 0., 0.);\n }\n "},ts=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=Ya(),o=e[0],a=e[1];this.outputShape=t;var i="",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;i+="\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 = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".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 "+Qa(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 "+i+"\n\n "+r.output+" = "+s+";\n }\n "},es="return real * expR - imag * expI;",ns="return real * expI + imag * expR;",rs=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+o+";\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) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},os=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}(),as=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=ui(this.rank),a=function(t,e){var n=t.length;if(n>4)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"],o=[],a=0;a<t.length;a++)a===e?o.push("int(getIndices("+r[a]+"))"):o.push(""+r[a]);return o.join()}(t,n);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "};var is=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=ui(e.length),o=ui(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+o+" 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 * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function ss(t,e){var n=Ya();return oe(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 us(t,e){return fe(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 cs(t,e){return de(t,e,new Uint16Array([0,1,2,2,1,3]))}function ls(t,e,n,r,o,a,i){ve(n,r);var s=pe(t,e),u=t.TEXTURE_2D;return Jt(t,e,(function(){return t.bindTexture(u,s)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),Jt(t,e,(function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function hs(t,e,n,r,o){var a=Xt(n,r);return ls(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function fs(t,e,n,r,o){var a=Xt(n,r);return ls(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function ds(t,e,n,r,o){var a=Xt(n,r);return ls(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ps(t,e,n,r,o){var a=$t(n,r);return ls(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function vs(t,e,n,r,o){var a=$t(n,r);return ls(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function gs(t,e,n,r){return Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),me(t,e,n,"clipSpacePos",r,3,20,0)&&me(t,e,n,"uv",r,2,20,12)}function ms(t,e,n,r,o,a,i){var s,u,c;Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,c=i.internalFormatPackedFloat),s.set(a),Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,o,0,t.RGBA,u,s)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function ys(t,e,n,r){Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function xs(t,e,n,r,o){var a=t.createBuffer();Jt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)}));var i=16*n*r;return Jt(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)})),Jt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),Jt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),a}function bs(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o}function ws(t,e,n,r,o){var a=Xt(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return Jt(t,e,(function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function Cs(t,e,n,r,o,a,i,s){var u=t,c=new Float32Array(function(t,e){var n=$t(t,e);return n[0]*n[1]*4}(a,i));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 Es(t,e,n,r){var o=new Float32Array(n*r*4);return Jt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)})),o}var Rs=Object.freeze({createVertexShader:ss,createVertexBuffer:us,createIndexBuffer:cs,createFloat32MatrixTexture:hs,createFloat16MatrixTexture:fs,createUnsignedBytesMatrixTexture:ds,createPackedMatrixTexture:ps,createFloat16PackedMatrixTexture:vs,bindVertexProgramAttributeStreams:gs,uploadDenseMatrixToTexture:ms,uploadPixelDataToTexture:ys,createBufferFromOutputTexture:xs,downloadFloat32MatrixFromBuffer:bs,downloadByteEncodedFloatMatrixFromOutputTexture:ws,downloadPackedMatrixFromBuffer:Cs,downloadMatrixFromPackedOutputTexture:Es}),Is=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=i().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Kt(e,t)):this.gl=jt(e);var n="WEBGL_color_buffer_float";if(1===i().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=re(this.gl,this.debug,"OES_texture_float"),Pe(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=re(this.gl,this.debug,"OES_texture_half_float");else if(i().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Pe(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=re(this.gl,this.debug,"EXT_color_buffer_half_float");else if(i().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Pe(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Pe(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=us(this.gl,this.debug),this.indexBuffer=cs(this.gl,this.debug),this.framebuffer=ge(this.gl,this.debug),this.textureConfig=Qt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return i().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;Jt(e,this.debug,(function(){return e.finish()})),Jt(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Jt(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),Jt(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),Jt(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),Jt(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),hs(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),fs(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),ds(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),ys(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),ms(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),vs(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ps(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(Ee(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Jt(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 ws(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return Cs(this.gl,t,0,0,0,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return bs(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=xs(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(i().getBool("WEBGL_FENCE_API_ENABLED")){var o=t,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(a,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=a}else i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,i().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 Es(r.gl,r.debug,e,n)}))},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=ae(e,this.debug,t),r=ss(e,this.debug),o=ce(e,this.debug);return Jt(e,this.debug,(function(){return e.attachShader(o,r)})),Jt(e,this.debug,(function(){return e.attachShader(o,n)})),le(e,this.debug,o),this.debug&&he(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=gs(e,this.debug,this.program,this.vertexBuffer)),o},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Jt(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&&he(this.gl,this.debug,this.program),Jt(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?xe(this.gl,this.debug,t,e):be(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Jt(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(),we(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=$t(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a)},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&&he(this.gl,this.debug,this.program),Re(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Jt(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=re(this.gl,this.debug,2===i().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===i().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(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o},t.prototype.endQuery=function(){if(2!==i().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 n(this,void 0,void 0,(function(){var e=this;return r(this,(function(n){switch(n.label){case 0:return[4,F((function(){return e.disposed||e.isQueryAvailable(t,i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,i().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(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!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;e<t.length;++e){if(!t[e]())break}return e-1}(this.itemsToPoll.map((function(t){return t.isDoneFn}))),e=0;e<=t;++e){(0,this.itemsToPoll[e].resolveFn)()}this.itemsToPoll=this.itemsToPoll.slice(t+1)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||F((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),Ce(this.gl,this.debug,t,this.framebuffer),this.debug&&Re(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(Ce(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Re(this.gl)):Ee(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;Ce(r,this.debug,t,this.framebuffer),this.debug&&Re(r),this.outputTexture=t,Jt(r,this.debug,(function(){return r.viewport(0,0,e,n)})),Jt(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return o.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 ks(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,o=e[n],a=o.shape;if(!S(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!S(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}}))}var Ss=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,h=n.dataFormat,f=s.left,d=s.top,p=o*r,v=Ya(),g="channelsLast"===h,m=g?0:1,y=g?1:2,x="",b=0;b<=1;b++)for(var w=0;w<=1;w++)x+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+b+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+i+" - "+d+";\n d0 = offsetY + "+l+" * (pos / "+p+");\n\n if(d0 < "+e[m]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+f+".);\n d1 = offsetX + "+c+" * (int(mod(float(pos), "+p+".) / "+o+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+o+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*b+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*b+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+x+"\n\n "+v.output+" = result;\n }\n "},As=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 = -"+i+"; j <= "+i+"; 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 * "+a+";\n setOutput(val);\n }\n "},Ts=function(t,e,n,r,o){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=o,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("+o+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+o+");\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 "},Ds=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 - "+i+";\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 = - "+i+"; j <= "+i+"; 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 * "+a+";\n setOutput(result);\n }\n "},Ns=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+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 < "+o+";\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 < "+a+"; 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 * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Fs=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=s-1-t.padInfo.front,h=u-1-t.padInfo.top,f=c-1-t.padInfo.left,d=s*u*c-1;this.userCode="\n const ivec3 pads = ivec3("+l+", "+h+", "+f+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+o+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".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 for (int wC = 0; wC < "+c+";\n wC += "+i+") {\n float dyC = float(dyCCorner + wC) / "+r+".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(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+d+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+c+" +\n wR * "+c+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},_s=function(t,e,n,r,o,a,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),c=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",p="";a&&(d=i?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",p="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+d+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+c+");\n vec4 b = getMatrixB(rc.x, "+l+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+h[0]+" * "+f[0]+");\n result += ("+h[1]+" * "+f[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+v+"\n\n "+p+"\n\n setOutput(result);\n }\n "},Os=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}(),Ms=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 "},Bs=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=Xa("rc",e),r=ui(e),o=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=t-2;o<t;o++)r+=n[o]+" >= "+e[o],o<t-1&&(r+="||");return r}(e,t,n),a=function(t,e,n,r){if(1===t)return"";var o=r.slice(-2);return"\n int r = "+o[0]+";\n int c = "+o[1]+";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i<t;i++)a=e[e.length-1-i]+","+a;n.push(a)}return n}(n,e);return 1===n?"getA(rc),\n rc + 1 >= "+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("+o+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+i+"));\n }\n }\n "}};var Ps=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));var r=t.length,o=ui(r),a=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+o+" start = "+o+"("+a+");\n "+o+" end = "+o+"("+i+");\n\n void main() {\n "+o+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+o+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Ls=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));for(var r=t.length,o=ui(r),a=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=Xa("rc",r),u=Xa("source",r),c=s[r-1]+" < "+this.outputShape[r-1],l=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n if("+c+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+c+") {"],f=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",p=0,v=1===r?2:4;p<v;p++)d+="\n "+h[p]+"\n if ("+f+") {\n result["+p+"] = float("+n+");\n } else {\n "+o+" source = rc - start;\n result["+p+"] = getChannel(getX("+u.join()+"), "+l+");\n }\n ";d+=1===r?"} ":"}}",this.userCode="\n const "+o+" start = "+o+"("+a+");\n const "+o+" end = "+o+"("+i+");\n\n void main() {\n "+o+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+d+"\n setOutput(result);\n }\n "},Ws=function(t,e,n,r,o){if(void 0===r&&(r=!1),void 0===o&&(o=!1),this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var a=t.filterWidth,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=t.padInfo.top,d=t.padInfo.left;this.outputShape=t.outShape;var p="avg"===e,v="((batch * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + d",g="(xR * "+t.inWidth+" + xC) * "+t.inChannels+" + d",m="0.0";if(p||(m="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+f+", "+d+");\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 < "+l+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+";\n wC += "+c+") {\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 = "+(r?o?v:g:"wR * "+h+" + wC")+";\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var x=4*Math.floor(a/4),b=a%4,w="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+f+", "+d+");\n const float initializationValue = "+m+";\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("+m+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+l+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+x+"; wC += 4) {\n int xC = xCCorner + wC * "+c+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+c+", d),\n getValue(batch, xR, xC + 2 * "+c+", d),\n getValue(batch, xR, xC + 3 * "+c+", d)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+x+";\n if ("+(1===b)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===b)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+c+", d),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===b)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+c+", d),\n getValue(batch, xR, xC + 2 * "+c+", d),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n "}},Us=function(t,e,n,r,o){if(void 0===r&&(r=!1),void 0===o&&(o=!1),this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var a=t.filterWidth,i=t.strideDepth,s=t.strideHeight,u=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,h=t.dilationWidth,f=t.effectiveFilterDepth,d=t.effectiveFilterHeight,p=t.effectiveFilterWidth,v=t.padInfo.front,g=t.padInfo.top,m=t.padInfo.left;this.outputShape=t.outShape;var y="avg"===e,x="0.0";if(y||(x="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+s+", "+u+");\n const ivec3 pads = ivec3("+v+", "+g+", "+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+f+";\n wD += "+c+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+d+";\n wR += "+l+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+";\n wC += "+h+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\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 = "+(r?o?"(((batch * "+t.inDepth+" + xD) * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"((xD * "+t.inHeight+" + xR) * "+t.inWidth+" + xC) * "+t.inChannels+" + ch":"wD * "+d+" * "+p+" +\n wR * "+p+" + wC")+";\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var b=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(b="avgValue / count");var w=4*Math.floor(a/4),C=a%4,E="\n if ("+y+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+s+", "+u+");\n const ivec3 pads = ivec3("+v+", "+g+", "+m+");\n const float initializationValue = "+x+";\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 xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+x+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+f+";\n wD += "+c+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+d+";\n wR += "+l+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+w+"; wC += 4) {\n int xC = xCCorner + wC * "+h+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+h+", ch),\n getValue(batch, xD, xR, xC + 2 * "+h+", ch),\n getValue(batch, xD, xR, xC + 3 * "+h+", ch)\n );\n\n "+E+"\n }\n\n int xC = xCCorner + "+w+";\n if ("+(1===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+E+"\n } else if ("+(2===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+h+", ch),\n initializationValue,\n initializationValue\n );\n\n "+E+"\n } else if ("+(3===C)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+h+", ch),\n getValue(batch, xD, xR, xC + 2 * "+h+", ch),\n initializationValue\n );\n\n "+E+"\n }\n }\n setOutput("+b+");\n }\n }\n "}},Vs=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var c=4*Math.floor(n/4),l=n%4,h="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",f="vec4";"all"===e?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",f="bvec4"):"any"===e&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",f="bvec4");var d="";o%n>0&&(d="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+d+"\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("+i+");\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 "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+h+"\n }\n\n int inIdx = inOffset + "+c+";\n if ("+(1===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(3===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+h+"\n }\n setOutput("+u+");\n }\n "},zs=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n "+o+"\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 "+$a(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Qa(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 "};var Gs=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],d=1/h,p=1/f,v=2*Math.ceil(d)+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("+h+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+p+");\n\n const int winHeight = int("+v+");\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), "+(o-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), "+(a-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 "},Hs=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],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("+a+".0, "+i+".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 "},qs=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],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("+a+".0, "+i+".0,\n "+i+".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 "},Ks=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],d=1/h,p=1/f,v=2*Math.ceil(d)+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("+h+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+p+");\n\n const int winHeight = int("+v+");\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("+o+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+a+") - 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 "},js=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],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("+a+".0, "+i+".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 "},Xs=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(","),o=ui(n);this.userCode="\n void main() {\n "+o+" 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 "},Ys=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=Xa("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=ui(n);function s(n){var r=t.map((function(r,o){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(o,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("+o+"){\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 "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(r.slice())+";\n if("+o+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+a+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+o+") {\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 "},$s=function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=ui(o.length),u=ui(a.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var f="getUpdates("+h+")",d=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+o+");\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 * "+d+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+f+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},Qs=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,c="\n sumValue += dot(values, segFilter);\n ",l="";o%n>0&&(l="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n ");var h="";o%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+o+") {\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 "+h+"\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 "+a+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\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 "},Js=function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<e.length;u++)s.push(""+a[u]),u<t&&i.push(""+a[u]);r=i.join(),o=s.join()}var c=ui(n);this.userCode="\n void main() {\n "+c+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n "},Zs=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=ui(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return tu.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."+tu[e]+" = start["+e+"] + coords."+tu[e]+";"})).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+o+"));\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}(),tu=["x","y","z","w","u","v"];var eu=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=ui(this.rank),n=Xa("coords",this.rank),r=Xa("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n result.x = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+a+";\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 = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+a+";\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 "+i+"\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}(),nu=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=ui(n.length),a=ui(n.length),i="";if(1===r)i="coords * strides + begin";else{var s=0;i=n.map((function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"})).join(",")}this.userCode="\n "+o+" begin = "+o+"("+t+");\n "+o+" strides = "+o+"("+e+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+i+"));\n }\n "},ru=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,o=ou(e,n),a=au(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===Gt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Gt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Gt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Gt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Gt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=au(e,ou(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,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 ou(t,e){if(t===zt.UPLOAD)return Gt.PACKED_2X2_FLOAT32;if(t===zt.RENDER||null==t)return function(t){return i().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?Gt.PACKED_2X2_FLOAT32:Gt.UNPACKED_FLOAT32:t?Gt.PACKED_2X2_FLOAT16:Gt.UNPACKED_FLOAT16}(e);if(t===zt.DOWNLOAD||t===zt.PIXELS)return Gt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function au(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var iu=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var o=ui(this.rank),a=function(t){var e=t.length;if(e>5)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=[],o=0;o<t.length;o++)r.push("imod("+n[o]+", "+t[o]+")");return r.join()}(t);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "};var su=1.7580993408473768,uu=1.0507009873554805,cu=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 "},lu="if (isnan(x)) return x;",hu="return x;",fu="return abs(x);",du=lu+"\n return (x < 0.0) ? 0.0 : x;\n",pu=lu+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",vu="return (x >= 0.0) ? x : (exp(x) - 1.0);",gu="\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = "+su+";\n float scale = "+uu+";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var mu="return -x;",yu="return ceil(x);",xu="return floor(x);",bu="return exp(x);",wu="return exp(x) - 1.0;",Cu=lu+"\n return sin(x);\n",Eu=lu+"\n return cos(x);\n",Ru=lu+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n",Iu=lu+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n",ku=lu+"\n return atan(x);\n",Su=lu+"return log(x + sqrt(x * x + 1.0));",Au=lu+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",Tu=lu+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Du="return x;",Nu="return x;",Fu="\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",_u="\n vec4 result = min(x, vec4(6.)) * 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",Ou="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",Mu=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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 "},Bu=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=Xa("rc",e),r=ui(e),o=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),a=n.slice(-2),i=e<=1?"rc":"vec2("+a.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+o+");\n\n setOutput(getChannel(packedInput, "+i+"));\n }\n "},Pu={};function Lu(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Nu:hu;if("relu"===t)return e?Fu:du;if("elu"===t)return e?Ou:vu;if("relu6"===t)return e?_u:pu;if("prelu"===t)return e?ki:Ei;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var Wu=600;var Uu=function(t){function o(e){var n,r=t.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!i().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var o=jt(i().getNumber("WEBGL_VERSION"));r.binaryCache=(n=i().getNumber("WEBGL_VERSION"))in Pu?Pu[n]:(Pu[n]={},Pu[n]),r.gpgpu=new Is(o),r.canvas=o.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=e,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new ru(r.gpgpu),r.numMBBeforeWarning=null==i().global.screen?1024:i().global.screen.height*i().global.screen.width*window.devicePixelRatio*Wu/1024/1024,r.texData=new ca(r,Lt),r}return e(o,t),o.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},o.prototype.write=function(t,e,n){if(i().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:e,dtype:n,values:t,usage:zt.UPLOAD}),r},o.prototype.move=function(t,e,n,r){if(i().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:e,usage:zt.UPLOAD})},o.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,o=e.complexTensors,a=e.slice,i=e.shape,s=e.isPacked;if(null!=a){var u=void 0;u=s?new Mu(i,Du):new cu(i,Du);var c=this.runWebGLProgram(u,[{dataId:t,shape:i,dtype:r}],r),l=this.readSync(c.dataId);return this.disposeData(c.dataId),l}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var h,f,d=null!=this.activeTimers;(d&&(h=et()),"complex64"===r)?f=Aa(o.real.dataSync(),o.imag.dataSync()):f=this.getValuesFromTexture(t);return d&&(this.downloadWaitMs+=et()-h),this.convertAndCacheOnCPU(t,f)},o.prototype.read=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,s,u,c,l,h,f,d,p,v,g,m,y,x,b,w,C,E,R;return r(this,(function(r){switch(r.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise((function(t){return e.push(t)}))];if(n=this.texData.get(t),o=n.values,a=n.shape,s=n.slice,u=n.dtype,c=n.complexTensors,l=n.isPacked,null!=s)return h=void 0,h=l?new Mu(a,Du):new cu(a,Du),f=this.runWebGLProgram(h,[{dataId:t,shape:a,dtype:u}],u),d=this.read(f.dataId),this.disposeData(f.dataId),[2,d];if(null!=o)return[2,this.convertAndCacheOnCPU(t)];if(!i().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===i().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return p=null,"complex64"!==u&&i().get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(t),g=this.texData.get(v.dataId),p=(R=this.gpgpu).createBufferFromTexture.apply(R,[g.texture].concat(Yt(a)))),this.pendingRead.set(t,[]),"complex64"===u?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:r.sent(),r.label=2;case 2:return"complex64"!==u?[3,4]:[4,Promise.all([c.real.data(),c.imag.data()])];case 3:return y=r.sent(),x=y[0],b=y[1],m=Aa(x,b),[3,5];case 4:null==p?m=this.getValuesFromTexture(t):(w=k(a),m=this.gpgpu.downloadFloat32MatrixFromBuffer(p,w)),r.label=5;case 5:return null!=v&&this.disposeData(v.dataId),C=this.convertAndCacheOnCPU(t,m),E=this.pendingRead.get(t),this.pendingRead.delete(t),E.forEach((function(t){return t(C)})),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,C]}}))}))},o.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e<t.length;e++){var n=t[e];if(!ee(n)){if(i().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},o.prototype.getValuesFromTexture=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.isPacked,s=k(r);if(i().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var u=this.decode(t),c=this.texData.get(u.dataId),l=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[c.texture].concat(Yt(r))).subarray(0,s);return this.disposeData(u.dataId),l}var h=i().getBool("WEBGL_PACK")&&!0===a,f=h?De(r):r,d=h?new Ji(f):new Qi(f),p=this.runWebGLProgram(d,[{shape:f,dtype:o,dataId:t}],"float32"),v=this.texData.get(p.dataId),g=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,s);return this.disposeData(p.dataId),g},o.prototype.time=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,s,u,c;return r(this,(function(r){switch(r.label){case 0:return e=this.activeTimers,n=[],o=!1,null==this.programTimersStack?(this.programTimersStack=n,o=!0):this.activeTimers.push(n),this.activeTimers=n,t(),a=I(this.activeTimers.map((function(t){return t.query}))).filter((function(t){return null!=t})),s=I(this.activeTimers.map((function(t){return t.name}))).filter((function(t){return null!=t})),this.activeTimers=e,o&&(this.programTimersStack=null),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(a)]:[3,2];case 1:return c=r.sent(),u.kernelMs=w(c),u.getExtraProfileInfo=function(){return c.map((function(t,e){return{name:s[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},r.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}}))}))},o.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},o.prototype.startTimer=function(){return i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:et(),endMs:null}},o.prototype.endTimer=function(t){return i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=et(),t)},o.prototype.getQueryTime=function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){return i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]}))}))},o.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;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)}}},o.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,a=e.usage,i=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(o,r),this.textureManager.releaseTexture(n,o,a,i)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},o.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},o.prototype.getDataInfo=function(t){return this.texData.get(t)},o.prototype.getCPUBackend=function(){return i().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Lt.findBackend("cpu")),this.cpuBackend):null},o.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&&k(t.shape)<e}))},o.prototype.getGPGPUContext=function(){return this.gpgpu},o.prototype.complex=function(t,e){var n=this.makeOutput(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Lt.keep(t.clone()),imag:Lt.keep(e.clone())},n},o.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},o.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},o.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===k(n))return Fn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,o=$o(t.shape,e,n);if(r||!o){var a=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new eu(n):new Zs(n),s=a.getCustomSetupFunc(e);return this.compileAndRun(a,[t],null,s)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},o.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),o=this.makeOutput(n,t.dtype),a=this.texData.get(o.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var i=Qo(e,t.strides);r.slice&&(i+=r.slice.flatOffset),a.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),o},o.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var o=jo(e,n,r);if(o.some((function(t){return 0===t})))return Fn([],o);var a=new nu(e,r,o);return this.compileAndRun(a,[t])},o.prototype.reverse=function(t,e){var n=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ys(t.shape,e):new Xs(t.shape,e);return this.compileAndRun(n,[t])},o.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map((function(t){return Dn(t)})),r=t.map((function(t){return Nn(t)}));return Tn(this.concat(n,e),this.concat(r,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>i().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(t.length/2),a=this.concat(t.slice(0,o),e),s=this.concat(t.slice(o),e);return this.concat([a,s],e)}if(i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var u=new Fi(t.map((function(t){return t.shape})),e);return this.compileAndRun(u,t)}var c=Sn(t.map((function(t){return t.shape})),e),l=t.map((function(t){return t.as2D(-1,k(t.shape.slice(e)))})),h=new Ni(l.map((function(t){return t.shape})));return this.compileAndRun(h,l).reshape(c)},o.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,mu,t.dtype);var e=new cu(t.shape,mu);return this.compileAndRun(e,[t])},o.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=ua(t,[0,2,1])),r&&(e=ua(e,[0,2,1]));var u=1===a?t:t.as3D(s,i,1),c=1===a?2:1,l=1===a?e.as3D(s,1,i):e;return this.multiply(u,l).sum(c,!0)}var h=Tt(t.dtype,e.dtype),f=new _s(t.shape,[s,o,a],n,r);return this.compileAndRun(f,[t,e],h)},o.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],c=o?n.shape[1]:n.shape[2],l=e.shape[0],h=Tt(e.dtype,n.dtype),f=null!=a,d=null!=s,p=i?Lu(i,!0):null,v=new _s(e.shape,[l,u,c],r,o,f,p,d),g=[e,n];return a&&g.push(a),s&&g.push(s),this.compileAndRun(v,g,h)},o.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new yi(gi,t.shape,e.shape),a=new yi(mi,t.shape,e.shape),s=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],u=this.compileAndRun(o,s),c=this.compileAndRun(a,s),l=this.complex(u,c);return u.dispose(),c.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,wi,t.dtype);var h=new Ri(wi,t.shape,e.shape);return this.compileAndRun(h,[t,e],t.dtype)},o.prototype.batchNormalization=function(t,e,n,r,o,a){var s=[t,e,n],u=null;null!=a&&(u=a.shape,s.push(a));var c=null;if(null!=o&&(c=o.shape,s.push(o)),i().getBool("WEBGL_PACK_NORMALIZATION")){var l=new vi(t.shape,e.shape,n.shape,u,c,r);return this.compileAndRun(l,s)}var h=new pi(t.shape,e.shape,n.shape,u,c,r);return this.compileAndRun(h,s)},o.prototype.localResponseNormalization4D=function(t,e,n,r,o){var a=i().getBool("WEBGL_PACK_NORMALIZATION")?new Ds(t.shape,e,n,r,o):new As(t.shape,e,n,r,o);return this.compileAndRun(a,[t])},o.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new Ts(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t])},o.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map((function(t){return ot(t)}));return Va(er(t.shape,t.dtype,n),e)}var r=new iu(t.shape,e);return this.compileAndRun(r,[t])},o.prototype.pad=function(t,e,n){var r=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ls(t.shape,e,n):new Ps(t.shape,e,n);return this.compileAndRun(r,[t])},o.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new as(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},o.prototype.batchToSpaceND=function(t,e,n){C(t.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),o=pr(t.shape,e,r),a=vr(o.length,e.length),i=gr(t.shape,e,r),s=mr(n,e.length),u=yr(i,n,e.length);return ua(t.reshape(o),a).reshape(i).slice(s,u)},o.prototype.spaceToBatchND=function(t,e,n){C(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})),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=pr(i.shape,e,r,!1),u=vr(s.length,e.length,!1),c=gr(i.shape,e,r,!1);return ua(i.reshape(s),u).reshape(c)},o.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],a=Uo(o),i=new Vs({windowSize:a,inSize:o,batchSize:r},e),s=this.compileAndRun(i,[t],n);return 1===s.shape[1]?s:this.reduce(s,e,n)},o.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],o=t.shape[1];null!=n&&(r=n.shape[0],o=n.shape[1]);var a=Uo(o),i=new Ka({windowSize:a,inSize:o,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(i,s,"int32");return 1===u.shape[1]?u:this.argReduce(t,e,u)},o.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,o=Uo(r[r.length-1]),a=new hi(r,o,e,null==n),i=null==n?[t]:[t,n],s=this.compileAndRun(a,i,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},o.prototype.sum=function(t,e){Cn("sum",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o),i=Dt(t.dtype);return this.reduce(a,"sum",i).reshape(r)},o.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o),i=Dt(t.dtype);return this.reduce(a,"prod",i).reshape(r)},o.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=En([r],t.rank),a=t;null!=o&&(a=ua(t,o),r=In(1,t.rank)[0]);var i=function(t,e,n){for(var r=[],o=t.length,a=0;a<o;a++)a!==e?r.push(t[a]):r.push(n);return r}(a.shape,r,n),s=k([a.shape[r]]),u=a.as2D(-1,s),c=Dt(t.dtype),l=this.segOpCompute(u,"unsortedSegmentSum",e,c,n).reshape(i);return null!=o&&(l=ua(l,Rn(o))),l},o.prototype.segOpCompute=function(t,e,n,r,o){var a=t.shape[0],i=t.shape[1],s=function(t,e){var n,r=!1;for(t<=Wo?(n=t,r=!0):n=Y(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=Y(t,n+1);return n}(i,o),u=new Qs({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),c=this.compileAndRun(u,[t,n],r);return c.shape[1]===o?c:(n=Kn(0,o).tile([i/s]),this.segOpCompute(c,e,n,r,o))},o.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(Cn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!i().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=bn(t.shape,r),a=o[0],s=k(o[1]),u=t.as2D(-1,s);return this.argReduce(u,n).reshape(a)}return this.argReducePacked(t,n)},o.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},o.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},o.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 o=new qi(t.shape,n,r);return this.compileAndRun(o,[t])},o.prototype.equal=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Ri("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.notEqual=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Ri("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Ri("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.lessEqual=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Ri("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Ri("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.greaterEqual=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Ri("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.logicalNot=function(t){var e=new cu(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},o.prototype.logicalAnd=function(t,e){if(i().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 Ri("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.logicalOr=function(t,e){if(i().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 Ri("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.select=function(t,e,n){var r=new Js(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],Tt(e.dtype,n.dtype))},o.prototype.where=function(t){dn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return Ga(t.shape,e)},o.prototype.topk=function(t,e,n){return za(t.dataSync(),t.shape,t.dtype,e)},o.prototype.min=function(t,e){Cn("min",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},o.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("\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 Ri("\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])},o.prototype.mod=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("\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 Ri("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},o.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);Cn("max",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},o.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("\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 Ri("\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])},o.prototype.all=function(t,e){Cn("all",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},o.prototype.any=function(t,e){Cn("any",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},o.prototype.floorDiv=function(t,e){if(i().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 Ri("\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);return this.compileAndRun(n,[t,e],"int32")},o.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,xi);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=Tt(t.dtype,e.dtype);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,xi,n);var r=new Ri(xi,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},o.prototype.packedUnaryOp=function(t,e,n){var r=new Mu(t.shape,e);return this.compileAndRun(r,[t],n)},o.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new Si(n,t.shape,e.shape,o);return this.compileAndRun(a,[t,e],r)},o.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map((function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorInfo(t,a),u=r.makeComplexComponentTensorInfo(e,i),c=new Ri(n,t.shape,e.shape);return r.compileAndRun(c,[s,u],Tt(a.dtype,i.dtype))})),s=i[0],u=i[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},o.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},o.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>i().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 o=t.map((function(t){return t.dtype})).reduce((function(t,e){return Tt(t,e)})),a=t.map((function(t){return t.shape})),s=i().getBool("WEBGL_PACK")?new qa(t[0].shape,a):new Ha(t[0].shape,a);return this.compileAndRun(s,t,o)},o.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,bi);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=Tt(t.dtype,e.dtype);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,bi,t.dtype);var r=new Ri(bi,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},o.prototype.pow=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("\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 // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\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 Ri("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),r=Tt(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},o.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,yu,t.dtype);var e=new cu(t.shape,yu);return this.compileAndRun(e,[t])},o.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,xu,t.dtype);var e=new cu(t.shape,xu);return this.compileAndRun(e,[t])},o.prototype.sign=function(t){var e=new cu(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},o.prototype.isNaN=function(t){var e=new cu(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},o.prototype.isInf=function(t){var e=new cu(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},o.prototype.isFinite=function(t){var e=new cu(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},o.prototype.round=function(t){var e=new cu(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])},o.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,bu,t.dtype);var e=new cu(t.shape,bu);return this.compileAndRun(e,[t])},o.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,wu,t.dtype);var e=new cu(t.shape,wu);return this.compileAndRun(e,[t])},o.prototype.softmax=function(t,e){var n=O([e],t.shape),r=this.max(t,n),o=wn(r.shape,n),a=this.subtract(t,r.reshape(o)),i=this.exp(a),s=this.sum(i,n).reshape(o);return Bo(i,s)},o.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\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",t.dtype);var e=new cu(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},o.prototype.log1p=function(t){var e=new cu(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},o.prototype.sqrt=function(t){var e=new cu(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},o.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new cu(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},o.prototype.reciprocal=function(t){var e=new cu(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},o.prototype.relu=function(t){var e;return e=i().getBool("WEBGL_PACK")?new Mu(t.shape,Fu):new cu(t.shape,du),this.compileAndRun(e,[t])},o.prototype.relu6=function(t){var e;return e=i().getBool("WEBGL_PACK")?new Mu(t.shape,_u):new cu(t.shape,pu),this.compileAndRun(e,[t])},o.prototype.prelu=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si(ki,t.shape,e.shape):new Ri(Ei,t.shape,e.shape);return this.compileAndRun(n,[t,e])},o.prototype.elu=function(t){if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Ou,t.dtype);var e=new cu(t.shape,vu);return this.compileAndRun(e,[t])},o.prototype.eluDer=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("\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 Ri("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},o.prototype.selu=function(t){var e=new cu(t.shape,gu);return this.compileAndRun(e,[t])},o.prototype.int=function(t){var e=new cu(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},o.prototype.clip=function(t,e,n){var r,o=(r=i().getBool("WEBGL_PACK_CLIP")?new Ti(t.shape):new Ai(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},o.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,fu,t.dtype);var e=new cu(t.shape,fu);return this.compileAndRun(e,[t])},o.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Di(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},o.prototype.sigmoid=function(t){var e=new cu(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},o.prototype.softplus=function(t){var e=new cu(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])},o.prototype.sin=function(t){var e=new cu(t.shape,Cu);return this.compileAndRun(e,[t])},o.prototype.cos=function(t){var e=new cu(t.shape,Eu);return this.compileAndRun(e,[t])},o.prototype.tan=function(t){var e=new cu(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},o.prototype.asin=function(t){var e=new cu(t.shape,Ru);return this.compileAndRun(e,[t])},o.prototype.acos=function(t){var e=new cu(t.shape,Iu);return this.compileAndRun(e,[t])},o.prototype.atan=function(t){var e=new cu(t.shape,ku);return this.compileAndRun(e,[t])},o.prototype.atan2=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("\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 Ri("\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])},o.prototype.sinh=function(t){var e=new cu(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},o.prototype.cosh=function(t){var e=new cu(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},o.prototype.tanh=function(t){var e=new cu(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])},o.prototype.asinh=function(t){var e=new cu(t.shape,Su);return this.compileAndRun(e,[t])},o.prototype.acosh=function(t){var e=new cu(t.shape,Au);return this.compileAndRun(e,[t])},o.prototype.atanh=function(t){var e=new cu(t.shape,Tu);return this.compileAndRun(e,[t])},o.prototype.erf=function(t){var e=new cu(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 sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},o.prototype.step=function(t,e){var n=new cu(t.shape,function(t){return void 0===t&&(t=0),lu+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},o.prototype.conv2dByMatMul=function(t,e,n,r,o,a){var s=t.shape,u=this.texData.get(t.dataId),c=n.inChannels,l=s[0]*s[1]*s[2],h=n.outChannels,f="channelsLast"===n.dataFormat,d=(1===l||1===h)&&c>1e3,p=s[2]%2!=0&&!!u.isPacked;if(d||!i().getBool("WEBGL_LAZILY_UNPACK")||!i().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!p){var v=f?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],g=this.reshape(t,[1,v,n.inChannels]),m=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:g,b:m,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),n.outShape)}var y=f?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),x={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},b=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,C(_e(u.shape,x.shape),(function(){return"packed reshape "+u.shape+" to "+x.shape+" isn't free"}));var w=this.reshape(e,[1,n.inChannels,n.outChannels]),E=this.fusedBatchMatMul({a:x,b:w,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),R=this.texData.get(E.dataId);return C(R.isPacked,(function(){return"batchMatMul result is expected to be packed"})),u.shape=b,R.shape=n.outShape,Lt.makeTensorFromDataId(E.dataId,n.outShape,E.dtype)},o.prototype.conv2dWithIm2Row=function(t,e,n,r,o,a){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,c=n.outWidth,l=n.outHeight,h="channelsLast"===n.dataFormat,f=i*s*u,d=l*c,p=[f,d],v=t.squeeze([0]),g=e.reshape([1,f,-1]),m=new Ss(p,v.shape,n),y=this.compileAndRun(m,[v]).reshape([1,p[0],p[1]]),x=null!=r,b=null!=a,w=o?Lu(o,!0):null,C=new _s(y.shape,[1,d,n.outChannels],!0,!1,x,w,b),E=[y,g];r&&E.push(r),b&&E.push(a);var R=this.compileAndRun(C,E);return h?R.reshape([1,l,c,n.outChannels]):R.reshape([1,n.outChannels,l,c])},o.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,s=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,o,a,s);if(i().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,a,s);var u=null!=o,c=null!=s,l=a?Lu(a,!1):null,h=new Ui(r,u,l,c),f=[e,n];return o&&f.push(o),s&&f.push(s),this.compileAndRun(h,f)},o.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(i().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Ui(n);return this.compileAndRun(r,[t,e])},o.prototype.conv2dDerInput=function(t,e,n){var r=new Mi(n);return this.compileAndRun(r,[t,e])},o.prototype.conv2dDerFilter=function(t,e,n){var r=new Oi(n);return this.compileAndRun(r,[t,e])},o.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,o=t.convInfo,a=t.bias,s=t.activation,u=t.preluActivationWeights,c=i().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,l=s?Lu(s,c):null,h=[n,r],f=null!=a,d=null!=u;return f&&h.push(a),d&&h.push(u),c?(e=new Gi(o,f,l,d),this.compileAndRun(e,h)):(e=new zi(o,f,l,d),this.compileAndRun(e,h))},o.prototype.depthwiseConv2D=function(t,e,n){var r;return i().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Gi(n),this.compileAndRun(r,[t,e])):(r=new zi(n),this.compileAndRun(r,[t,e]))},o.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Wi(n);return this.compileAndRun(r,[t,e])},o.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Li(n);return this.compileAndRun(r,[t,e])},o.prototype.conv3d=function(t,e,n){var r=new Vi(n);return this.compileAndRun(r,[t,e])},o.prototype.conv3dDerInput=function(t,e,n){var r=new Pi(n);return this.compileAndRun(r,[t,e])},o.prototype.conv3dDerFilter=function(t,e,n){var r=new Bi(n);return this.compileAndRun(r,[t,e])},o.prototype.maxPool=function(t,e){var n=new Ws(e,"max",!1);return this.compileAndRun(n,[t])},o.prototype.avgPool=function(t,e){var n=new Ws(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},o.prototype.maxPoolBackprop=function(t,e,n,r){var o=new Ws(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Ns(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},o.prototype.avgPoolBackprop=function(t,e,n){var r=new fi(n);return this.compileAndRun(r,[t],e.dtype)},o.prototype.cast=function(t,e){return Ra(t,e,this)},o.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},o.prototype.avgPool3d=function(t,e){var n=new Us(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},o.prototype.avgPool3dBackprop=function(t,e,n){var r=new di(n);return this.compileAndRun(r,[t],e.dtype)},o.prototype.maxPool3d=function(t,e){var n=new Us(e,"max",!1);return this.compileAndRun(n,[t],"float32")},o.prototype.maxPool3dBackprop=function(t,e,n,r){var o=new Us(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Fs(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},o.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!_e(t.shape,e)&&(null===n.texture||!_e(n.shape,e))){var r=this.packedReshape(t,e);return Lt.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return Ia(t,e)},o.prototype.resizeBilinear=function(t,e,n,r){var o=i().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new qs(t.shape,e,n,r):new Hs(t.shape,e,n,r);return this.compileAndRun(o,[t],"float32")},o.prototype.resizeBilinearBackprop=function(t,e,n){var r=new Gs(t,e,n);return this.compileAndRun(r,[t])},o.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new js(t.shape,e,n,r);return this.compileAndRun(o,[t])},o.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Ks(t,e,n);return this.compileAndRun(r,[t])},o.prototype.multinomial=function(t,e,n,r){var o=e?t:ia(t),a=o.shape[0],i=o.shape[1],s=new Os(a,i,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],"int32",u)},o.prototype.oneHot=function(t,e,n,r){var o=new Ms(t.size,e,n,r);return this.compileAndRun(o,[t])},o.prototype.diag=function(t){var e=new $i(t.size);return this.compileAndRun(e,[t])},o.prototype.nonMaxSuppression=function(t,e,n,r,o){return dn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Oa(t.dataSync(),e.dataSync(),n,r,o)},o.prototype.cropAndResize=function(t,e,n,r,o,a){var i=new Hi(t.shape,e.shape,r,o,a);return this.compileAndRun(i,[t,e,n],"float32")},o.prototype.depthToSpace=function(t,e,n){C(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,c=i/(e*e),l=new Yi("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},o.prototype.split=function(t,e,n){return Ua(t,e,n)},o.prototype.scatterND=function(t,e,n){var r=Go(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/i,i],l=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return Ia(Fn([]),n);var f=On(0),d=new $s(a,o,l.rank,h.rank,s,c);return this.compileAndRun(d,[h,l,f]).reshape(n)},o.prototype.sparseToDense=function(t,e,n,r){var o=Go(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,c=new $s(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},o.prototype.fft=function(t){return this.fftImpl(t,!1)},o.prototype.ifft=function(t){return this.fftImpl(t,!0)},o.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new rs(es,t.shape,e),o=new rs(ns,t.shape,e),a=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},o.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Po(t,e),a=o[0],i=o[1],s=o[2],u=o[3],c=e.reshape([i,r]),l=t.reshape([t.size/s,s]),h=new is(r,u,[i,s]);return this.compileAndRun(h,[l,c]).reshape(a)},o.prototype.fill=function(t,e,n){if("string"===(n=n||j(e))){var r=P(n,k(t));return r.fill(e),Lt.makeTensor(r,t,n,this)}var o=new os(t,e),a=o.getCustomSetupFunc(e);return this.compileAndRun(o,[],n,a)},o.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)},o.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},o.prototype.linspace=function(t,e,n){return ka(t,e,n)},o.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},o.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Lt.makeTensorFromDataId(n,t,e,this)},o.prototype.unpackTensor=function(t){var e=new Bu(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},o.prototype.packTensor=function(t){var e=new Bs(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},o.prototype.packedReshape=function(t,e){var n=[Ae(t.shape)].concat(Te(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},o=[Ae(e)].concat(Te(e)),a=new zs(o,n),i=this.runWebGLProgram(a,[r],t.dtype,null,!0);return{dataId:i.dataId,shape:e,dtype:i.dtype}},o.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=De(o);e=r?new Xi(i):new ji(i);return{dtype:a,shape:o,dataId:this.runWebGLProgram(e,[{shape:i,dtype:a,dataId:t}],a,null,!0).dataId}},o.prototype.runWebGLProgram=function(t,e,n,r,o){var a=this;void 0===o&&(o=!1);var s=this.makeTensorInfo(t.outputShape,n),u=this.texData.get(s.dataId);if(t.packedOutput&&(u.isPacked=!0),t.outPackingScheme===Vt.DENSE){var c=Yt(t.outputShape);u.texShape=c.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(u.usage=t.outTexUsage),0===k(s.shape))return u.values=B(s.dtype,0),s;var l=[],h=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=a.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&k(e.shape)<=i().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?a.unpackTensor(e):a.packTensor(e),l.push(e),n=a.texData.get(e.dataId);else if(n.isPacked&&!_e(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=a.packedReshape(e,o),l.push(e),n=a.texData.get(e.dataId),r.shape=o}return a.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(s.dataId);var f,d={shape:s.shape,texData:u,isUniform:!1},p=function(t,e,n){var r="";e.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 o=t.userCode,a=t.constructor.name;return a+="_"+r+"_"+o}(t,h,d),v=this.getAndSaveBinary(p,(function(){return function(t,e,n,r){var o=e.userCode,a=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}})),s=a.map((function(t){return t.shapeInfo})),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=Za(a,u,o,e.packedInputs),l=t.createProgram(c),h=null,f=t.getUniformLocation(l,"NAN",!1);1===i().getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(l,"INFINITY",!1));for(var d={},p=0;p<e.variableNames.length;p++){var v=e.variableNames[p];d[v]=t.getUniformLocation(l,v,!1),d["offset"+v]=t.getUniformLocation(l,"offset"+v,!1)}return{program:e,source:c,webGLProgram:l,uniformLocations:d,inShapeInfos:s,outShapeInfo:u,infLoc:h,nanLoc:f}}(a.gpgpu,t,h,d)})),g=null!=this.activeTimers;if(g&&(f=this.startTimer()),function(t,e,n,r,o){ks(e.inShapeInfos,n),ks([e.outShapeInfo],[r]);var a=r.texData.texture,s=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(a,s[0],s[1]):t.setOutputMatrixTexture(a,s[0],s[1]),t.setProgram(e.webGLProgram),1===i().getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach((function(n,r){var o=e.program.variableNames[r],a=e.uniformLocations[o],i=e.uniformLocations["offset"+o];if(null!=a)if(n.isUniform)if(k(n.shape)<2)t.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(a,s)}else null!=n.texData.slice&&null!=i&&t.gl.uniform1i(i,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,a,r)})),null!=o&&o(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,v,h,d,r),l.forEach((function(t){return a.disposeData(t.dataId)})),g&&(f=this.endTimer(f),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(f)})),!i().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&!1===o){var m=this.unpackTensor(s);return this.disposeData(s.dataId),m}return s},o.prototype.compileAndRun=function(t,e,n,r,o){void 0===o&&(o=!1),n=n||e[0].dtype;var a=this.runWebGLProgram(t,e,n,r,o);return Lt.makeTensorFromDataId(a.dataId,a.shape,a.dtype)},o.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},o.prototype.getTextureManager=function(){return this.textureManager},o.prototype.dispose=function(){var t=this;if(!this.disposed){if(!i().getBool("IS_TEST"))Object.keys(this.binaryCache).forEach((function(e){t.gpgpu.deleteProgram(t.binaryCache[e].webGLProgram),delete t.binaryCache[e]}));this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}},o.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Ze((function(){if(!i().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=i().getBool("DEBUG");i().set("DEBUG",!1);var n=t.abs(On(1e-8)).dataSync()[0];if(i().set("DEBUG",e),n>0)return 32}return 16}))),this.floatPrecisionValue},o.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},o.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var c,l=null!=this.activeTimers;l&&(c=et());var h=n.texShape;if(null==h&&(h=Ne(r,u),n.texShape=h),null!=a){var f=De(r),d=void 0,p=h[1],v=h[0],g=a instanceof Uint8Array;u?(p=(e=$t(h[0],h[1]))[0],v=e[1],d=new ts(f,[v,p],g)):d=new Zi(f,[v,p],g);var m=this.makeTensorInfo([v,p],o);this.texData.get(m.dataId).usage=g?zt.PIXELS:zt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(m.dataId),p,v,a);var y=this.runWebGLProgram(d,[m],o,null,!0),x=this.texData.get(y.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(m.dataId),this.texData.delete(y.dataId),n.values=null,l&&(this.uploadWaitMs+=et()-c)}else{var b=this.acquireTexture(h,s,o,u);n.texture=b}}},o.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;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,r)),n.values},o.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},o.prototype.computeBytes=function(t,e){return t[0]*t[1]*z(e)},o}(la);Wt()&&Lt.registerBackend("webgl",(function(){return new Uu}),2);"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Vu(t,e){return t(e={exports:{}},e.exports),e.exports}var zu=Vu((function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>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}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.alea=a}(0,t,!1)})),Gu=Vu((function(t){!function(t,e,n){function r(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<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xor128=a}(0,t,!1)})),Hu=Vu((function(t){!function(t,e,n){function r(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<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}function o(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 a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xorwow=a}(0,t,!1)})),qu=Vu((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xorshift7=a}(0,t,!1)})),Ku=Vu((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=i,t.X=s,t.i=o}(e,t)}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xor4096=a}(0,t,!1)})),ju=Vu((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-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<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.tychei=a}(0,t,!1)})),Xu=Vu((function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),c=n.pow(2,52),l=2*c,h=a-1;function f(t,h,f){var m=[],y=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==a?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,g(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),g(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date,o,i,o.screen,g(e)]}}():t,3),m),x=new d(m),b=function(){for(var t=x.g(i),e=u,n=0;t<c;)t=(t+n)*a,e*=a,n=x.g(1);for(;t>=l;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,v(g(x.S),e),(h.pass||f||function(t,e,r,o){return o&&(o.S&&p(o,x),t.state=function(){return p(x,{})}),r?(n[s]=t,e):t})(b,y,"global"in h?h.global:this==n,h.state)}function d(t){var e,n=t.length,r=this,o=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o<a;)s[o]=o++;for(o=0;o<a;o++)s[o]=s[i=h&i+t[o%n]+(e=s[o])],s[i]=e;(r.g=function(t){for(var e,n=0,o=r.i,i=r.j,s=r.S;t--;)e=s[o=h&o+1],n=n*a+s[h&(s[o]=s[i=h&i+e])+(s[i]=e)];return r.i=o,r.j=i,n})(a)}function p(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function v(t,e){for(var n,r=t+"",o=0;o<r.length;)e[h&o]=h&(n^=19*e[h&o])+r.charCodeAt(o++);return g(e)}function g(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=f,v(n.random(),e),t.exports){t.exports=f;try{r=__webpack_require__(480)}catch(t){}}}([],Math)}));Xu.alea=zu,Xu.xor128=Gu,Xu.xorwow=Hu,Xu.xorshift7=qu,Xu.xor4096=Ku,Xu.tychei=ju;var Yu=Xu.alea;var $u=An({addN_:function(t){C(Array.isArray(t),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),C(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 gn(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(!S(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Lt.runKernelFunc((function(t,n){return t.addN(e)}),r,null,"AddN")}});function Qu(){Xe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}function Ju(t){return 0===t.rank||1===t.rank?t.as4D(1,1,1,t.size):2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function Zu(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u=gn(t,"x","batchNorm"),c=gn(e,"mean","batchNorm"),l=gn(n,"variance","batchNorm");null!=o&&(i=gn(o,"scale","batchNorm")),null!=r&&(s=gn(r,"offset","batchNorm")),C(c.rank===l.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),C(null==s||c.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),C(null==i||c.rank===i.rank,(function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}));var h={x:u,scale:i,offset:s,mean:c,variance:l},f={varianceEpsilon:a};return Lt.runKernelFunc((function(t,e){var n=Ju(u),r=t.batchNormalization(n,tc(c),tc(l),a,tc(i),tc(s));return e([u,c,l,i]),r}),h,null,"FusedBatchNorm",f).reshape(u.shape)}function tc(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}var ec=An({batchNormalization_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Qu(),Zu(t,e,n,a,o,r)}}),nc=An({batchNorm_:Zu});function rc(t,e,n,r,o,a){var i,s,u=gn(t,"x","batchNorm"),c=gn(e,"mean","batchNorm"),l=gn(n,"variance","batchNorm");return null!=o&&(i=gn(o,"scale","batchNorm")),null!=r&&(s=gn(r,"offset","batchNorm")),C(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),C(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),C(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!=i&&C(2===i.rank||1===i.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."})),null!=s&&C(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),nc(u,c,l,s,i,a)}var oc=An({batchNormalization2d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Qu(),rc(t,e,n,a,o,r)}}),ac=An({batchNorm2d_:rc});function ic(t,e,n,r,o,a){var i,s,u=gn(t,"x","batchNorm"),c=gn(e,"mean","batchNorm"),l=gn(n,"variance","batchNorm");return null!=o&&(i=gn(o,"scale","batchNorm")),null!=r&&(s=gn(r,"offset","batchNorm")),C(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),C(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),C(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!=i&&C(3===i.rank||1===i.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."})),null!=s&&C(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),nc(u,c,l,s,i,a)}var sc=An({batchNormalization3d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Qu(),ic(t,e,n,a,o,r)}}),uc=An({batchNorm3d_:ic});function cc(t,e,n,r,o,a){var i,s,u=gn(t,"x","batchNorm"),c=gn(e,"mean","batchNorm"),l=gn(n,"variance","batchNorm");return null!=o&&(i=gn(o,"scale","batchNorm")),null!=r&&(s=gn(r,"offset","batchNorm")),C(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),C(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),C(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!=i&&C(4===i.rank||1===i.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."})),null!=s&&C(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),nc(u,c,l,s,i,a)}var lc=An({batchNormalization4d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Qu(),cc(t,e,n,a,o,r)}}),hc=An({batchNorm4d_:cc});var fc=An({broadcastTo_:function(t,e){var n=gn(t,"broadcastTo","x"),r=n.shape;if(e.some((function(t){return!(t>0)||t%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.length<n.rank)throw new Error("broadcastTo(): shape.length="+e.length+" < input.rank="+n.rank+".");if(e.length>n.rank){for(var o=n.shape.slice();o.length<e.length;)o.unshift(1);n=n.reshape(o)}for(var a=n.shape,i=Array.from(e),s=e.length-1;s>=0;s--)if(a[s]===e[s])i[s]=1;else if(1!==n.shape[s])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var u=i.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));if(0===u.length)return n.clone();var c={x:n},l={shape:e,inputShape:a};return Lt.runKernelFunc((function(t){return t.tile(n,i)}),c,(function(t){return{x:function(){return t.sum(u,!0)}}}),Sr,l)}});var dc=An({clone_:function(t){var e=gn(t,"x","clone",null);return Lt.runKernelFunc((function(){return Lt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{x:e},null,Tr)}});var pc=An({logicalAnd_:function(t,e){var n=gn(t,"a","logicalAnd","bool"),r=gn(e,"b","logicalAnd","bool");return Pr(n.shape,r.shape),Lt.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),vc=An({logicalNot_:function(t){var e=gn(t,"x","logicalNot","bool");return Lt.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),gc=An({logicalOr_:function(t,e){var n=gn(t,"a","logicalOr","bool"),r=gn(e,"b","logicalOr","bool");return Pr(n.shape,r.shape),Lt.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),mc=An({logicalXor_:function(t,e){var n=gn(t,"a","logicalXor","bool"),r=gn(e,"b","logicalXor","bool");return Pr(n.shape,r.shape),gc(t,e).logicalAnd(pc(t,e).logicalNot())}}),yc=An({where_:function(t,e,n){var r=gn(e,"a","where"),o=gn(n,"b","where"),a=gn(t,"condition","where","bool");return E(r.shape,o.shape,"Error in where: "),1===a.rank?C(a.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):E(a.shape,o.shape,"Error in where: "),Lt.runKernelFunc((function(t,e){var n=t.select(a,r,o);return e([a]),n}),{$condition:a,$a:r,$b:o},(function(t,e){var n=e[0];return{$condition:function(){return Xn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),xc=function(t){return n(this,void 0,void 0,(function(){var e,n,o;return r(this,(function(r){switch(r.label){case 0:return[4,(e=gn(t,"condition","whereAsync","bool")).data()];case 1:return n=r.sent(),o=Ga(e.shape,n),t!==e&&e.dispose(),[2,o]}}))}))};var bc=An({divNoNan_:function(t,e){var n,r=gn(t,"a","div"),o=gn(e,"b","div");r=(n=Nt(r,o))[0],o=n[1];var a=Bo(r,o),i=Xn(a),s=o.equal(i);return yc(s,i,a)}});var wc=An({tile_:function(t,e){var n=gn(t,"x","tile",null);C(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}));var r=[n],o={x:n},a={reps:e};return Lt.runKernelFunc((function(t,r){var o=t.tile(n,e);return r([n]),o}),o,null,Dr,a,r)}});var Cc=An({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=er([t,e],r),a=t<=e?t:e,i=0;i<a;++i)o.set(1,i,i);var s=o.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return wc(sr(s,0),[n[0],1,1]);if(2===n.length)return wc(sr(sr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return wc(sr(sr(sr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}});var Ec=An({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=gn(t,"logits","multinomial"),a=o.size,i=o.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=Lt.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===i?u.as1D():u}});var Rc=An({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 o=gn(t,"indices","oneHot","int32"),a=o.shape.concat([e]),i={indices:o=o.flatten()},s={depth:e,onValue:n,offValue:r};return Lt.runKernelFunc((function(t,a){return a([o]),t.oneHot(o,e,n,r)}),i,null,Ar,s).reshape(a)}});var Ic=An({pad_:function(t,e,n){void 0===n&&(n=0);var r=gn(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:e,constantValue:n},a={x:r};return Lt.runKernelFunc((function(t,o){return o([r]),t.pad(r,e,n)}),a,null,Nr,o)}});var kc=An({pad1d_:function(t,e,n){return void 0===n&&(n=0),C(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),Ic(t,[e],n)}});var Sc=An({pad2d_:function(t,e,n){return void 0===n&&(n=0),C(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Ic(t,e,n)}});var Ac=An({pad3d_:function(t,e,n){return void 0===n&&(n=0),C(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."})),Ic(t,e,n)}});var Tc=An({pad4d_:function(t,e,n){return void 0===n&&(n=0),C(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."})),Ic(t,e,n)}});var Dc=An({rand_:function(t,e,n){var r=k(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r)}for(var a=0;a<r;a++)o[a]=e();return Lt.makeTensor(o,t,n)}}),Nc=.001,Fc=.1;function _c(){return 32===Lt.backend.floatPrecision()?Nc:Fc}function Oc(t,e,n){var r=!0;if((V(t)||V(e))&&(r=!1),V(t)&&V(e)&&(r=!0),r){var o=t.constructor.name,a=e.constructor.name;if(o!==a)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+a)}if(Array.isArray(t)&&Array.isArray(e)){var i=pn(t),s=pn(e);if(!S(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=V(t)?t:I(t),c=V(e)?e:I(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;l<c.length;++l){var h=u[l],f=c[l];if(!n(h,f))throw new Error("Arrays differ: actual["+l+"] = "+h+", expected["+l+"] = "+f+".\nActual: "+u+".\nExpected: "+c+".")}}function Mc(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var Bc=Object.freeze({TEST_EPSILON_FLOAT16:Fc,expectArraysClose:function(t,e,n){return null==n&&(n=_c()),Oc(t,e,(function(t,e){return Mc(t,e,n)}))},testEpsilon:_c,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 H(t)||H(t[0])||H(e)||H(e[0])?Oc(t,n,(function(t,e){return t==e})):Oc(t,e,(function(t,e){return Mc(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=_c()),!Mc(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;r<t.length;r++)if(t[r]<e||t[r]>n)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))}}),Pc=function(){function t(t,e,n,r,o){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var a=o||Math.random();this.random=Yu(a.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var o=void 0,a=void 0,i=void 0;do{i=(o=2*this.random()-1)*o+(a=2*this.random()-1)*a}while(i>=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*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}(),Lc=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=Yu(o.toString()),this.randn=new Pc(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,o,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(o=this.randu())<e||Math.log(o)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),Wc=function(){function t(t,e,n,r){var o=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==o.dtype||"float32"===o.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=Yu(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}();var Uc=An({randomGamma_:function(t,e,n,r,o){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var a=new Lc(e,n,r,o),i=er(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}});var Vc=An({randomNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new Pc(e,n,r,!1,o),i=er(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}});var zc=An({randomUniform_:function(t,e,n,r,o){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var a=er(t,r),i=new Wc(e,n,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}});var Gc=An({square_:function(t){var e=gn(t,"x","square"),n=[e];return Lt.runKernelFunc((function(t,n){return n([e]),t.square(e)}),{x:e},null,"Square",{},n,[])}});var Hc=An({squaredDifference_:function(t,e){var n,r=gn(t,"a","squaredDifference"),o=gn(e,"b","squaredDifference");n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape);var a={a:r,b:o},i=[r,o];return Lt.runKernelFunc((function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n}),a,(function(t,e){var n=e[0],r=e[1],o=On(2);return{a:function(){return t.mul(n.sub(r).mul(o))},b:function(){return t.mul(r.sub(n).mul(o))}}}),Er,{},i,[])}});var qc=An({truncatedNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");for(var a=new Pc(e,n,r,!0,o),i=er(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}});var Kc=An({equal_:function(t,e){var n,r=gn(t,"a","equal"),o=gn(e,"b","equal");return n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.equal(r,o)}),{$a:r,$b:o})}}),jc=An({equalStrict_:function(t,e){var n=gn(t,"a","equalStrict"),r=gn(e,"b","equalStrict");return E(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),Xc=An({greater_:function(t,e){var n,r=gn(t,"a","greater"),o=gn(e,"b","greater");return n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.greater(r,o)}),{a:r,b:o},null,"Greater")}}),Yc=An({greaterEqual_:function(t,e){var n,r=gn(t,"a","greaterEqual"),o=gn(e,"b","greaterEqual");return n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.greaterEqual(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){return Xn(n)},b:function(){return Xn(r)}}}),"GreaterEqual")}}),$c=An({greaterEqualStrict_:function(t,e){var n=gn(t,"a","greaterEqualStrict"),r=gn(e,"b","greaterEqualStrict");return E(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),Qc=An({greaterStrict_:function(t,e){var n=gn(t,"a","greaterStrict"),r=gn(e,"b","greaterStrict");return E(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),Jc=An({less_:function(t,e){var n,r=gn(t,"a","less"),o=gn(e,"b","less");return n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.less(r,o)}),{a:r,b:o},null,"Less")}}),Zc=An({lessEqual_:function(t,e){var n,r=gn(t,"a","lessEqual"),o=gn(e,"b","lessEqual");return n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.lessEqual(r,o);return e([r,o]),n}),{a:r,b:o},null,"LessEqual")}}),tl=An({lessEqualStrict_:function(t,e){var n=gn(t,"a","lessEqualStrict"),r=gn(e,"b","lessEqualStrict");return E(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),el=An({lessStrict_:function(t,e){var n=gn(t,"a","lessStrict"),r=gn(e,"b","lessStrict");return E(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),nl=An({notEqual_:function(t,e){var n,r=gn(t,"a","notEqual"),o=gn(e,"b","notEqual");return n=Nt(r,o),r=n[0],o=n[1],Pr(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.notEqual(r,o)}),{a:r,b:o},null,"NotEqual")}}),rl=An({notEqualStrict_:function(t,e){var n=gn(t,"a","notEqualStrict"),r=gn(e,"b","notEqualStrict");return E(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function ol(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function al(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e}var il=An({gather_:function(t,e,n){void 0===n&&(n=0);var r=gn(t,"x","gather"),o=gn(e,"indices","gather","int32");n=O(n,r.shape)[0];var a=function(t,e,n){for(var r=t.shape[n],o=[],a=1,i=1,s=0;s<n;s++)o.push(t.shape[s]),a*=t.shape[s];for(s=0;s<e.rank;s++)o.push(e.shape[s]);for(s=n+1;s<t.rank;s++)o.push(t.shape[s]),i*=t.shape[s];return{batchSize:a,sliceSize:i,dimSize:r,outputShape:o}}(r,o,n);return Lt.runKernelFunc((function(t,e){var a=t.gather(r,o.flatten(),n);return e([o]),a}),{x:r,indices:o},(function(t,e){var o=e[0];return{x:function(){var e=r.shape,a=o.size,i=e.slice(0,n),s=i.length,u=e.slice(n,e.length).slice(1),c=u.length,l=ol(0,s),h=ol(s+1,s+1+c),f=al([i,[a],u]),d=t.reshape(f),p=o.reshape([a]),v=al([[s],l,h]),g=d.transpose(v),m=sl(g,p,r.shape[n]),y=Rn(v);return m=m.transpose(y)},indices:function(){return o}}}),"Gather",{axis:n}).reshape(a.outputShape)}}),sl=An({unsortedSegmentSum_:function(t,e,n){var r=gn(t,"x","unsortedSegmentSum"),o=gn(e,"segmentIds","unsortedSegmentSum","int32");return C(A(n),(function(){return"numSegments must be of dtype int"})),Lt.runKernelFunc((function(t,e){var a=t.unsortedSegmentSum(r,o,n);return e([o]),a}),{$x:r},(function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=Eo(e,Xn(e)),r=il(t,n),o=Yc(e,On(0,"int32")),a=r.rank-o.rank,i=0;i<a;++i)o=sr(o,i+1);o=pc(o,zn(r.shape,"bool"));var s=Xn(r);return yc(o,r,s)}(t,n)}}}))}});var ul=function(t,e,o){return n(this,void 0,void 0,(function(){var n,a,i,s,u,c,l,h,f,d,p,v,g;return r(this,(function(r){switch(r.label){case 0:for(n=gn(t,"tensor","boolMask"),a=gn(e,"mask","boolMask","bool"),i=null==o?0:o,s=a.rank,u=n.shape,C(s>0,(function(){return"mask cannot be scalar"})),E(u.slice(i,i+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),c=1,l=i;l<i+s;l++)c*=u[l];return h=u.slice(0,i).concat([c],u.slice(i+s)),f=n.reshape(h),d=a.reshape([-1]),[4,xc(d)];case 1:return p=r.sent(),v=p.squeeze([1]),g=il(f,v,i),t!==n&&n.dispose(),e!==a&&a.dispose(),v.dispose(),f.dispose(),d.dispose(),p.dispose(),[2,g]}}))}))};function cl(t,e,n,r,o,a,i){void 0===a&&(a="NHWC"),C(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var s=t,u=e,c=!1;3===e.rank&&(c=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),C(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),C(4===u.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank})),C(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var l="NHWC"===a?s[3]:s[1],h="NHWC"===a?u.shape[3]:u.shape[1];C(l===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."})),C(h===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+n.shape[3]+"."})),null!=i&&C(A(o),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var f=Ea(a),d=pa(s,n.shape,r,1,o,i,!1,f),p=Lt.runKernelFunc((function(t,e){var r=t.conv2dDerInput(u,n,d);return e([n,u]),r}),{dy4D:u,filter:n},(function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return dl(t,n,r,o,a,1,i)},filter:function(){return vl(t,s,n.shape,r,o,a,i)}}}));return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function ll(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function hl(t,e,n,r,o){C(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var a=t,i=e,s=!1;4===e.rank&&(s=!0,i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),a=[1,t[0],t[1],t[2],t[3]]);var u=a[4],c=i.shape[4];C(5===a.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."})),C(5===i.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank})),C(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),C(u===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."})),C(c===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[4]+"."}));var l=va(a,n.shape,r,1,o),h=Lt.runKernelFunc((function(t){return t.conv3dDerInput(i,n,l)}),{dy5D:i});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var fl=An({conv1d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NWC"),void 0===a&&(a=1);var s=gn(t,"x","conv1d"),u=gn(e,"filter","conv1d"),c=s,l=!1;2===s.rank&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),C(3===c.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."})),C(3===u.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."})),null!=i&&C(A(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."})),C(c.shape[2]===u.shape[1],(function(){return"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+u.shape[1]+"."})),C(Ca(n,a),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'"})),C("NWC"===o,(function(){return"Error in conv1d: got dataFormat of "+o+" but only NWC is currently supported."}));var h=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),f=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),d=dl(f,h,[1,n],r,"NHWC",[1,a],i);return l?d.as2D(d.shape[2],d.shape[3]):d.as3D(d.shape[0],d.shape[2],d.shape[3])}}),dl=An({conv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=gn(t,"x","conv2d"),u=gn(e,"filter","conv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(4===c.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."})),C(4===u.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."})),null!=i&&C(A(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var h="NHWC"===o?c.shape[3]:c.shape[1];C(h===u.shape[2],(function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."})),C(Ca(n,a),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}));var f=Ea(o),d=pa(c.shape,u.shape,n,a,r,i,!1,f),p=[u,c],v=Lt.runKernelFunc((function(t,e){var n=t.conv2d(c,u,d);return e([u,c]),n}),{x:c,filter:u},(function(t,e){var i=e,s=i[0],u=i[1];return C(wa(a),(function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"})),{x:function(){return gl(u.shape,t,s,n,r,o)},filter:function(){return vl(u,t,s.shape,n,r,o)}}}),"Conv2D",d,p);return l?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),pl=An({conv3d_:function(t,e,n,r,o,a){void 0===o&&(o="NDHWC"),void 0===a&&(a=[1,1,1]);var i=gn(t,"x","conv3d"),s=gn(e,"filter","conv3d"),u=i,c=!1;4===i.rank&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),C(5===u.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."})),C(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),C(u.shape[4]===s.shape[3],(function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."})),C(function(t,e){return ll(t)||ll(e)}(n,a),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),C("NDHWC"===o,(function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."}));var l=va(u.shape,s.shape,n,a,r),h=Lt.runKernelFunc((function(t,e){var n=t.conv3d(u,s,l);return e([u,s]),n}),{x:u,$filter:s},(function(t,e){C(ll(a),(function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"}));var o=e[0],i=e[1];return{x:function(){return hl(o.shape,t,i,n,r)},$filter:function(){return function(t,e,n,r,o){var a=t;4===t.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var i=e;4===i.rank&&(i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]));C(5===a.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+"."})),C(5===i.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."})),C(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),C(a.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+"."})),C(i.shape[4]===n[4],(function(){return"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+n[4]+")."}));var s=va(a.shape,n,r,1,o);return Lt.runKernelFunc((function(t){return t.conv3dDerFilter(a,i,s)}),{x5D:a,dy5D:i})}(o,t,i.shape,n,r)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),vl=An({conv2dDerFilter_:function(t,e,n,r,o,a,i){void 0===a&&(a="NHWC");var s=t;3===t.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var u=e;3===u.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),C(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),C(4===u.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."})),C(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var c="NHWC"===a?s.shape[3]:s.shape[1],l="NHWC"===a?u.shape[3]:u.shape[1];C(c===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+n[2]+"."})),C(l===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+n[3]+")."})),null!=i&&C(A(o),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var h=Ea(a),f=pa(s.shape,n,r,1,o,i,!1,h);return Lt.runKernelFunc((function(t){return t.conv2dDerFilter(s,u,f)}),{x4D:s,dy4D:u})}}),gl=An({conv2dDerInput_:cl}),ml=An({depthwiseConv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=gn(t,"x","depthwiseConv2d"),u=gn(e,"filter","depthwiseConv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(4===c.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."})),C(4===u.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."})),C(c.shape[3]===u.shape[2],(function(){return"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."})),null==a&&(a=[1,1]),C(Ca(n,a),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=i&&C(A(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var h=pa(c.shape,u.shape,n,a,r,i,!0),f=[c,u],d=Lt.runKernelFunc((function(t,e){var n=t.depthwiseConv2D(c,u,h);return e([c,u]),n}),{x:c,filter:u},(function(t,e){C(wa(a),(function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+a+"'"}));var n=e[0],r=e[1];return{x:function(){return yl(n.shape,t,r,h)},filter:function(){return xl(n,t,r.shape,h)}}}),"DepthwiseConv2dNative",h,f);return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}}),yl=An({depthwiseConv2dDerInput_:function(t,e,n,r){var o=e,a=!1;3===e.rank&&(a=!0,o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=Lt.runKernelFunc((function(t){return t.depthwiseConv2DDerInput(o,n,r)}),{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),xl=An({depthwiseConv2dDerFilter_:function(t,e,n,r){var o=t;3===t.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var a=e;return 3===a.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Lt.runKernelFunc((function(t){return t.depthwiseConv2DDerFilter(o,a,r)}),{x4D:o,dy4D:a})}}),bl=An({separableConv2d_:function(t,e,n,r,o,a,i){void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC");var s=gn(t,"x","separableConv2d"),u=gn(e,"depthwiseFilter","separableConv2d"),c=gn(n,"pointwiseFilter","separableConv2d"),l=s,h=!1;if(3===s.rank&&(h=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");C(4===l.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."})),C(4===u.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."})),C(4===c.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."})),C(1===c.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+c.shape[0]+"."})),C(1===c.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."}));var f=u.shape[2],d=u.shape[3];C(c.shape[2]===f*d,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+f*d+", but got "+c.shape[2]+"."}));var p=ml(l,u,r,o,i,a),v=dl(p,c,1,"valid",i);return h?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),wl=An({conv2dTranspose_:function(t,e,n,r,o,a){return cl(n,gn(t,"x","conv2dTranspose"),gn(e,"filter","conv2dTranspose"),r,o,"NHWC",a)}}),Cl=An({conv3dTranspose_:function(t,e,n,r,o){return hl(n,gn(t,"x","conv3dTranspose"),gn(e,"filter","conv3dTranspose"),r,o)}});var El=An({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=gn(t,"a","matMul"),i=gn(e,"b","matMul");o=Nt(a,i),a=o[0],i=o[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],u=r?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?a.shape[a.rank-1]:a.shape[a.rank-2],l=r?i.shape[i.rank-2]:i.shape[i.rank-1],h=a.shape.slice(0,-2),f=i.shape.slice(0,-2),d=k(h),p=k(f);C(a.rank>=2&&i.rank>=2&&a.rank===i.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."})),C(S(h,f),(function(){return"Error in matMul: outer dimensions ("+h+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."})),C(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var v=a.shape.slice(0,-2).concat([c,l]),g=n?a.as3D(d,s,c):a.as3D(d,c,s),m=r?i.as3D(p,l,u):i.as3D(p,u,l),y={transposeA:n,transposeB:r};return Lt.runKernelFunc((function(t,e){var o=t.batchMatMul(g,m,n,r);return e([g,m]),o}),{a:g,b:m},(function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{a:function(){return t.matMul(i,!1,!1)},b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{a:function(){return i.matMul(t,!1,!0)},b:function(){return a.matMul(t,!1,!1)}}:{a:function(){return i.matMul(t,!0,!0)},b:function(){return t.matMul(a,!0,!0)}}:{a:function(){return t.matMul(i,!1,!0)},b:function(){return a.matMul(t,!0,!1)}}}),"BatchMatMul",y).reshape(v)}}),Rl=An({dot_:function(t,e){var n=gn(t,"t1","dot"),r=gn(e,"t2","dot");C(!(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 o=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return C(o===a,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."})),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]))}}),Il=An({outerProduct_:function(t,e){var n=gn(t,"v1","outerProduct"),r=gn(e,"v2","outerProduct");return C(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))}});var kl=An({reverse_:function(t,e){var n=gn(t,"x","reverse");if(0===n.rank)return n.clone();var r=O(e,n.shape);return Lt.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),Sl=An({reverse1d_:function(t){var e=gn(t,"x","reverse");return C(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),kl(e,0)}}),Al=An({reverse2d_:function(t,e){var n=gn(t,"x","reverse");return C(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),kl(n,e)}}),Tl=An({reverse3d_:function(t,e){var n=gn(t,"x","reverse");return C(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),kl(n,e)}}),Dl=An({reverse4d_:function(t,e){var n=gn(t,"x","reverse");return C(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),kl(n,e)}});function Nl(t,e,n,r,o,a){var i=gn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),C(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),C(Ca(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=a&&C(A(o),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=fa(s.shape,e,n,r,o,a);if(1===c.filterWidth&&1===c.filterHeight&&S(c.inShape,c.outShape))return i.clone();var l=[s],h=Lt.runKernelFunc((function(t,e){var n=t.maxPool(s,c);return e([s,n]),n}),{x:s},(function(t,a){var i=a[0],s=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=gn(t,"dy","maxPoolBackprop"),c=gn(e,"input","maxPoolBackprop"),l=gn(n,"output","maxPoolBackprop");C(c.rank===u.rank,(function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"})),null==a&&(a=[1,1]);C(Ca(o,a),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),C(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),C(4===c.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."})),null!=s&&C(A(i),(function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var h=fa(c.shape,r,o,a,i,s);return Lt.runKernelFunc((function(t){return t.maxPoolBackprop(u,c,l,h)}),{$dy:u,$input:c})}(t,i,s,e,n,r,o)}}}),"MaxPool",c,l);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function Fl(t,e,n,r,o,a){var i=gn(t,"x","avgPool","float32");null==r&&(r=[1,1]),C(Ca(n,r),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}));var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),C(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=a&&C(A(o),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=fa(s.shape,e,n,r,o,a);if(1===c.filterWidth&&1===c.filterHeight&&S(c.inShape,c.outShape))return i.clone();var l=Lt.runKernelFunc((function(t){return t.avgPool(s,c)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,o,a){var i=gn(t,"dy","avgPoolBackprop"),s=gn(e,"input","avgPoolBackprop");C(s.rank===i.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"})),null==o&&(o=[1,1]);C(Ca(r,o),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}));var u=s,c=i,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));C(4===c.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),C(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var h=fa(u.shape,n,r,o,a),f=Lt.runKernelFunc((function(t){return t.avgPoolBackprop(c,u,h)}),{dy4D:c,input4D:u});if(l)return f.as3D(f.shape[1],f.shape[2],f.shape[3]);return f}(t,s,e,n,r,o)}}}),"AvgPool",c);return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var _l=An({maxPool_:function(t,e,n,r,o){return Nl(t,e,n,1,r,o)}}),Ol=An({avgPool_:function(t,e,n,r,o){return Fl(t,e,n,1,r,o)}}),Ml=An({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=gn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),C(Ca(a,o),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"}));var c,l=fa(s.shape,e,a,o,r),h=[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)})),o=n.map((function(t,e){return t-r[e]}));return n.map((function(t,e){return[r[e],o[e]]}))}([l.filterHeight,l.filterWidth],h):[[0,0],[0,0]];var f=1===h[0]&&1===h[1],d=function(t,e,n){var r=n.map((function(t){return t[0]})),o=n.map((function(t){return t[1]})),a=t.concat(r,o),i=e.map((function(t,e){return(t-a[e]%t)%t})),s=o.map((function(t,e){return t+i[e]})),u=e.map((function(t,e){return[r[e],s[e]]})),c=e.map((function(t,e){return[0,i[e]]}));return[u,c]}([l.inHeight,l.inWidth],h,c),p=d[0],v=d[1],g=f?r:"valid",m=f?s:cr(s,h,p),y=("avg"===n?function(){return Fl(m,e,a,1,g)}:function(){return Nl(m,e,a,1,g)})(),x=f?y:rr(y,h,v);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),Bl=An({maxPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=gn(t,"x","maxPool3d"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),C(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),C("NDHWC"===a,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),C(Ca(n,i),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&C(A(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=da(u.shape,e,n,i,r,o,a),h=Lt.runKernelFunc((function(t,e){var n=t.maxPool3d(u,l);return e([u,n]),n}),{x:u},(function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=gn(t,"dy","maxPool3dBackprop"),c=gn(e,"input","maxPool3dBackprop"),l=gn(n,"output","maxPool3dBackprop"),h=u,f=c,d=l,p=!1;4===c.rank&&(p=!0,h=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),d=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]));C(5===h.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."})),C(5===f.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+f.rank+"."})),C(5===d.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."})),null==a&&(a=[1,1,1]);C(Ca(o,a),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),null!=s&&C(A(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var v=da(f.shape,r,o,a,i,s),g=Lt.runKernelFunc((function(t){return t.maxPool3dBackprop(h,f,d,v)}),{dy5D:h,input5D:f});if(p)return g.as4D(g.shape[1],g.shape[2],g.shape[3],g.shape[4]);return g}(t,s,u,e,n,i,r,o)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Pl=An({avgPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=gn(t,"x","avgPool3d","float32"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),C(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),C("NDHWC"===a,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),C(Ca(n,i),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&C(A(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=da(u.shape,e,n,i,r,o,a),h=Lt.runKernelFunc((function(t){return t.avgPool3d(u,l)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,o,a,i){var s=gn(t,"dy","avgPool3dBackprop"),u=gn(e,"input","avgPool3dBackprop"),c=s,l=u,h=!1;4===u.rank&&(h=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),l=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]));C(5===c.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."})),C(5===l.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+l.rank+"."})),null==o&&(o=[1,1,1]);C(Ca(r,o),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"})),null!=i&&C(A(a),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var f=da(l.shape,n,r,o,a,i),d=Lt.runKernelFunc((function(t){return t.avgPool3dBackprop(c,l,f)}),{dy5D:c,input5D:l});if(h)return d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]);return d}(t,u,e,n,i,r,o)}}}));return h=h.cast(u.dtype),c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Ll=An({maxPoolWithArgmax_:function(t,e,n,r,o){void 0===o&&(o=!1);var a=gn(t,"x","maxPoolWithArgmax"),i={filterSize:e,strides:n,pad:r,includeBatchInIndex:o},s=Lt.runKernel("MaxPoolWithArgmax",{x:a},i);return{result:s[0],indexes:s[1]}}});var Wl=An({slice_:function(t,e,n){var r,o,a=gn(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length<a.rank?e.concat(new Array(a.rank-e.length).fill(0)):e.slice()).forEach((function(t){C(-1!==t,(function(){return"slice() does not support negative begin indexing."}))})),o=(o=null==n?new Array(a.rank).fill(-1):"number"==typeof n?[n].concat(new Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(new Array(a.rank-n.length).fill(-1)):n).map((function(t,e){return t>=0?t:(C(-1===t,(function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."})),a.shape[e]-r[e])})),qo(a,r,o);var i=a.shape,s={begin:r,size:o};return Lt.runKernelFunc((function(t){return t.slice(a,r,o)}),{x:a},(function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],i[n]-r[n]-o[n]]);return{x:function(){return Ic(t,e)}}}),"Slice",s)}}),Ul=An({slice1d_:function(t,e,n){var r=gn(t,"x","slice1d");return C(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),Wl(r,[e],[n])}}),Vl=An({slice2d_:function(t,e,n){var r=gn(t,"x","slice2d");return C(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),Wl(r,e,n)}}),zl=An({slice3d_:function(t,e,n){var r=gn(t,"x","slice3d");return C(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),Wl(r,e,n)}}),Gl=An({slice4d_:function(t,e,n){var r=gn(t,"x","slice4d");return C(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),Wl(r,e,n)}});function Hl(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(wn(e.shape,r))),t.rank<n.rank&&(t=t.reshape(wn(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o)}}}var ql=An({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","all","bool"),o=O(e,r.shape),a=o,i=En(a,r.rank);null!=i&&(r=r.transpose(i),a=In(a.length,r.rank));var s=Lt.runKernelFunc((function(t){return t.all(r,a)}),{$x:r});if(n){var u=wn(s.shape,o);return s.reshape(u)}return s}}),Kl=An({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","any","bool"),o=O(e,r.shape),a=o,i=En(a,r.rank);null!=i&&(r=r.transpose(i),a=In(a.length,r.rank));var s=Lt.runKernelFunc((function(t){return t.any(r,a)}),{$x:r});if(n){var u=wn(s.shape,o);return s.reshape(u)}return s}}),jl=An({argMax_:function(t,e){void 0===e&&(e=0);var n=gn(t,"x","argMax");null==e&&(e=0);var r=O(e,n.shape),o=En(r,n.rank);null!=o&&(n=n.transpose(o),r=In(r.length,n.rank));var a={axis:r[0]},i=[n];return Lt.runKernelFunc((function(t,e){var o=t.argMax(n,r[0]);return e([n]),o}),{x:n},(function(t,e){var n=e[0];return{x:function(){return Xn(n)}}}),"ArgMax",a,i)}}),Xl=An({argMin_:function(t,e){void 0===e&&(e=0);var n=gn(t,"x","argMin");null==e&&(e=0);var r=O(e,n.shape),o=En(r,n.rank);return null!=o&&(n=n.transpose(o),r=In(r.length,n.rank)),Lt.runKernelFunc((function(t,e){var o=t.argMin(n,r[0]);return e([n]),o}),{$x:n},(function(t,e){var n=e[0];return{$x:function(){return Xn(n)}}}))}}),Yl=An({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","logSumExp"),o=O(e,r.shape),a=r.max(o,!0),i=r.sub(a).exp().sum(o).log(),s=a.reshape(i.shape).add(i);if(n){var u=wn(s.shape,o);return s.reshape(u)}return s}}),$l=An({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","max"),o=r,a=O(e,r.shape),i=a,s=En(i,r.rank);null!=s&&(r=r.transpose(s),i=In(i.length,r.rank));var u=[r],c=Lt.runKernelFunc((function(t,e){var n=t.max(r,i);return e([o,n]),n}),{x:r},(function(t,e){return Hl(t,e[1],e[0],a,s)}),"Max",{axes:i},u,[!0]);if(n){var l=wn(c.shape,a);c=c.reshape(l)}return c}}),Ql=An({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","mean"),o=O(e,r.shape),a=k(bn(r.shape,o)[1]);return oa((function(t){var r=On(a);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return o.forEach((function(t){n[t]=1})),e.reshape(n).mul(zn(t.shape,"float32")).div(a)}}}))(r)}}),Jl=An({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","min"),o=r,a=O(e,r.shape),i=a,s=En(i,r.rank);null!=s&&(r=r.transpose(s),i=In(i.length,r.rank));var u=[r],c=Lt.runKernelFunc((function(t,e){var n=t.min(r,i);return e([o,n]),n}),{x:r},(function(t,e){return Hl(t,e[1],e[0],a,s)}),"Min",{axes:i},u,[!0]);if(n){var l=wn(c.shape,a);c=c.reshape(l)}return c}}),Zl=An({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=O(e,(t=gn(t,"x","moments")).shape),o=t.mean(r,n),a=o.shape;n||(a=wn(o.shape,r));var i=t.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(r,n)}}}),th=An({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=O(e,r.shape);return oa((function(t){var e=En(o,t.rank),r=o,a=t;null!=e&&(a=t.transpose(e),r=In(r.length,t.rank));var i=function(e){var n=t.shape.slice();return o.forEach((function(t){n[t]=1})),e.reshape(n).mul(zn(t.shape,"float32"))},s={axes:r},u=Lt.runKernelFunc((function(t){return t.sum(a,r)}),{x:a},(function(t){return{x:function(){return i(t)}}}),"Sum",s);if(n){var c=wn(u.shape,o);u=u.reshape(c)}return{value:u,gradFunc:i}}))(r)}}),eh=An({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=gn(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=O(e,r.shape),a=En(o,r.rank),i=o,s=r;null!=a&&(s=r.transpose(a),i=In(i.length,r.rank));var u=Lt.runKernelFunc((function(t){return t.prod(s,i)}),{permutedX:s});if(n){var c=wn(u.shape,o);u=u.reshape(c)}return u}});var nh=An({elu_:function(t){var e=gn(t,"x","elu");return Lt.runKernelFunc((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 Lt.runKernelFunc((function(e){return e.eluDer(t,n)}),{dy:t,y:n})}}}))}}),rh=An({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=gn(t,"x","leakyRelu");return Eo(On(e).mul(n),n)}}),oh=An({prelu_:function(t,e){var n=gn(t,"x","prelu"),r=gn(e,"alpha","prelu");return Lt.runKernelFunc((function(t,e){var o=t.prelu(n,r);return e([n,r]),o}),{x:n,alpha:r},(function(t,e){var n=e[0],r=e[1],o=n.greater(0);return{x:function(){return yc(o,t,t.mul(r))},alpha:function(){var e=yc(o,Xn(t),t.mul(n)),a=Br(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}}),"Prelu")}}),ah=An({relu_:function(t){var e=gn(t,"x","relu");return"bool"===e.dtype?e.toInt():Lt.runKernelFunc((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())}}}),"Relu")}}),ih=An({relu6_:function(t){var e=gn(t,"x","relu6");return"bool"===e.dtype?e.toInt():Lt.runKernelFunc((function(t,n){var r=t.relu6(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(r.toFloat())}}}),"Relu6")}}),sh=An({selu_:function(t){var e=gn(t,"x","selu");return Lt.runKernelFunc((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(On(0)),r=On(su),o=On(uu),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return yc(e,a,i)}}}))}});var uh=An({localResponseNormalization_:function(t,e,n,r,o){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===o&&(o=.5);var a=gn(t,"x","localResponseNormalization");C(4===a.rank||3===a.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+a.rank+"."})),C(A(e),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."}));var i=a,s=!1;3===a.rank&&(s=!0,i=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=Lt.runKernelFunc((function(t,a){var s=t.localResponseNormalization4D(i,e,n,r,o);return a([i,s]),s}),{x4D:i},(function(t,a){var i=a[0],s=a[1];return{x4D:function(){return Lt.runKernelFunc((function(a){return a.LRNGrad(t,i,s,e,n,r,o)}),{})}}}));return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}});var ch=An({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var o=function t(e,n,r){void 0===r&&(r=null);if(0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(On(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=gn(t,"x","norm"),e,n),a=o.shape;if(r){var i=O(n,t.shape);a=wn(o.shape,i)}return o.reshape(a)}});var lh=An({basicLSTMCell_:function(t,e,n,r,o,a){var i=gn(t,"forgetBias","basicLSTMCell"),s=gn(e,"lstmKernel","basicLSTMCell"),u=gn(n,"lstmBias","basicLSTMCell"),c=gn(r,"data","basicLSTMCell"),l=gn(o,"c","basicLSTMCell"),h=gn(a,"h","basicLSTMCell"),f=c.concat(h,1).matMul(s).add(u),d=f.shape[0],p=f.shape[1]/4,v=[d,p],g=f.slice([0,0],v),m=f.slice([0,p],v),y=f.slice([0,2*p],v),x=f.slice([0,3*p],v),b=g.sigmoid().mulStrict(m.tanh()).addStrict(l.mulStrict(i.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w]}}),hh=An({multiRNNCell_:function(t,e,n,r){for(var o=gn(e,"data","multiRNNCell"),a=mn(n,"c","multiRNNCell"),i=mn(r,"h","multiRNNCell"),s=o,u=[],c=0;c<t.length;c++){var l=t[c](s,a[c],i[c]);u.push(l[0]),u.push(l[1]),s=l[1]}var h=[],f=[];for(c=0;c<u.length;c+=2)h.push(u[c]),f.push(u[c+1]);return[h,f]}});var fh=An({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var a=gn(t,"v","movingAverage"),i=gn(e,"x","movingAverage"),s=gn(n,"decay","movingAverage");Ft(a,i),C(S(a.shape,i.shape),(function(){return"Shape mismatch in v and x"}));var u=On(1),c=u.sub(s),l=i.sub(a).mul(c);if(o){C(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var h=gn(r,"step","movingAverage");l=l.div(u.sub(No(s,h)))}return a.add(l)}});var dh=An({stridedSlice_:function(t,e,n,r,o,a,i,s,u){if(void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==i)throw new Error("ellipsis mask is not yet supported");var c=gn(t,"x","stridedSlice"),l=Ko(s),h=c.shape.slice();l.forEach((function(t){e[t]=0,n[t]=1,h.splice(t,0,1)})),c=c.reshape(h);for(var f=0;f<c.rank;f++)e[f]=Xo(o,e,r,c.shape,f),n[f]=Yo(a,n,r,c.shape,f),r[f]=r[f]||1;var d=Ko(u);d.forEach((function(t){n[t]=e[t]+1,r[t]=1}));var p=jo(e,n,r),v=p.filter((function(t,e){return-1===d.indexOf(e)}));return r.every((function(t){return 1===t}))?Wl(c,e,p).reshape(v):Lt.runKernelFunc((function(t){return t.stridedSlice(c,e,n,r)}),{$x:c}).reshape(v)}});var ph=An({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=gn(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var o=r.shape[r.shape.length-1];if(e>o)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=Lt.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:a[0],indices:a[1]}}});var vh=An({scatterND_:function(t,e,n){var r=gn(t,"indices","scatterND","int32"),o=gn(e,"updates","scatterND");return zo(o,r,n),Lt.runKernelFunc((function(t){return t.scatterND(r,o,n)}),{indices:r,updates:o},null,"ScatterNd",{shape:n})}});var gh=An({fft_:function(t){C("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Lt.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),mh=An({ifft_:function(t){C("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Lt.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),yh=An({rfft_:function(t,e){C("float32"===t.dtype,(function(){return"The dtype for rfft() must be real value but got "+t.dtype}));var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&e<r){var a=t.shape.map((function(t){return 0})),i=t.shape.map((function(t){return t}));i[t.shape.length-1]=e,n=t.slice(a,i),r=e}else if(null!=e&&e>r){var s=t.shape.map((function(t){return t}));s[t.shape.length-1]=e-r,n=t.concat(Gn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=Tn(n,u).as2D(o,r),l=gh(c),h=Math.floor(r/2)+1,f=Dn(l),d=Nn(l),p=f.split([h,r-h],f.shape.length-1),v=d.split([h,r-h],d.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=h,Tn(p[0],v[0]).reshape(g)}}),xh=An({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=mh(r);return Dn(o)}var a=[n,2*(e-1)],i=Dn(t).as2D(n,e),s=Nn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(On(-1)),l=i.concat(u,1),h=s.concat(c,1);return r=Tn(l,h).as2D(a[0],a[1]),o=mh(r),Dn(o)}}),bh=Object.freeze({fft:gh,ifft:mh,rfft:yh,irfft:xh});var wh=An({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=gn(t,"sparseIndices","sparseToDense","int32"),a=gn(e,"sparseValues","sparseToDense"),i=gn(r,"defaultValue","sparseToDense",a.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 o=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,n,i),Lt.runKernelFunc((function(t){return t.sparseToDense(o,a,n,i)}),{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});var Ch=An({gatherND_:function(t,e){var n=gn(e,"indices","gatherND","int32"),r=gn(t,"x","gatherND");return Lt.runKernelFunc((function(t){return t.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}});var Eh=An({diag_:function(t){var e=gn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Lt.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}});var Rh=An({dropout_:function(t,e,n,r){var o=gn(t,"x","dropout");if(C("float32"===o.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."})),C(e>=0&&e<1,(function(){return"rate must be a float in the range [0, 1), but got "+e+"."})),0===e)return t instanceof wt?o.clone():o;var a=function(t,e){if(null==e)return t.shape.slice();if(S(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r<t.shape.length;r++)null==e[r]&&null!=t.shape[r]?n.push(t.shape[r]):n.push(e[r]);return n}return e}(o,n),i=1-e,s=zc(a,0,1,"float32",r).add(i).floor().div(i);return o.mul(s)}});function Ih(t,e,n){for(var r=1-t%2,o=new Float32Array(t),a=0;a<t;++a){var i=2*Math.PI*a/(t+r-1);o[a]=e-n*Math.cos(i)}return Mn(o,"float32")}var kh=An({hannWindow_:function(t){return Ih(t,.5,.5)}}),Sh=An({hammingWindow_:function(t){return Ih(t,.54,.46)}}),Ah=An({frame_:function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=0);for(var a=0,i=[];a+e<=t.size;)i.push(Wl(t,a,e)),a+=n;if(r)for(;a<t.size;){var s=a+e-t.size,u=Yn([Wl(t,a,e-s),Hn([s],o)]);i.push(u),a+=n}return 0===i.length?Bn([],[0,e]):Yn(i).as2D(i.length,e)}}),Th=An({stft_:function(t,e,n,r,o){var a;void 0===o&&(o=kh),null==r&&(a=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var i=Ah(t,e,n),s=To(i,o(e)),u=[],c=0;c<i.shape[0];c++)u.push(yh(s.slice([c,0],[1,e]),r));return Yn(u)}}),Dh=Object.freeze({hannWindow:kh,hammingWindow:Sh,frame:Ah,stft:Th});var Nh,Fh=function(t,e,o){return void 0===o&&(o=1),n(this,void 0,void 0,(function(){var n,a,i,s,u,c,l,h,f,d,p,v,g,m;return r(this,(function(r){switch(r.label){case 0:return n=gn(t,"predictions","inTopK"),a=gn(e,"targets","inTopK"),C(n.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank})),C(n.rank-1===a.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+a.rank})),E(n.shape.slice(0,n.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=n.shape[n.shape.length-1],C(o>0&&o<=i,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+o})),[4,n.data()];case 1:return s=r.sent(),[4,a.data()];case 2:for(u=r.sent(),c=[s.length/i,i],h=c[1],f=B("bool",l=c[0]),d=0;d<l;d++){for(p=d*h,v=s.subarray(p,p+h),g=[],m=0;m<v.length;m++)g.push({value:v[m],index:m});for(g.sort((function(t,e){return e.value-t.value})),f[d]=0,m=0;m<o;m++)if(g[m].index===u[d]){f[d]=1;break}}return t!==n&&n.dispose(),e!==a&&a.dispose(),[2,Fn(f,a.shape,"bool")]}}))}))};!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(Nh||(Nh={}));var _h=An({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=Nh.SUM_BY_NONZERO_WEIGHTS);var o=gn(t,"labels","absoluteDifference"),a=gn(e,"predictions","absoluteDifference"),i=null;null!=n&&(i=gn(n,"weights","absoluteDifference")),E(o.shape,a.shape,"Error in absoluteDifference: ");var s=o.sub(a).abs();return Oh(s,i,r)}}),Oh=An({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=Nh.SUM_BY_NONZERO_WEIGHTS);var r=gn(t,"losses","computeWeightedLoss"),o=null;null!=e&&(o=gn(e,"weights","computeWeightedLoss"));var a=null==o?r:r.mul(o);if(n===Nh.NONE)return a;if(n===Nh.SUM)return a.sum();if(n===Nh.MEAN){if(null==o)return a.mean();var i=r.size/o.size,s=a.sum().div(o.sum());return i>1?s.div(On(i)):s}if(n===Nh.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(On(r.size));var u=o.mul(zn(r.shape)).notEqual(On(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+n)}}),Mh=An({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=Nh.SUM_BY_NONZERO_WEIGHTS);var a=gn(t,"labels","cosineDistance"),i=gn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=gn(r,"weights","cosineDistance")),E(a.shape,i.shape,"Error in cosineDistance: ");var u=On(1).sub(a.mul(i).sum(n,!0));return Oh(u,s,o)}}),Bh=An({hingeLoss_:function(t,e,n,r){void 0===r&&(r=Nh.SUM_BY_NONZERO_WEIGHTS);var o=gn(t,"labels","hingeLoss"),a=gn(e,"predictions","hingeLoss"),i=null;null!=n&&(i=gn(n,"weights","hingeLoss")),E(o.shape,a.shape,"Error in hingeLoss: ");var s=On(1);o=On(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return Oh(u,i,r)}}),Ph=An({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=Nh.SUM_BY_NONZERO_WEIGHTS);var a=gn(t,"labels","huberLoss"),i=gn(e,"predictions","huberLoss"),s=null;null!=n&&(s=gn(n,"weights","huberLoss")),E(a.shape,i.shape,"Error in huberLoss: ");var u=On(r),c=i.sub(a).abs(),l=Io(c,u),h=c.sub(l),f=On(.5).mul(l.square()).add(u.mul(h));return Oh(f,s,o)}}),Lh=An({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=Nh.SUM_BY_NONZERO_WEIGHTS);var a=gn(t,"labels","logLoss"),i=gn(e,"predictions","logLoss"),s=null;null!=n&&(s=gn(n,"weights","logLoss")),E(a.shape,i.shape,"Error in logLoss: ");var u=On(1),c=On(r),l=a.mul(i.add(c).log()).neg().sub(u.sub(a).mul(u.sub(i).add(c).log()));return Oh(l,s,o)}}),Wh=An({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=Nh.SUM_BY_NONZERO_WEIGHTS);var o=gn(t,"labels","meanSquaredError"),a=gn(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=gn(n,"weights","meanSquaredError")),E(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return Oh(s,i,r)}}),Uh=An({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Nh.SUM_BY_NONZERO_WEIGHTS);var a=gn(t,"multiClassLabels","sigmoidCrossEntropy"),i=gn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=gn(n,"weights","sigmoidCrossEntropy")),E(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=On(r),c=On(1),l=On(.5);a=a.mul(c.sub(u)).add(l.mul(u))}var h=function(t,e){var n=gn(t,"labels","sigmoidCrossEntropyWithLogits"),r=gn(e,"logits","sigmoidCrossEntropyWithLogits");E(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i)}(a,i);return Oh(h,s,o)}}),Vh=An({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Nh.SUM_BY_NONZERO_WEIGHTS);var a=gn(t,"onehotLabels","softmaxCrossEntropy"),i=gn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=gn(n,"weights","softmaxCrossEntropy")),E(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=On(r),c=On(1),l=On(a.shape[1]);a=a.mul(c.sub(u)).add(u.div(l))}var h=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 oa((function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);r([t,a]);return{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=wn(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))]}}}))(t,e)}(a,i);return Oh(h,s,o)}}),zh=Object.freeze({get Reduction(){return Nh},absoluteDifference:_h,computeWeightedLoss:Oh,cosineDistance:Mh,hingeLoss:Bh,huberLoss:Ph,logLoss:Lh,meanSquaredError:Wh,sigmoidCrossEntropy:Uh,softmaxCrossEntropy:Vh});function Gh(t,e){return void 0===e&&(e=!1),Lt.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],o=Cc(n),a=t.clone(),i=Bn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,c=function(t){var e,u=a,c=s,l=o;e=Lt.tidy((function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),c=a.slice([t,t],[1,1]),l=Bn([[-1]]).where(c.greater(0),Bn([[1]])),h=c.sub(l.mul(u)),f=e.div(h);s=1===f.shape[0]?i.clone():i.concat(f.slice([1,0],[f.shape[0]-1,f.shape[1]]),0);var d=l.matMul(h).div(u).neg(),p=a.slice([t,0],[n-t,r]),v=d.mul(s),g=s.transpose();if(0===t)a=p.sub(v.matMul(g.matMul(p)));else{var m=p.sub(v.matMul(g.matMul(p)));a=a.slice([0,0],[t,r]).concat(m,0)}var y=v.transpose(),x=o.slice([0,t],[n,o.shape[1]-t]);if(0===t)o=x.sub(x.matMul(s).matMul(y));else{var b=x.sub(x.matMul(s).matMul(y));o=o.slice([0,0],[n,t]).concat(b,1)}return[s,a,o]})),s=e[0],a=e[1],o=e[2],tn([u,c,l])},l=0;l<u;++l)c(l);return!e&&n>r&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]}))}var Hh=An({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=gn(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var o=r.shape,a=r.shape.slice(-2),i=a[0],s=a[1];if(!(e<=i))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+i+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=i),n<0&&(n=s);var u=Kn(0,i,1,"int32").reshape([-1,1]),c=Kn(0,s,1,"int32"),l=Oo(u,c),h=pc(l.lessEqual(On(+e,"int32")),l.greaterEqual(On(-n,"int32"))),f=Gn([i,s],r.dtype);return hr(fr(r.reshape([-1,i,s])).map((function(t){return yc(h,t,f)}))).reshape(o)}}),qh=An({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,C(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){C(t[e].shape[0]===n,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"}))},o=1;o<t.length;++o)r(o)}else e=!0,t=tr(t,t.shape[0],0).map((function(t){return lr(t,[0])}));C(t.length<=t[0].shape[0],(function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."}));var a=[],i=t,s=function(t){a.push(Lt.tidy((function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=th(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r)}return e.div(ch(e,"euclidean"))})))};for(o=0;o<t.length;++o)s(o);return e?hr(a,0):a}}),Kh=An({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return Gh(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=fr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach((function(t){var n=Gh(t,e),r=n[0],i=n[1];o.push(r),a.push(i)})),[hr(o,0).reshape(t.shape),hr(a,0).reshape(t.shape)]}}),jh=Object.freeze({bandPart:Hh,gramSchmidt:qh,qr:Kh});function Xh(t,e,n,r,o,a){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY),null==a&&(a=0);var i=t.shape[0];return n=Math.min(n,i),C(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),C(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),C(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),C(1===e.rank,(function(){return"scores must be a 1D tensor"})),C(e.shape[0]===i,(function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+e.shape[0]})),C(0<=a&&a<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:a}}var Yh=An({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=gn(t,"images","resizeBilinear");C(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),C(2===e.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."}));var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Lt.runKernelFunc((function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)}),{x:o},(function(t,e){return{x:function(){return Lt.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:i,newWidth:s});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),$h=An({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=gn(t,"images","resizeNearestNeighbor");C(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),C(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),C("float32"===r.dtype||"int32"===r.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Lt.runKernelFunc((function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)}),{batchImages:o},(function(t,e){return{batchImages:function(){return Lt.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Qh=An({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=gn(t,"boxes","nonMaxSuppression"),i=gn(e,"scores","nonMaxSuppression"),s=Xh(a,i,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return Lt.runKernelFunc((function(t){return t.nonMaxSuppression(a,i,n,r,o)}),{boxes:a,scores:i},null,"NonMaxSuppressionV3",u)}}),Jh=function(t,e,o,a,i){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),n(this,void 0,void 0,(function(){var n,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return n=gn(t,"boxes","nonMaxSuppressionAsync"),s=gn(e,"scores","nonMaxSuppressionAsync"),u=Xh(n,s,o,a,i),o=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,Promise.all([n.data(),s.data()])];case 1:return c=r.sent(),l=c[0],h=c[1],f=Oa(l,h,o,a,i),n!==t&&n.dispose(),s!==e&&s.dispose(),[2,f]}}))}))},Zh=An({nonMaxSuppressionWithScore_:function(t,e,n,r,o,a){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===a&&(a=0);var i=gn(t,"boxes","nonMaxSuppression"),s=gn(e,"scores","nonMaxSuppression"),u=Xh(i,s,n,r,o,a),c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},l=Lt.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),tf=function(t,e,o,a,i,s){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),void 0===s&&(s=0),n(this,void 0,void 0,(function(){var n,u,c,l,h,f,d;return r(this,(function(r){switch(r.label){case 0:return n=gn(t,"boxes","nonMaxSuppressionAsync"),u=gn(e,"scores","nonMaxSuppressionAsync"),c=Xh(n,u,o,a,i,s),o=c.maxOutputSize,a=c.iouThreshold,i=c.scoreThreshold,s=c.softNmsSigma,[4,Promise.all([n.data(),u.data()])];case 1:return l=r.sent(),h=l[0],f=l[1],d=Ma(h,f,o,a,i,s),n!==t&&n.dispose(),u!==e&&u.dispose(),[2,d]}}))}))},ef=An({cropAndResize_:function(t,e,n,r,o,a){var i=gn(t,"image","cropAndResize"),s=gn(e,"boxes","cropAndResize","float32"),u=gn(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return C(4===i.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."})),C(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),C(1===u.rank&&u.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),C(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),C(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),C("bilinear"===o||"nearest"===o,(function(){return"method must be bilinear or nearest, but was "+o})),Lt.runKernelFunc((function(t,e){return t.cropAndResize(i,s,u,r,o,a)}),{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:r})}}),nf=Object.freeze({resizeBilinear:Yh,resizeNearestNeighbor:$h,nonMaxSuppression:Qh,nonMaxSuppressionAsync:Jh,nonMaxSuppressionWithScore:Zh,nonMaxSuppressionWithScoreAsync:tf,cropAndResize:ef}),rf=function(t,e){return!(t>0)||"linear"===e},of=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},af=function(t,e){var n=e,r=Br(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},sf=function(t,e,n){if("linear"===e)return t;if("relu"===e)return ah(t);if("elu"===e)return nh(t);if("relu6"===e)return ih(t);if("prelu"===e)return oh(t,n);throw new Error("Unknown fused activation "+e+".")};var uf=An({fusedMatMul_:function(t){var e,n=t.a,r=t.b,o=t.transposeA,a=void 0!==o&&o,i=t.transposeB,s=void 0!==i&&i,u=t.bias,c=t.activation,l=void 0===c?"linear":c,h=t.preluActivationWeights;if(!1===rf(Lt.state.gradientDepth,l)){var f=El(n,r,a,s);return null!=u&&(f=Or(f,u)),sf(f,l,h)}var d=gn(n,"a","fused matMul"),p=gn(r,"b","fused matMul");e=Nt(d,p),d=e[0],p=e[1];var v=a?d.shape[d.rank-2]:d.shape[d.rank-1],g=s?p.shape[p.rank-1]:p.shape[p.rank-2],m=a?d.shape[d.rank-1]:d.shape[d.rank-2],y=s?p.shape[p.rank-2]:p.shape[p.rank-1],x=d.shape.slice(0,-2),b=p.shape.slice(0,-2),w=k(x),E=k(b);C(d.rank>=2&&p.rank>=2&&d.rank===p.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+p.rank+"."})),C(S(x,b),(function(){return"Error in fused matMul: outer dimensions ("+x+") and ("+b+") of Tensors with shapes "+d.shape+" and "+p.shape+" must match."})),C(v===g,(function(){return"Error in fused matMul: inner shapes ("+v+") and ("+g+") of Tensors with shapes "+d.shape+" and "+p.shape+" and transposeA="+a+" and transposeB="+s+" must match."}));var R,I,A=d.shape.slice(0,-2).concat([m,y]),T=a?d.as3D(w,v,m):d.as3D(w,m,v),D=s?p.as3D(E,y,g):p.as3D(E,g,y);null!=u&&Pr(A,(R=Nt(R=gn(u,"bias","fused matMul"),d)[0]).shape),null!=h&&(I=gn(h,"prelu weights","fused matMul"));var N={a:T,b:D};null!=u&&(N.bias=R),null!=h&&(N.preluActivationWeights=I);var F=[T,D];return Lt.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:T,b:D,transposeA:a,transposeB:s,bias:R,activation:l,preluActivationWeights:I});return e([T,D,n]),n}),N,(function(t,e){var n=e[0],r=e[1],o=e[2],i=of(t,o,l),c={};return null!=u&&(c={bias:function(){return af(R,i)}}),a||s?!a&&s?Object.assign({a:function(){return i.matMul(r,!1,!1)},b:function(){return i.matMul(n,!0,!1)}},c):a&&!s?Object.assign({a:function(){return r.matMul(i,!1,!0)},b:function(){return n.matMul(i,!1,!1)}},c):Object.assign({a:function(){return r.matMul(i,!0,!0)},b:function(){return i.matMul(n,!0,!0)}},c):Object.assign({a:function(){return i.matMul(r,!1,!0)},b:function(){return n.matMul(i,!0,!1)}},c)}),"_FusedMatMul",{transposeA:a,transposeB:s,activation:l},F,[!0]).reshape(A)}}),cf=An({fusedConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,h=t.activation,f=void 0===h?"linear":h,d=t.preluActivationWeights;if(f=f||"linear",!1===rf(Lt.state.gradientDepth,f)){var p=dl(e,n,r,o,i,u,c);return null!=l&&(p=Or(p,l)),sf(p,f,d)}var v=gn(e,"x","conv2d"),g=gn(n,"filter","conv2d"),m=v,y=!1;3===v.rank&&(y=!0,m=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),C(4===m.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+m.rank+"."})),C(4===g.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."})),null!=c&&C(A(o),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."})),C(m.shape[3]===g.shape[2],(function(){return"Error in conv2d: depth of input ("+m.shape[3]+") must match input depth for filter "+g.shape[2]+"."})),C(Ca(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),C("NHWC"===i,(function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."}));var x,b,w=pa(m.shape,g.shape,r,u,o,c);null!=l&&(x=Nt(x=gn(l,"bias","fused conv2d"),v)[0],Pr(w.outShape,x.shape)),null!=d&&(b=gn(d,"prelu weights","fused conv2d"));var E={x:m,filter:g};null!=l&&(E.bias=x),null!=d&&(E.preluActivationWeights=b);var R=[g,m],I=Lt.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:m,filter:g,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([g,m,n]),n}),E,(function(t,e){var n=e,a=n[0],i=n[1],s=n[2],c=of(t,s,f);C(wa(u),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"}));var h={};return null!=l&&(h={bias:function(){return af(x,c)}}),Object.assign({x:function(){return gl(i.shape,c,a,r,o)},filter:function(){return vl(i,c,a.shape,r,o)}},h)}),"FusedConv2D",{convInfo:w,activation:f},R,[!0]);return y?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),lf=An({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,h=t.activation,f=void 0===h?"linear":h,d=t.preluActivationWeights;if(!1===rf(Lt.state.gradientDepth,f)){var p=ml(e,n,r,o,i,u,c);return null!=l&&(p=Or(p,l)),sf(p,f,d)}var v=gn(e,"x","depthwiseConv2d"),g=gn(n,"filter","depthwiseConv2d"),m=v,y=!1;3===v.rank&&(y=!0,m=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),C(4===m.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+m.rank+"."})),C(4===g.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+g.rank+"."})),C(m.shape[3]===g.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+m.shape[3]+") must match the inChannels dimension in filter "+g.shape[2]+"."})),null==u&&(u=[1,1]),C(Ca(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=c&&C(A(o),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."}));var x,b,w=pa(m.shape,g.shape,r,u,o,c,!0);null!=l&&(x=Nt(x=gn(l,"bias","fused conv2d"),v)[0],Pr(w.outShape,x.shape)),null!=d&&(b=gn(d,"prelu weights","fused depthwiseConv2d"));var E={x:m,filter:g};null!=l&&(E.bias=x),null!=d&&(E.preluActivationWeights=b);var R=[g,m],I=Lt.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:m,filter:g,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([g,m,n]),n}),E,(function(t,e){C(wa(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var n=e[0],r=e[1],o=e[2],a=of(t,o,f),i={};return null!=l&&(i={bias:function(){return af(x,a)}}),Object.assign({x:function(){return yl(r.shape,a,n,w)},filter:function(){return xl(r,a,n.shape,w)}},i)}),"FusedDepthwiseConv2D",{convInfo:w,activation:f},R,[!0]);return y?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),hf=Object.freeze({matMul:uf,conv2d:cf,depthwiseConv2d:lf}),ff=Object.freeze({image:nf,linalg:jh,losses:zh,spectral:bh,fused:hf,signal:Dh,add:Or,addN:$u,batchNorm:nc,batchNormalization:ec,batchNorm2d:ac,batchNormalization2d:oc,batchNorm3d:uc,batchNormalization3d:sc,batchNorm4d:hc,batchNormalization4d:lc,broadcastTo:fc,clone:dc,div:Bo,divNoNan:bc,eye:Cc,multinomial:Ec,oneHot:Rc,pad:Ic,pad1d:kc,pad2d:Sc,pad3d:Ac,pad4d:Tc,rand:Dc,randomGamma:Uc,randomNormal:Vc,randomUniform:zc,square:Gc,squaredDifference:Hc,tile:wc,truncatedNormal:qc,conv1d:fl,conv2d:dl,conv3d:pl,depthwiseConv2d:ml,separableConv2d:bl,conv2dTranspose:wl,conv3dTranspose:Cl,op:An,booleanMaskAsync:ul,complex:Tn,real:Dn,imag:Nn,concat:Yn,concat1d:$n,concat2d:Qn,concat3d:Jn,concat4d:Zn,split:tr,matMul:El,dot:Rl,outerProduct:Il,reverse:kl,reverse1d:Sl,reverse2d:Al,reverse3d:Tl,reverse4d:Dl,maxPool:_l,avgPool:Ol,pool:Ml,maxPool3d:Bl,avgPool3d:Pl,maxPoolWithArgmax:Ll,slice:Wl,slice1d:Ul,slice2d:Vl,slice3d:zl,slice4d:Gl,abs:Lr,acos:Wr,acosh:Ur,asin:Vr,asinh:zr,atan:Gr,atanh:Hr,ceil:qr,clipByValue:Kr,cos:jr,cosh:Xr,erf:Yr,exp:$r,expm1:Qr,floor:Jr,log:Zr,log1p:to,logSigmoid:eo,neg:no,reciprocal:ro,round:oo,rsqrt:ao,sigmoid:io,sign:so,isNaN:uo,isInf:co,isFinite:lo,sin:ho,sinh:fo,softplus:po,sqrt:vo,step:go,tan:mo,tanh:yo,all:ql,any:Kl,argMax:jl,argMin:Xl,logSumExp:Yl,max:$l,mean:Ql,min:Jl,moments:Zl,sum:th,prod:eh,equal:Kc,equalStrict:jc,greater:Xc,greaterEqual:Yc,greaterEqualStrict:$c,greaterStrict:Qc,less:Jc,lessEqual:Zc,lessEqualStrict:tl,lessStrict:el,notEqual:nl,notEqualStrict:rl,addStrict:xo,atan2:bo,divStrict:wo,floorDiv:Co,maximum:Eo,maximumStrict:Ro,minimum:Io,minimumStrict:ko,mod:So,modStrict:Ao,mul:To,mulStrict:Do,pow:No,powStrict:Fo,squaredDifferenceStrict:_o,sub:Oo,subStrict:Mo,elu:nh,leakyRelu:rh,prelu:oh,relu:ah,relu6:ih,selu:sh,logicalAnd:pc,logicalNot:vc,logicalOr:gc,logicalXor:mc,where:yc,whereAsync:xc,buffer:er,print:nr,batchToSpaceND:rr,cast:or,cumsum:ar,depthToSpace:ir,expandDims:sr,reshape:ur,spaceToBatchND:cr,squeeze:lr,stack:hr,unstack:fr,setdiff1dAsync:dr,fill:Hn,linspace:qn,ones:zn,range:Kn,scalar:On,tensor:Fn,tensor1d:Mn,tensor2d:Bn,tensor3d:Pn,tensor4d:Ln,tensor5d:Wn,tensor6d:Un,variable:Vn,zeros:Gn,onesLike:jn,zerosLike:Xn,transpose:ua,softmax:ia,logSoftmax:sa,localResponseNormalization:uh,norm:ch,gather:il,unsortedSegmentSum:sl,basicLSTMCell:lh,multiRNNCell:hh,movingAverage:fh,stridedSlice:dh,topk:ph,scatterND:vh,fft:gh,ifft:mh,rfft:yh,irfft:xh,sparseToDense:wh,gatherND:Ch,diag:Eh,dropout:Rh,hannWindow:kh,hammingWindow:Sh,frame:Ah,stft:Th,inTopKAsync:Fh});function df(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&C("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function pf(t,e,n,r,o,a){for(var i=o.strideHeight,s=o.strideWidth,u=o.dilationHeight,c=o.dilationWidth,l=o.effectiveFilterHeight,h=o.effectiveFilterWidth,f=o.padInfo.top,d=o.padInfo.left,p="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=er(o.outShape,n),g=v.values,m=o.outShape[1]*o.outShape[2]*o.outShape[3],y=o.outShape[2]*o.outShape[3],x=o.outShape[3],b=0;b<o.batchSize;++b)for(var w=b*m,C=b*r[0],E=0;E<o.inChannels;++E)for(var R=0;R<o.outHeight;++R)for(var I=R*i-f,k=Math.max(0,I),S=Math.min(o.inHeight,l+I),A=w+R*y,T=0;T<o.outWidth;++T){for(var D=T*s-d,N=Math.max(0,D),F=Math.min(o.inWidth,h+D),_=p,O=0,M=0,B=k;B<S;B+=u){for(var P=C+B*r[1],L=N;L<F;L+=c){var W=t[P+L*r[2]+E];"max"===a&&W>_?_=W:"avg"===a&&(O+=W,M++)}if(isNaN(_))break}g[A+T*x+E]="avg"===a?O/M:_}return v}function vf(t,e,n,r,o,a){void 0===o&&(o=!1),void 0===a&&(a=!1);for(var i=er(r.outShape,"int32"),s=r.strideHeight,u=r.strideWidth,c=r.dilationHeight,l=r.dilationWidth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=r.padInfo.top,p=r.padInfo.left,v=er(e,n,t),g=0;g<r.batchSize;++g)for(var m=0;m<r.inChannels;++m)for(var y=0;y<r.outHeight;++y){for(var x=y*s-d,b=x;b<0;)b+=c;for(var w=Math.min(r.inHeight,h+x),C=0;C<r.outWidth;++C){for(var E=C*u-p,R=E;R<0;)R+=l;for(var I=Math.min(r.inWidth,f+E),k=Number.NEGATIVE_INFINITY,S=-1,A=b;A<w;A+=c)for(var T=A-x,D=R;D<I;D+=l){var N=D-E,F=v.get(g,A,D,m);F>k&&(k=F,S=o?a?((g*r.inHeight+A)*r.inWidth+D)*r.inChannels+m:(A*r.inWidth+D)*r.inChannels+m:T*f+N)}i.set(S,g,y,C,m)}}return i}function gf(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var mf=function(t){function o(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new ca(e,Lt),e}return e(o,t),o.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,i().get("IS_NODE")&&dn("\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============================"));var r={};return this.data.set(r,{values:t,dtype:n}),r},o.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},o.prototype.numDataIds=function(){return this.data.numDataIds()},o.prototype.read=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){return[2,this.readSync(t)]}))}))},o.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?Aa(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},o.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map((function(t){return ot(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return er(t.shape,t.dtype,n)},o.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Lt.makeTensorFromDataId(r,e,n,this)},o.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},o.prototype.time=function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){return e=et(),t(),[2,{kernelMs:et()-e}]}))}))},o.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},o.prototype.complex=function(t,e){var n=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:Lt.keep(t.clone()),imag:Lt.keep(e.clone())},n},o.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},o.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},o.prototype.slice=function(t,e,n){if(df(t,"slice"),$o(t.shape,e,n)){var r=Qo(e,t.strides),o=k(n);return Fn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype)}for(var a=er(n,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s).map((function(t,n){return t+e[n]}));a.values[s]=i.get.apply(i,u)}return a.toTensor()},o.prototype.stridedSlice=function(t,e,n,r){df(t,"stridedSlice");var o=jo(e,n,r);if(o.some((function(t){return 0===t})))return Fn([],o);for(var a=er(o,t.dtype),i=this.bufferSync(t),s=0;s<a.size;s++){for(var u=a.indexToLoc(s),c=new Array(u.length),l=0;l<c.length;l++)c[l]=u[l]*r[l]+e[l];a.set.apply(a,[i.get.apply(i,c)].concat(u))}return a.toTensor()},o.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=er([t.size,t.size],t.dtype),r=n.values,o=0;o<e.length;o++)r[o*t.size+o]=e[o];return n.toTensor()},o.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},o.prototype.reverse=function(t,e){df(t,"reverse");for(var n=er(t.shape,t.dtype),r=this.bufferSync(t),o=function(o){var a=n.indexToLoc(o),i=a.slice();e.forEach((function(e){return i[e]=t.shape[e]-1-i[e]})),n.set.apply(n,[r.get.apply(r,i)].concat(a))},a=0;a<n.size;a++)o(a);return n.toTensor()},o.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map((function(t){return Dn(t)})),o=t.map((function(t){return Nn(t)}));return Tn(this.concat(r,e),this.concat(o,e))}var a=t.map((function(t){var n=k(t.shape.slice(e));return t.as2D(-1,n)})),i=Sn(a.map((function(t){return t.shape})),1),s=er(i,t[0].dtype).values;if(1===a[0].shape[0]){var u=0;a.forEach((function(t){s.set(n.readSync(t.dataId),u),u+=t.size}))}else{var c=0;a.forEach((function(t){for(var e=n.readSync(t.dataId),r=0,o=0;o<t.shape[0];++o)for(var a=o*i[1]+c,u=0;u<t.shape[1];++u)s[a+u]=e[r++];c+=t.shape[1]}))}var l=Sn(t.map((function(t){return t.shape})),e);return Fn(s,l,t[0].dtype)},o.prototype.neg=function(t){return df(t,"neg"),this.multiply(On(-1),t)},o.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t+n,imag:e+r}})):this.broadcastedBinaryOp(t,e,Tt(t.dtype,e.dtype),(function(t,e){return t+e}))},o.prototype.addN=function(t){var e=this;df(t,"addN");for(var n=t.map((function(t){return e.readSync(t.dataId)})),r=er(t[0].shape,t[0].dtype),o=r.values,a=0;a<t.length;a++)for(var i=n[a],s=0;s<o.length;s++)o[s]+=i[s];return r.toTensor()},o.prototype.softmax=function(t,e){var n=O([e],t.shape),r=this.max(t,n),o=wn(r.shape,n),a=this.subtract(t,r.reshape(o)),i=this.exp(a),s=this.sum(i,n).reshape(o);return Bo(i,s)},o.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t-n,imag:e-r}})):this.broadcastedBinaryOp(t,e,Tt(t.dtype,e.dtype),(function(t,e){return t-e}))},o.prototype.pow=function(t,e){return df([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.pow(t,e)}))},o.prototype.batchMatMul=function(t,e,n,r){df([t,e],"matMul");for(var o=n?t.shape[1]:t.shape[2],a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],h=l[0],f=l[1],d=l[2],p=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=p[0],g=p[1],m=p[2],y=a*i,x=er([s,a,i],t.dtype),b=x.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<a;E+=w)for(var R=0;R<i;R+=w)for(var I=0;I<o;I+=w)for(var k=Math.min(E+w,a),S=Math.min(R+w,i),A=Math.min(I+w,o),T=E;T<k;T++)for(var D=R;D<S;D++){for(var N=0,F=I;F<A;F++)N+=u[C*h+T*f+F*d]*c[F*v+D*g+C*m];b[C*y+(T*i+D)]+=N}return x.toTensor()},o.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,o);return a&&(u=this.add(u,a)),i&&(u=gf(this,u,i,s)),u},o.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}})):this.broadcastedBinaryOp(t,e,Tt(t.dtype,e.dtype),(function(t,e){return t*e}))},o.prototype.floorDiv=function(t,e){df([t,e],"floorDiv");return this.broadcastedBinaryOp(t,e,"int32",(function(t,e){return Math.floor(t/e)}))},o.prototype.sum=function(t,e){df(t,"sum"),Cn("sum",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,Tt(t.dtype,"int32")),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=0,f=0;f<i;++f)h+=u[l+f];s[c]=h}return a},o.prototype.prod=function(t,e){df(t,"sum");for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,Tt(t.dtype,"int32")),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=1,f=0;f<i;++f)h*=u[l+f];s[c]=h}return a},o.prototype.unsortedSegmentSum=function(t,e,n){df(t,"unsortedSegmentSum");for(var r=[],o=t.rank-e.rank,a=0;a<o;++a)e=e.expandDims(a+1);for(a=0;a<n;++a){var i=On(a,"int32"),s=Kc(i,e).asType("float32").mul(t).sum(0);r.push(s)}return hr(r)},o.prototype.argMin=function(t,e){df(t,"argMin");var n=[e];Cn("argMin",n,t.rank);for(var r=bn(t.shape,n),o=r[0],a=r[1],i=Gn(o,"int32"),s=k(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,f=c[h],d=0,p=0;p<s;++p){var v=c[h+p];v<f&&(f=v,d=p)}u[l]=d}return i},o.prototype.argMax=function(t,e){df(t,"argMax");var n=[e];Cn("argMax",n,t.rank);for(var r=bn(t.shape,n),o=r[0],a=r[1],i=Gn(o,"int32"),s=k(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,f=c[h],d=0,p=0;p<s;++p){var v=c[h+p];v>f&&(f=v,d=p)}u[l]=d}return i},o.prototype.cumsum=function(t,e,n,r){if(df(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 o=Tt(t.dtype,"int32"),a=Gn(t.shape,o),i=this.readSync(a.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;l<s.length;l+=u)for(var h=0;h<u;h++){var f=c(l,h);if(0===h)i[f]=n?0:s[f];else{var d=c(l,h-1);i[f]=n?s[d]+i[d]:s[f]+i[d]}}return a},o.prototype.equal=function(t,e){return df([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t===e?1:0}))},o.prototype.notEqual=function(t,e){return df([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t!==e?1:0}))},o.prototype.less=function(t,e){return df([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<e?1:0}))},o.prototype.lessEqual=function(t,e){return df([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<=e?1:0}))},o.prototype.greater=function(t,e){return df([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>e?1:0}))},o.prototype.greaterEqual=function(t,e){return df([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},o.prototype.logicalNot=function(t){df(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return this.makeOutput(n,t.shape,"bool")},o.prototype.logicalAnd=function(t,e){return df([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t&&e}))},o.prototype.logicalOr=function(t,e){return df([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t||e}))},o.prototype.select=function(t,e,n){df([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=this.readSync(n.dataId),i=Gn(e.shape,Tt(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,c=0===t.rank||t.rank>1||1===e.rank?1:k(e.shape.slice(1)),l=0;l<r.length;l++)for(var h=0;h<c;h++)1===r[l]?s[u++]=o[l]:s[u++]=a[l];return i},o.prototype.where=function(t){df([t],"where");var e=this.readSync(t.dataId);return Ga(t.shape,e)},o.prototype.topk=function(t,e,n){return df(t,"topk"),za(this.readSync(t.dataId),t.shape,t.dtype,e)},o.prototype.min=function(t,e){df(t,"min"),Cn("min",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];d<h&&(h=d)}s[c]=h}return a},o.prototype.minimum=function(t,e){return df([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.min(t,e)}))},o.prototype.mod=function(t,e){return df([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e}))},o.prototype.max=function(t,e){df(t,"max"),Cn("max",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];d>h&&(h=d)}s[c]=h}return a},o.prototype.maximum=function(t,e){return df([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},o.prototype.all=function(t,e){df(t,"all"),Cn("all",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];h=h&&d}s[c]=h}return a},o.prototype.any=function(t,e){df(t,"any"),Cn("any",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];h=h||d}s[c]=h}return a},o.prototype.squaredDifference=function(t,e){return df([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t-e;return n*n}))},o.prototype.ceil=function(t){df(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.floor=function(t){df(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.sign=function(t){df(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,t.shape,"float32")},o.prototype.isNaN=function(t){df(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},o.prototype.isInf=function(t){df(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},o.prototype.isFinite=function(t){df(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},o.prototype.round=function(t){df(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=Math.floor(e[r]);e[r]-o<.5?n[r]=Math.floor(e[r]):e[r]-o>.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1}return this.makeOutput(n,t.shape,"float32")},o.prototype.exp=function(t){df(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.expm1=function(t){df(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.log=function(t){df(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.log1p=function(t){df(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log1p(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.sqrt=function(t){df(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.sqrt(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.rsqrt=function(t){df(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=1/Math.sqrt(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.reciprocal=function(t){df(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return this.makeOutput(n,t.shape,"float32")},o.prototype.linear=function(t){return t},o.prototype.relu=function(t){df(t,"relu");for(var e=Gn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.max(0,r[o]);return e},o.prototype.relu6=function(t){df(t,"relu");for(var e=Gn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.min(Math.max(0,r[o]),6);return e},o.prototype.prelu=function(t,e){return df([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return t<0?e*t:t}))},o.prototype.elu=function(t){df(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r];e[r]=o>=0?o:Math.exp(o)-1}return this.makeOutput(e,t.shape,"float32")},o.prototype.eluDer=function(t,e){df([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),a=0;a<r.length;++a){var i=r[a];n[a]=i>=1?o[a]:o[a]*(i+1)}return this.makeOutput(n,e.shape,"float32")},o.prototype.selu=function(t){df(t,"selu");for(var e=su,n=uu,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>=0?n*i:e*(Math.exp(i)-1)}return this.makeOutput(r,t.shape,"float32")},o.prototype.clip=function(t,e,n){df(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>n?n:i<e?e:i}return this.makeOutput(r,t.shape,"float32")},o.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var o=n[2*r],a=n[2*r+1];e[r]=Math.hypot(o,a)}return this.makeOutput(e,t.shape,"float32")},o.prototype.int=function(t){df(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return this.makeOutput(e,t.shape,"int32")},o.prototype.sigmoid=function(t){df(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(e,t.shape,"float32")},o.prototype.softplus=function(t){df(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o]>-e,i=r[o]<e,s=Math.exp(r[o]),u=void 0;u=i?s:a?r[o]:Math.log(1+s),n[o]=u}return this.makeOutput(n,t.shape,"float32")},o.prototype.sin=function(t){df(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.cos=function(t){df(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.tan=function(t){df(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.asin=function(t){df(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.acos=function(t){df(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.atan=function(t){df(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.atan2=function(t,e){return df([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.atan2(t,e)}))},o.prototype.sinh=function(t){df(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.cosh=function(t){df(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.tanh=function(t){df(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=T(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.asinh=function(t){df(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.acosh=function(t){df(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.atanh=function(t){df(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.erf=function(t){df(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=Math.sign(n[r]),a=Math.abs(n[r]),i=1/(1+.3275911*a);e[r]=o*(1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-a*a))}return this.makeOutput(e,t.shape,"float32")},o.prototype.step=function(t,e){void 0===e&&(e=0),df(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o];isNaN(a)?n[o]=NaN:n[o]=a>0?1:e}return this.makeOutput(n,t.shape,"float32")},o.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.conv2d(e,n,r);return o&&(s=this.add(s,o)),a&&(s=gf(this,s,a,i)),s},o.prototype.conv2d=function(t,e,n){df([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c="channelsLast"===n.dataFormat,l=er(n.outShape,t.dtype),h=t.strides[0],f=c?t.strides[1]:t.strides[2],d=c?t.strides[2]:1,p=c?1:t.strides[1],v=l.strides[0],g=c?l.strides[1]:l.strides[2],m=c?l.strides[2]:1,y=c?1:l.strides[1],x=this.readSync(t.dataId),b=this.readSync(e.dataId),w=l.values,C=0;C<n.batchSize;++C)for(var E=C*h,R=C*v,I=0;I<n.outHeight;++I)for(var k=R+I*g,S=I*n.strideHeight-u,A=0;A<r;A++){var T=S+A*a;if(!(T<0||T>=n.inHeight))for(var D=A*e.strides[0],N=E+T*f,F=0;F<n.outWidth;++F)for(var _=k+F*m,O=F*n.strideWidth-s,M=0;M<o;M++){var B=O+M*i;if(!(B<0||B>=n.inWidth))for(var P=N+B*d,L=D+M*e.strides[1],W=0;W<n.inChannels;++W){for(var U=x[P+W*p],V=0;V<n.outChannels;++V)w[_+V*y]+=U*b[L+V];L+=n.outChannels}}}return l.toTensor()},o.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,o=n.filterHeight,a=n.filterWidth,i=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,c=n.padInfo.front,l=n.padInfo.left,h=n.padInfo.top,f=er(n.outShape,t.dtype),d=this.readSync(t.dataId),p=this.readSync(e.dataId),v=f.values,g=0;g<n.batchSize;++g)for(var m=g*t.strides[0],y=g*f.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*f.strides[1],w=x*n.strideDepth-c,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var R=C*e.strides[0],I=m+E*t.strides[1],k=0;k<n.outHeight;++k)for(var S=b+k*f.strides[2],A=k*n.strideHeight-h,T=0;T<o;T++){var D=A+T*s;if(!(D<0||D>=n.inHeight))for(var N=R+T*e.strides[1],F=I+D*t.strides[2],_=0;_<n.outWidth;++_)for(var O=S+_*n.outChannels,M=_*n.strideWidth-l,B=0;B<a;B++){var P=M+B*u;if(!(P<0||P>=n.inWidth))for(var L=N+B*e.strides[2],W=F+P*n.inChannels,U=L,V=0;V<n.inChannels;++V){for(var z=d[W+V],G=0;G<n.outChannels;++G)v[O+G]+=z*p[U+G];U+=n.outChannels}}}}return f.toTensor()},o.prototype.conv2dDerInput=function(t,e,n){df([t,e],"conv2dDerInput");for(var r=er(n.inShape,"float32"),o=r.values,a=this.readSync(t.dataId),i=this.readSync(e.dataId),s=e.strides,u=s[0],c=s[1],l=s[2],h=n.batchSize,f=n.filterHeight,d=n.filterWidth,p=n.inChannels,v=n.inHeight,g=n.inWidth,m=n.outChannels,y=n.outHeight,x=n.outWidth,b=n.strideHeight,w=n.strideWidth,C=n.dataFormat,E=f-1-n.padInfo.top,R=d-1-n.padInfo.left,I="channelsLast"===C,k=r.strides[0],S=I?r.strides[1]:r.strides[2],A=I?r.strides[2]:1,T=I?1:r.strides[1],D=t.strides[0],N=I?t.strides[1]:t.strides[2],F=I?t.strides[2]:1,_=I?1:t.strides[1],O=0;O<h;++O)for(var M=0;M<p;++M)for(var B=0;B<v;++B)for(var P=B-E,L=Math.max(0,Math.ceil(P/b)),W=Math.min(y,(f+P)/b),U=0;U<g;++U){for(var V=U-R,z=Math.max(0,Math.ceil(V/w)),G=Math.min(x,(d+V)/w),H=0,q=L;q<W;++q)for(var K=q*b-P,j=z;j<G;++j)for(var X=D*O+N*q+F*j,Y=u*(f-1-K)+c*(d-1-(j*w-V))+l*M,$=0;$<m;++$){H+=a[X+_*$]*i[Y+$]}o[k*O+S*B+A*U+T*M]=H}return r.toTensor()},o.prototype.conv3dDerInput=function(t,e,n){for(var r=er(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=a[3],l=this.readSync(t.dataId),h=t.strides,f=h[0],d=h[1],p=h[2],v=h[3],g=this.readSync(e.dataId),m=e.strides,y=m[0],x=m[1],b=m[2],w=m[3],C=n.batchSize,E=n.filterDepth,R=n.filterHeight,I=n.filterWidth,k=n.inChannels,S=n.inDepth,A=n.inHeight,T=n.inWidth,D=n.outChannels,N=n.outDepth,F=n.outHeight,_=n.outWidth,O=n.strideDepth,M=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=R-1-n.padInfo.top,W=I-1-n.padInfo.left,U=0;U<C;++U)for(var V=0;V<k;++V)for(var z=0;z<S;++z)for(var G=z-P,H=Math.max(0,Math.ceil(G/O)),q=Math.min(N,(E+G)/O),K=0;K<A;++K)for(var j=K-L,X=Math.max(0,Math.ceil(j/M)),Y=Math.min(F,(R+j)/M),$=0;$<T;++$){for(var Q=$-W,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(_,(I+Q)/B),tt=0,et=H;et<q;++et)for(var nt=et*O-G,rt=X;rt<Y;++rt)for(var ot=rt*M-j,at=J;at<Z;++at)for(var it=f*U+d*et+p*rt+v*at,st=y*(E-1-nt)+x*(R-1-ot)+b*(I-1-(at*B-Q))+w*V,ut=0;ut<D;++ut){tt+=l[it+ut]*g[st+ut]}o[i*U+s*z+u*K+c*$+V]=tt}return r.toTensor()},o.prototype.conv2dDerFilter=function(t,e,n){df([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s="channelsLast"===n.dataFormat,u=er(n.filterShape,"float32"),c=n.padInfo.left,l=n.padInfo.top,h=this.bufferSync(t),f=this.bufferSync(e),d=0;d<a;++d)for(var p=Math.max(0,Math.ceil((l-d)/r)),v=Math.min(n.outHeight,(n.inHeight+l-d)/r),g=0;g<i;++g)for(var m=Math.max(0,Math.ceil((c-g)/o)),y=Math.min(n.outWidth,(n.inWidth+c-g)/o),x=0;x<n.inChannels;++x)for(var b=0;b<n.outChannels;++b){for(var w=0,C=0;C<n.batchSize;++C)for(var E=p;E<v;++E)for(var R=d+E*r-l,I=m;I<y;++I){var k=g+I*o-c;w+=s?h.get(C,R,k,x)*f.get(C,E,I,b):h.get(C,x,R,k)*f.get(C,b,E,I)}u.set(w,d,g,x,b)}return u.toTensor()},o.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=er(n.filterShape,"float32"),l=c.values,h=c.strides,f=h[0],d=h[1],p=h[2],v=h[3],g=this.readSync(e.dataId),m=e.strides,y=m[0],x=m[1],b=m[2],w=m[3],C=this.readSync(t.dataId),E=t.strides,R=E[0],I=E[1],k=E[2],S=E[3],A=n.padInfo.front,T=n.padInfo.left,D=n.padInfo.top,N=0;N<i;++N)for(var F=Math.max(0,Math.ceil((A-N)/r)),_=Math.min(n.outDepth,(n.inDepth+A-N)/r),O=N*f,M=0;M<s;++M)for(var B=Math.max(0,Math.ceil((D-M)/o)),P=Math.min(n.outHeight,(n.inHeight+D-M)/o),L=M*d+O,W=0;W<u;++W)for(var U=Math.max(0,Math.ceil((T-W)/a)),V=Math.min(n.outWidth,(n.inWidth+T-W)/a),z=W*p+L,G=0;G<n.inChannels;++G)for(var H=G*v+z,q=0;q<n.outChannels;++q){for(var K=0,j=0;j<n.batchSize;++j)for(var X=j*R,Y=j*y,$=F;$<_;++$)for(var Q=(N+$*r-A)*I+X,J=$*x+Y,Z=B;Z<P;++Z)for(var tt=(M+Z*o-D)*k+Q,et=Z*b+J,nt=U;nt<V;++nt){var rt=nt*w+et;K+=C[(W+nt*a-T)*S+tt+G]*g[rt+q]}l[H+q]=K}return c.toTensor()},o.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return o&&(s=this.add(s,o)),a&&(s=gf(this,s,a,i)),s},o.prototype.depthwiseConv2D=function(t,e,n){df([t,e],"depthwiseConv2D");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=n.outChannels/n.inChannels,l=er(n.outShape,t.dtype),h=this.readSync(t.dataId),f=this.readSync(e.dataId),d=l.values,p=0;p<n.batchSize;++p)for(var v=p*t.strides[0],g=p*l.strides[0],m=0;m<n.outHeight;++m)for(var y=g+m*l.strides[1],x=m*n.strideHeight-s,b=0;b<r;++b){var w=x+b*a;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],R=0;R<n.outWidth;++R)for(var I=y+R*l.strides[2],k=R*n.strideWidth-u,S=0;S<o;++S){var A=k+S*i;if(!(A<0||A>=n.inWidth))for(var T=C+S*e.strides[1],D=E+A*n.inChannels,N=I,F=T,_=0;_<n.inChannels;++_){for(var O=h[D+_],M=0;M<c;++M)d[N+M]+=O*f[F+M];N+=c,F+=c}}}return l.toTensor()},o.prototype.depthwiseConv2DDerInput=function(t,e,n){df([t,e],"depthwiseConv2DDerInput");for(var r=er(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=this.readSync(t.dataId),l=t.strides,h=l[0],f=l[1],d=l[2],p=this.readSync(e.dataId),v=e.strides,g=v[0],m=v[1],y=v[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,R=n.inWidth,I=n.outChannels,k=n.outHeight,S=n.outWidth,A=n.strideHeight,T=n.strideWidth,D=b-1-n.padInfo.top,N=w-1-n.padInfo.left,F=I/C,_=0;_<x;++_)for(var O=0;O<C;++O)for(var M=0;M<E;++M)for(var B=M-D,P=Math.max(0,Math.ceil(B/A)),L=Math.min(k,(b+B)/A),W=0;W<R;++W){for(var U=W-N,V=Math.max(0,Math.ceil(U/T)),z=Math.min(S,(w+U)/T),G=0,H=P;H<L;++H)for(var q=H*A-B,K=V;K<z;++K)for(var j=h*_+f*H+d*K,X=g*(b-1-q)+m*(w-1-(K*T-U))+y*O,Y=0;Y<F;++Y){G+=c[j+(O*F+Y)]*p[X+Y]}o[i*_+s*M+u*W+O]=G}return r.toTensor()},o.prototype.depthwiseConv2DDerFilter=function(t,e,n){df([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=er(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,h=this.bufferSync(t),f=this.bufferSync(e),d=0;d<a;++d)for(var p=Math.max(0,Math.ceil((c-d)/r)),v=Math.min(n.outHeight,(n.inHeight+c-d)/r),g=0;g<i;++g)for(var m=Math.max(0,Math.ceil((u-g)/o)),y=Math.min(n.outWidth,(n.inWidth+u-g)/o),x=0;x<n.outChannels;++x){for(var b=Math.trunc(x/l),w=x%l,C=0,E=0;E<n.batchSize;++E)for(var R=p;R<v;++R)for(var I=d+R*r-c,k=m;k<y;++k){var S=g+k*o-u;C+=h.get(E,I,S,b)*f.get(E,R,k,x)}s.set(C,d,g,b,w)}return s.toTensor()},o.prototype.tile=function(t,e){return df(t,"tile"),Va(this.bufferSync(t),e)},o.prototype.pad=function(t,e,n){df(t,"pad");var r=e.map((function(e,n){return e[0]+t.shape[n]+e[1]})),o=e.map((function(t){return t[0]})),a=this.bufferSync(t),i=er(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),c=u.map((function(t,e){return t+o[e]}));i.set.apply(i,[a.get.apply(a,u)].concat(c))}return i.toTensor()},o.prototype.gather=function(t,e,n){df([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var a=er(r,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),c=u.slice();c[n]=o[u[n]];var l=i.locToIndex(c);a.values[s]=i.values[l]}return a.toTensor()},o.prototype.batchToSpaceND=function(t,e,n){df([t],"batchToSpaceND");var r=e.reduce((function(t,e){return t*e})),o=pr(t.shape,e,r),a=vr(o.length,e.length),i=gr(t.shape,e,r),s=mr(n,e.length),u=yr(i,n,e.length);return ua(t.reshape(o),a).reshape(i).slice(s,u)},o.prototype.spaceToBatchND=function(t,e,n){df([t],"spaceToBatchND");var r=e.reduce((function(t,e){return t*e})),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=pr(i.shape,e,r,!1),u=vr(s.length,e.length,!1),c=gr(i.shape,e,r,!1);return ua(i.reshape(s),u).reshape(c)},o.prototype.maxPool=function(t,e){return df(t,"maxPool"),pf(this.readSync(t.dataId),t.shape,t.dtype,t.strides,e,"max").toTensor()},o.prototype.maxPoolBackprop=function(t,e,n,r){df([e,n],"maxPoolBackprop");for(var o=this.readSync(e.dataId),a=er(r.outShape,e.dtype,vf(o,e.shape,e.dtype,r).values),i=r.strideHeight,s=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,l=r.effectiveFilterHeight,h=r.effectiveFilterWidth,f=h-1-r.padInfo.left,d=l-1-r.padInfo.top,p=er(e.shape,"float32"),v=this.bufferSync(t),g=0;g<r.batchSize;++g)for(var m=0;m<r.inChannels;++m)for(var y=0;y<r.inHeight;++y)for(var x=0;x<r.inWidth;++x){for(var b=y-d,w=x-f,C=0,E=0;E<l;E+=u){var R=(b+E)/i;if(!(R<0||R>=r.outHeight||Math.floor(R)!==R))for(var I=0;I<h;I+=c){var k=(w+I)/s;if(!(k<0||k>=r.outWidth||Math.floor(k)!==k)){var S=l*h-1-a.get(g,R,k,m)===E*h+I?1:0;if(0!==S)C+=v.get(g,R,k,m)*S}}}p.set(C,g,y,x,m)}return p.toTensor()},o.prototype.avgPoolBackprop=function(t,e,n){df([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=l-1-n.padInfo.left,f=c-1-n.padInfo.top,d=er(e.shape,"float32"),p=1/(a*i),v=this.bufferSync(t),g=0;g<n.batchSize;++g)for(var m=0;m<n.inChannels;++m)for(var y=0;y<n.inHeight;++y)for(var x=0;x<n.inWidth;++x){for(var b=y-f,w=x-h,C=0,E=0;E<c;E+=s){var R=(b+E)/r;if(!(R<0||R>=n.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/o;if(!(k<0||k>=n.outWidth||Math.floor(k)!==k))C+=v.get(g,R,k,m)}}d.set(C*p,g,y,x,m)}return d.toTensor()},o.prototype.pool3d=function(t,e,n){df(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,f=e.padInfo.front,d=e.padInfo.top,p=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(t.dataId),m=er(e.outShape,t.dtype),y=m.values,x=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],E=0;E<e.batchSize;++E)for(var R=E*x,I=E*t.strides[0],k=0;k<e.inChannels;++k)for(var S=0;S<e.outDepth;++S){for(var A=S*r-f,T=A;T<0;)T+=i;for(var D=Math.min(e.inDepth,c+A),N=R+S*b,F=0;F<e.outHeight;++F){for(var _=F*o-d,O=_;O<0;)O+=s;for(var M=Math.min(e.inHeight,l+_),B=N+F*w,P=0;P<e.outWidth;++P){for(var L=P*a-p,W=L;W<0;)W+=u;for(var U=Math.min(e.inWidth,h+L),V=B+P*C,z=v,G=0,H=0,q=T;q<D;q+=i){for(var K=I+q*t.strides[1],j=O;j<M;j+=s){for(var X=K+j*t.strides[2],Y=W;Y<U;Y+=u){var $=g[X+Y*t.strides[3]+k];if("max"===n&&$>z?z=$:"avg"===n&&(G+=$,H++),isNaN(z))break}if(isNaN(z))break}if(isNaN(z))break}y[V+k]="avg"===n?G/H:z}}}return m.toTensor()},o.prototype.avgPool3d=function(t,e){return df(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},o.prototype.avgPool3dBackprop=function(t,e,n){df([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=n.dilationDepth,l=n.dilationHeight,h=n.dilationWidth,f=n.effectiveFilterDepth,d=n.effectiveFilterHeight,p=n.effectiveFilterWidth,v=f-1-n.padInfo.front,g=p-1-n.padInfo.left,m=d-1-n.padInfo.top,y=er(e.shape,"float32"),x=1/(i*s*u),b=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var E=0;E<n.inDepth;++E)for(var R=0;R<n.inHeight;++R)for(var I=0;I<n.inWidth;++I){for(var k=E-v,S=R-m,A=I-g,T=0,D=0;D<f;D+=c){var N=(k+D)/r;if(!(N<0||N>=n.outDepth||Math.floor(N)!==N))for(var F=0;F<d;F+=l){var _=(S+F)/o;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var O=0;O<p;O+=h){var M=(A+O)/a;if(!(M<0||M>=n.outWidth||Math.floor(M)!==M))T+=b.get(w,N,_,M,C)}}}y.set(T*x,w,E,R,I,C)}return y.toTensor()},o.prototype.maxPool3d=function(t,e){return df(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},o.prototype.maxPool3dPositions=function(t,e){for(var n=er(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,f=e.padInfo.front,d=e.padInfo.top,p=e.padInfo.left,v=this.bufferSync(t),g=0;g<e.batchSize;++g)for(var m=0;m<e.inChannels;++m)for(var y=0;y<e.outDepth;++y){for(var x=y*r-f,b=x;b<0;)b+=i;for(var w=Math.min(e.inDepth,c+x),C=0;C<e.outHeight;++C){for(var E=C*o-d,R=E;R<0;)R+=s;for(var I=Math.min(e.inHeight,l+E),k=0;k<e.outWidth;++k){for(var S=k*a-p,A=S;A<0;)A+=u;for(var T=Math.min(e.inWidth,h+S),D=Number.NEGATIVE_INFINITY,N=-1,F=b;F<w;F+=i)for(var _=F-x,O=R;O<I;O+=s)for(var M=O-E,B=A;B<T;B+=u){var P=B-S,L=v.get(g,F,O,B,m);L>=D&&(D=L,N=_*l*h+M*l+P)}n.set(N,g,y,C,k,m)}}}return n.toTensor()},o.prototype.maxPool3dBackprop=function(t,e,n,r){df([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),a=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,h=r.effectiveFilterDepth,f=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=h-1-r.padInfo.front,v=d-1-r.padInfo.left,g=f-1-r.padInfo.top,m=er(e.shape,"float32"),y=this.bufferSync(o),x=this.bufferSync(t),b=0;b<r.batchSize;++b)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var E=0;E<r.inHeight;++E)for(var R=0;R<r.inWidth;++R){for(var I=C-p,k=E-g,S=R-v,A=0,T=0;T<h;T+=u){var D=(I+T)/a;if(!(D<0||D>=r.outDepth||Math.floor(D)!==D))for(var N=0;N<f;N+=c){var F=(k+N)/i;if(!(F<0||F>=r.outHeight||Math.floor(F)!==F))for(var _=0;_<d;_+=l){var O=(S+_)/s;if(!(O<0||O>=r.outWidth||Math.floor(O)!==O)){var M=h*f*d-1-y.get(b,D,F,O,w)===T*f*d+N*d+_?1:0;if(0!==M)A+=x.get(b,D,F,O,w)*M}}}}m.set(A,b,C,E,R,w)}return m.toTensor()},o.prototype.cast=function(t,e){return Ra(t,e,this)},o.prototype.reshape=function(t,e){return Ia(t,e)},o.prototype.avgPool=function(t,e){return df(t,"avgPool"),df(t,"maxPool"),pf(this.readSync(t.dataId),t.shape,t.dtype,t.strides,e,"avg").toTensor().toFloat()},o.prototype.resizeBilinear=function(t,e,n,r){df(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(k([a,e,n,u])),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=0,p=h[0]/f[0],v=h[1]/f[1],g=0;g<a;g++)for(var m=0;m<e;m++)for(var y=p*m,x=Math.floor(y),b=y-x,w=Math.min(i-1,Math.ceil(y)),C=g*t.strides[0]+x*t.strides[1],E=g*t.strides[0]+w*t.strides[1],R=0;R<n;R++)for(var I=v*R,S=Math.floor(I),A=I-S,T=Math.min(s-1,Math.ceil(I)),D=C+S*t.strides[2],N=E+S*t.strides[2],F=C+T*t.strides[2],_=E+T*t.strides[2],O=0;O<u;O++){var M=c[D+O],B=c[N+O],P=M+(c[F+O]-M)*A,L=P+(B+(c[_+O]-B)*A-P)*b;l[d++]=L}return Fn(l,[a,e,n,u])},o.prototype.resizeBilinearBackprop=function(t,e,n){df([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*a*i*s),f=[n&&c>1?a-1:a,n&&l>1?i-1:i],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],p=f[0]/d[0],v=f[1]/d[1],g=this.readSync(t.dataId),m=0,y=0;y<o;y++)for(var x=y*e.strides[0],b=0;b<c;b++)for(var w=b*p,C=Math.floor(w),E=Math.min(Math.ceil(w),a-1),R=x+C*e.strides[1],I=x+E*e.strides[1],k=w-C,S=1-k,A=0;A<l;A++)for(var T=A*v,D=Math.floor(T),N=Math.min(Math.ceil(T),i-1),F=T-D,_=1-F,O=R+D*e.strides[2],M=R+N*e.strides[2],B=I+D*e.strides[2],P=I+N*e.strides[2],L=S*_,W=S*F,U=k*_,V=k*F,z=0;z<s;z++){var G=g[m++];h[O+z]+=G*L,h[M+z]+=G*W,h[B+z]+=G*U,h[P+z]+=G*V}return Ln(h,[o,i,a,s],e.dtype)},o.prototype.resizeNearestNeighbor=function(t,e,n,r){df(t,"resizeNearestNeighbor");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(a*e*n*u),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=h[0]/f[0],p=h[1]/f[1],v=0,g=0;g<a;g++)for(var m=g*t.strides[0],y=0;y<e;y++)for(var x=d*y,b=m+Math.min(i-1,r?Math.round(x):Math.floor(x))*t.strides[1],w=0;w<n;w++)for(var C=p*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],R=0;R<u;R++){var I=c[E+R];l[v++]=I}return Fn(l,[a,e,n,u],t.dtype)},o.prototype.resizeNearestNeighborBackprop=function(t,e,n){df([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*a*i*s),f=this.readSync(t.dataId),d=[n&&c>1?a-1:a,n&&l>1?i-1:i],p=[n&&c>1?c-1:c,n&&l>1?l-1:l],v=d[0]/p[0],g=d[1]/p[1],m=1/v,y=1/g,x=2*Math.ceil(m)+2,b=2*Math.ceil(y)+2,w=0;w<o;w++)for(var C=w*e.strides[0],E=0;E<a;E++)for(var R=C+E*e.strides[1],I=Math.floor(E*m),k=Math.floor(I-x/2),S=0;S<i;S++)for(var A=R+S*e.strides[2],T=Math.floor(S*y),D=Math.floor(T-b/2),N=0;N<s;N++){for(var F=0,_=0;_<x;_++){var O=_+k;if(!(O<0||O>=c)){var M=C+O*t.strides[1],B=O*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P<b;P++){var L=P+D;if(!(L<0||L>=l)){var W=M+L*t.strides[2],U=L*g;S===Math.min(i-1,n?Math.round(U):Math.floor(U))&&(F+=f[W+N])}}}}h[A+N]=F}return Ln(h,e.shape,e.dtype)},o.prototype.batchNormalization=function(t,e,n,r,o,a){df([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),l=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),f=l.length,d=c.length,p=u.length,v=s.length,g=0,m=0,y=0,x=0,b=0;b<i.length;++b)h[b]=l[g++]+(i[b]-s[m++])*c[y++]/Math.sqrt(u[x++]+r),g>=f&&(g=0),m>=v&&(m=0),y>=d&&(y=0),x>=p&&(x=0);return Ln(h,t.shape)},o.prototype.localResponseNormalization4D=function(t,e,n,r,o){df(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var c=s[r];u+=c*c}return u}for(var h=0;h<u;h++){var f=l(h),d=s[h]*Math.pow(n+r*f,-o);c[h]=d}return Ln(c,t.shape)},o.prototype.LRNGrad=function(t,e,n,r,o,a,i){df(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=this.readSync(n.dataId),h=new Float32Array(t.size),f=t.size,d=0;d<f;d++){for(var p=d%s,v=d-p+Math.max(0,p-r),g=d-p+Math.min(s,p+r+1),m=0,y=v;y<g;y++)m+=Math.pow(c[y],2);m=a*m+o;for(y=v;y<g;y++){var x=-2*a*i*c[y]*l[d]/m;d===y&&(x+=Math.pow(m,-i)),x*=u[d],h[y]+=x}}return Ln(h,t.shape)},o.prototype.multinomial=function(t,e,n,r){df(t,"multinomial");for(var o=e?t:ia(t),a=o.shape[0],i=o.shape[1],s=Gn([a,n],"int32"),u=this.readSync(s.dataId),c=this.readSync(o.dataId),l=0;l<a;++l){var h=l*i,f=new Float32Array(i-1);f[0]=c[h];for(var d=1;d<f.length;++d)f[d]=f[d-1]+c[h+d];for(var p=Yu(r.toString()),v=l*n,g=0;g<n;++g){var m=p();u[v+g]=f.length;for(var y=0;y<f.length;y++)if(m<f[y]){u[v+g]=y;break}}}return s},o.prototype.oneHot=function(t,e,n,r){df(t,"oneHot");var o=new Float32Array(t.size*e);o.fill(r);for(var a=this.readSync(t.dataId),i=0;i<t.size;++i)a[i]>=0&&a[i]<e&&(o[i*e+a[i]]=n);return Bn(o,[t.size,e],"int32")},o.prototype.nonMaxSuppression=function(t,e,n,r,o){return df(t,"nonMaxSuppression"),Oa(this.readSync(t.dataId),this.readSync(e.dataId),n,r,o)},o.prototype.fft=function(t){return this.fftBatch(t,!1)},o.prototype.ifft=function(t){return this.fftBatch(t,!0)},o.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],o=er(t.shape,"float32"),a=er(t.shape,"float32"),i=Dn(t).as2D(n,r),s=Nn(t).as2D(n,r),u=0;u<n;u++)for(var c=i.slice([u,0],[1,r]),l=s.slice([u,0],[1,r]),h=Tn(c,l),f=this.readSync(this.fftImpl(h,e).dataId),d=0;d<r;d++){var p=Ta(f,d);o.values[u*r+d]=p.real,a.values[u*r+d]=p.imag}return Tn(o.toTensor(),a.toTensor()).as2D(n,r)},o.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var o=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(o=Tn(Dn(o).div(On(r)),Nn(o).div(On(r)))),o}var a=this.readSync(t.dataId),i=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(a,r,e));return Tn(i.real,i.imag).as2D(t.shape[0],t.shape[1])},o.prototype.isExponentOf2=function(t){return 0==(t&t-1)},o.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),o=e/2,a=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=0;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),i=Tn(a.real,a.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=2;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),u=Tn(s.real,s.imag).as1D();i=this.fftRadix2(i,o,n),u=this.fftRadix2(u,o,n);var c=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),o=0;o<Math.ceil(t/2);o++){var a=(e?2:-2)*Math.PI*(o/t);n[o]=Math.cos(a),r[o]=Math.sin(a)}return{real:n,imag:r}}(e,n),l=Tn(c.real,c.imag).mul(u),h=i.add(l),f=i.sub(l),d=Dn(h).concat(Dn(f)),p=Nn(h).concat(Nn(f));return Tn(d,p).as1D()},o.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),o=0;o<e;o++){for(var a=0,i=0,s=0;s<e;s++){var u=Na(o*s,e,n),c=Ta(t,s);a+=c.real*u.real-c.imag*u.imag,i+=c.real*u.imag+c.imag*u.real}n&&(a/=e,i/=e),Da(r,a,i,o)}return r},o.prototype.depthToSpace=function(t,e,n){C("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),C(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,c=i/(e*e),l=this.readSync(t.dataId),h=new Float32Array(r*s*u*c),f=0,d=0;d<r;++d)for(var p=0;p<s;++p)for(var v=Math.floor(p/e),g=p%e,m=0;m<u;++m)for(var y=Math.floor(m/e),x=(g*e+m%e)*c,b=0;b<c;++b){var w=b+x+i*(y+a*(v+o*d));h[f++]=l[w]}return Ln(h,[r,s,u,c])},o.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=Pr(t.shape,e.shape),a=er(o,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Mr(t.shape,o),c=Mr(e.shape,o),l=a.values;if(u.length+c.length===0)for(var h=0;h<l.length;++h)l[h]=r(i[h%i.length],s[h%s.length]);else{var f=this.bufferSync(t),d=this.bufferSync(e),p=function(n){var o=a.indexToLoc(n),h=o.slice(-t.rank);u.forEach((function(t){return h[t]=0}));var p=f.locToIndex(h),v=o.slice(-e.rank);c.forEach((function(t){return v[t]=0}));var g=d.locToIndex(v);l[n]=r(i[p],s[g])};for(h=0;h<l.length;++h)p(h)}return a.toTensor()},o.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=Pr(t.shape,e.shape),o=er(r,"float32"),a=er(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Mr(t.shape,r),c=Mr(e.shape,r),l=o.values,h=a.values;if(u.length+c.length===0)for(var f=0;f<l.length;f++){var d=f%i.length,p=f%s.length,v=n(i[2*d],i[2*d+1],s[2*p],s[2*p+1]);l[f]=v.real,h[f]=v.imag}else{var g=this.bufferSync(this.data.get(t.dataId).complexTensors.real),m=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var a=o.indexToLoc(r),f=a.slice(-t.rank);u.forEach((function(t){return f[t]=0}));var d=g.locToIndex(f),p=a.slice(-e.rank);c.forEach((function(t){return p[t]=0}));var v=m.locToIndex(p),y=n(i[2*d],i[2*d+1],s[2*v],s[2*v+1]);l[r]=y.real,h[r]=y.imag};for(f=0;f<l.length;f++)y(f)}return this.complex(o.toTensor(),a.toTensor())},o.prototype.split=function(t,e,n){return Ua(t,e,n)},o.prototype.dispose=function(){},o.prototype.floatPrecision=function(){return 32},o.prototype.epsilon=function(){return 1e-7},o.prototype.cropAndResize=function(t,e,n,r,o,a){for(var i=t.shape,s=i[0],u=i[1],c=i[2],l=i[3],h=e.shape[0],f=r[0],d=r[1],p=er([h,f,d,l],"float32"),v=this.readSync(e.dataId),g=this.readSync(n.dataId),m=this.readSync(t.dataId),y=t.strides,x=p.strides,b=0;b<h;b++){var w=4*b,C=v[w],E=v[w+1],R=v[w+2],I=v[w+3],k=g[b];if(!(k>=s))for(var S=f>1?(R-C)*(u-1)/(f-1):0,A=d>1?(I-E)*(c-1)/(d-1):0,T=0;T<f;T++){var D=f>1?C*(u-1)+T*S:.5*(C+R)*(u-1);if(D<0||D>u-1)for(var N=0;N<d;N++)for(var F=0;F<l;F++){var _=F+N*x[2]+T*x[1]+b*x[0];p.values[_]=a}else if("bilinear"===o){var O=Math.floor(D),M=Math.ceil(D),B=D-O;for(N=0;N<d;N++){if((q=d>1?E*(c-1)+N*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++){_=F+N*x[2]+T*x[1]+b*x[0];p.values[_]=a}else{var P=Math.floor(q),L=Math.ceil(q),W=q-P;for(F=0;F<l;F++){var U=m[_=F+P*y[2]+O*y[1]+k*y[0]],V=m[_=F+L*y[2]+O*y[1]+k*y[0]],z=m[_=F+P*y[2]+M*y[1]+k*y[0]],G=U+(V-U)*W,H=z+(m[_=F+L*y[2]+M*y[1]+k*y[0]]-z)*W;_=F+N*x[2]+T*x[1]+b*x[0],p.values[_]=G+(H-G)*B}}}}else for(N=0;N<d;++N){var q;if((q=d>1?E*(c-1)+N*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++){_=F+N*x[2]+T*x[1]+b*x[0];p.values[_]=a}else{var K=Math.round(q),j=Math.round(D);for(F=0;F<l;F++){var X=F+K*y[2]+j*y[1]+k*y[0],Y=F+N*x[2]+T*x[1]+b*x[0];p.values[Y]=m[X]}}}}}return p.toTensor()},o.prototype.sparseToDense=function(t,e,n,r){var o=Go(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.sliceSize,u=o.strides,c=o.outputSize;return this.scatter(t,e,n,c,s,i,a,u,r,!1)},o.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Po(t,e),a=o[0],i=o[1],s=o[2],u=o[3];if(0===i)return Fn([],a,t.dtype);for(var c=new mt([i,s],t.dtype),l=this.readSync(e.dataId),h=this.readSync(t.dataId),f=0;f<i;f++){for(var d=[],p=0,v=0;v<r;v++){var g=l[f*r+v];p+=g*u[v],d.push(g)}if(p<0||p>=t.size/s)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var m=0;m<s;m++)c.values[f*s+m]=h[p*s+m]}return c.toTensor().reshape(a)},o.prototype.scatterND=function(t,e,n){var r=Go(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=On(0);return this.scatter(t,e,n,u,i,a,o,s,c,!0)},o.prototype.fill=function(t,e,n){var r=P(n=n||j(e),k(t));return r.fill(e),Lt.makeTensor(r,t,n,this)},o.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},o.prototype.zerosLike=function(t){var e=P(t.dtype,k(t.shape));return this.makeOutput(e,t.shape,t.dtype)},o.prototype.linspace=function(t,e,n){return ka(t,e,n)},o.prototype.scatter=function(t,e,n,r,o,a,i,s,u,c){var l=[r/o,o],h=this.readSync(t.dataId),f=this.readSync(e.dataId);if(0===r)return Fn([],n,e.dtype);var d=new mt(l,e.dtype);d.values.fill(this.readSync(u.dataId)[0]);for(var p=0;p<a;p++){for(var v=[],g=0,m=0;m<i;m++){var y=h[p*i+m];v.push(y),g+=y*s[m]}if(g<0||g>=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var x=0;x<o;x++)c?d.values[g*o+x]+=f[p*o+x]:d.values[g*o+x]=0===e.rank?f[0]:f[p*o+x]}return d.toTensor().reshape(n)},o}(la);function yf(t,e){return{kernelName:t,backendName:"cpu",kernelFunc:function(n){var r=n.inputs,o=n.backend,a=r,i=a.a,s=a.b,u=o;df([i,s],t);var c=u.data.get(i.dataId).values,l=u.data.get(s.dataId).values,h=e(i.shape,s.shape,c,l,i.dtype),f=h[0],d=h[1];return{dataId:u.write(f,d,i.dtype),shape:d,dtype:i.dtype}}}}function xf(t){return function(e,n,r,o,a){var i=Pr(e,n),s=i.length,u=$(i),c=B(a,k(i)),l=e.length,h=n.length,f=$(e),d=$(n),p=Mr(e,i),v=Mr(n,i);if(p.length+v.length===0)for(var g=0;g<c.length;++g)c[g]=t(r[g%r.length],o[g%o.length]);else{var m=function(e){var n=it(e,s,u),a=n.slice(-l);p.forEach((function(t){return a[t]=0}));var i=at(a,l,f),g=n.slice(-h);v.forEach((function(t){return g[t]=0}));var m=at(g,h,d);c[e]=t(r[i],o[m])};for(g=0;g<c.length;++g)m(g)}return[c,i]}}Lt.registerBackend("cpu",(function(){return new mf}),1);var bf=xf((function(t,e){return t/e})),wf=yf(wr,bf);var Cf={kernelName:"MaxPoolWithArgmax",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.attrs,r=t.backend,o=e.x,a=n,i=a.filterSize,s=a.strides,u=a.pad,c=a.includeBatchInIndex,l=r;df(o,"MaxPoolWithArgmax");var h=l.data.get(o.dataId).values,f=fa(o.shape,i,s,[1,1],u),d=function(t,e,n,r,o){var a=pf(t,0,n,$(e),o,"max"),i=vf(t,e,n,o,!0,r);return[a.values,i.values]}(h,o.shape,o.dtype,c,f),p=d[0],v=d[1],g=l.write(p,f.outShape,o.dtype),m=l.write(v,f.outShape,o.dtype);return[{dataId:g,shape:f.outShape,dtype:o.dtype},{dataId:m,shape:f.outShape,dtype:"int32"}]}},Ef={kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e,a=o.boxes,i=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=n;df(a,"NonMaxSuppressionWithScore");var d=Ma(f.data.get(a.dataId).values,f.data.get(i.dataId).values,u,c,l,h);return[d.selectedIndices,d.selectedScores]}},Rf={kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n;df(r,"square");for(var a=o.data.get(r.dataId).values,i=new Float32Array(a.length),s=0;s<a.length;++s){var u=a[s];i[s]=u*u}return{dataId:o.write(i,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},If=xf((function(t,e){var n=t-e;return n*n}));function kf(t,e,n,r,o){for(var a=k(e),i=e.length,s=$(e),u=$(o),c=B(n,k(o)),l=0;l<a;++l){for(var h=it(l,i,s),f=new Array(h.length),d=0;d<f.length;d++)f[d]=h[r[d]];c[at(f,i,u)]=t[l]}return c}for(var Sf=0,Af=[Ef,Rf,yf(Er,If),wf,{kernelName:"Transpose",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.attrs,r=t.backend,o=e.x,a=n.perm,i=r;df(o,"transpose");for(var s=o.shape.length,u=new Array(s),c=0;c<u.length;c++)u[c]=o.shape[a[c]];var l=kf(i.data.get(o.dataId).values,o.shape,o.dtype,a,u);return{dataId:i.write(l,u,o.dtype),shape:u,dtype:o.dtype}}},Cf];Sf<Af.length;Sf++){d(Af[Sf])}var Tf,Df=function(t){this.variableNames=["A"];var e=Ya(),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 "},Nf=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=Ya(),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) /\n 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 "};var Ff=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var o=ui(this.rank),a=function(t){var e=t.length;if(e>6)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),o=0;o<t.length;o++)r[t[o]]=n[o];return r.join()}(e);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "};var _f=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=ui(this.rank),a=ja("rc",this.rank),i=new Array(this.rank);for(r=0;r<e.length;r++)i[e[r]]=a[r];var s="vec2("+i.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+n[this.rank-1],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = "+c+";\n if("+u+") {\n result[1] = "+c+";\n }\n --"+a[this.rank-1]+";\n if(++"+a[this.rank-2]+" < "+n[this.rank-2]+") {\n result[2] = "+c+";\n if("+u+") {\n result[3] = "+c+";\n }\n }\n setOutput(result);\n }\n "};for(var Of=0,Mf=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e.pixels,a=r.numChannels,s="undefined"!=typeof HTMLVideoElement&&o instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&o instanceof HTMLImageElement,c=s?[o.videoWidth,o.videoHeight]:[o.width,o.height],l=c[0],h=c[1],f=[h,l],d=[h,l,a];(u||s)&&(null==Tf&&(Tf=document.createElement("canvas").getContext("2d")),Tf.canvas.width=l,Tf.canvas.height=h,Tf.drawImage(o,0,0,l,h),o=Tf.canvas);var p=n.makeTensorInfo(f,"int32");n.texData.get(p.dataId).usage=zt.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),o);var v=i().getBool("WEBGL_PACK")?new Nf(d):new Df(d),g=n.runWebGLProgram(v,[p],"int32");return n.disposeData(p.dataId),g}},{kernelName:wr,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e;return function(t,e,n){var r=new Ri(Ci,t.shape,e.shape);return i().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&(r=new Si(Ii,t.shape,e.shape,!0)),n.runWebGLProgram(r,[t,e],"float32")}(r.a,r.b,n)}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs;dn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var o=e,a=o.boxes,i=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=n,d=Ma(f.readSync(a.dataId),f.readSync(i.dataId),u,c,l,h);return[d.selectedIndices,d.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n,a=new cu(r.shape,"return x * x;");return o.runWebGLProgram(a,[r],r.dtype)}},{kernelName:Er,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,a=r.b,s=n,u=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si("return (a - b) * (a - b);",o.shape,a.shape):new Ri("return (a - b) * (a - b);",o.shape,a.shape);return s.compileAndRun(u,[o,a])}},{kernelName:"Transpose",backendName:"webgl",kernelFunc:function(t){for(var e,n=t.inputs,r=t.attrs,o=t.backend,a=n.x,s=r.perm,u=o,c=a.shape.length,l=new Array(c),h=0;h<l.length;h++)l[h]=a.shape[s[h]];if(u.shouldExecuteOnCPU([a])){var f=kf(u.texData.get(a.dataId).values,a.shape,a.dtype,s,l);e=u.makeTensorInfo(l,a.dtype),u.texData.get(e.dataId).values=f}else e=function(t,e,n){var r=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _f(t.shape,e):new Ff(t.shape,e);return n.runWebGLProgram(r,[t],t.dtype)}(a,s,u);return e}},{kernelName:"MaxPoolWithArgmax",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.attrs,r=t.backend,o=e.x,a=n,i=a.filterSize,s=a.strides,u=a.pad,c=a.includeBatchInIndex,l=r;C(4===o.shape.length,(function(){return"Error in maxPool: input must be rank 4 but got rank "+o.shape.length+"."}));var h=[1,1];C(Ca(s,h),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+s+" and dilations '"+h+"'"}));var f=fa(o.shape,i,s,h,u),d=function(t,e,n,r){var o=new Ws(n,"max",!1),a=r.runWebGLProgram(o,[t],"float32");return o=new Ws(n,"max",!0,!0,e),[a,r.runWebGLProgram(o,[t],"float32")]}(o,c,f,l);return[d[0],d[1]]}}];Of<Mf.length;Of++){d(Mf[Of])}for(var Bf=0,Pf=[{kernelName:xr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],o=Pr(n.shape,r.shape);return{a:function(){var e=t,r=Br(n.shape,o);return r.length>0&&(e=e.sum(r)),e.reshape(n.shape)},b:function(){var e=t,n=Br(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)}}}},{kernelName:"AddN",saveAllInputs:!0,gradFunc:function(t,e){var n={};return e.forEach((function(e,r){n[r]=function(){return t.clone()}})),n}},{kernelName:Sr,gradFunc:function(t,e,n){for(var r=n,o=r.inputShape,a=r.shape,i=Array.from(a),s=o.length-1;s>=0;s--)if(o[s]===a[s])i[s]=1;else if(1!==o[s])throw new Error("broadcastTo(): ["+o+"] cannot be broadcast to ["+a+"].");var u=[];for(s=0;s<i.length;s++)i[s]>1&&u.push(s);return{x:function(){return t.sum(u,!0)}}}},{kernelName:wr,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],o=Pr(n.shape,r.shape);return{a:function(){var e=Bo(t,r.toFloat()),a=Br(n.shape,o);return a.length>0?th(e,a).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),a=Br(r.shape,o);a.length>0&&(e=th(e,a).reshape(r.shape));var i=Gc(r);return no(Bo(e,i.toFloat()))}}}},{kernelName:"FusedBatchNorm",inputsToSave:["x","mean","variance","scale"],gradFunc:function(t,e,n){var r=n.varianceEpsilon,o=e[0],a=e[1],i=e[2],s=e[3],u=Ju(o),c=null==s?On(1):s,l=Br(a.shape,u.shape),h=[];if(1===a.rank){for(var f=0;f<u.shape.length-1;++f)h.push(u.shape[f]);h.push(1)}var d=Oo(o,a),p=To(t,c),v=ao(Or(i,On(r))),g=To(To(To(v,v),v),On(-.5));return{x:function(){return 1===a.rank?ur(To(To(t,wc(v.as4D(1,1,1,a.shape[0]),h)),c),o.shape):ur(To(To(t,v),c),o.shape)},mean:function(){var t=To(To(v,On(-1)),p);return 1===a.rank&&(t=th(t,l)),ur(t,a.shape)},variance:function(){var t=To(To(g,d),p);return 1===a.rank&&(t=th(t,l)),ur(t,a.shape)},scale:function(){var e=To(d,v),n=To(t,e);return 1===a.rank&&(n=th(n,l)),ur(n,a.shape)},offset:function(){var e=t;return 1===a.rank&&(e=th(e,l)),ur(e,a.shape)}}}},{kernelName:Tr,gradFunc:function(t){return{x:function(){return t.toFloat()}}}},{kernelName:Ar,inputsToSave:["indices"],gradFunc:function(t,e){var n=e[0];return{indices:function(){return Gn(n.shape,"float32")}}}},{kernelName:Nr,inputsToSave:["x"],gradFunc:function(t,e,n){var r=e[0],o=n.paddings.map((function(t){return t[0]}));return{x:function(){return t.slice(o,r.shape)}}}},{kernelName:"Square",inputsToSave:["x"],gradFunc:function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().mul(2))}}}},{kernelName:Er,inputsToSave:["a","b"],gradFunc:function(t,e){var n=e[0],r=e[1],o=On(2);return{a:function(){return To(t,To(o,Oo(n,r)))},b:function(){return To(t,To(o,Oo(r,n)))}}}},{kernelName:Dr,inputsToSave:["x"],gradFunc:function(t,e,n){var r=e[0],o=n.reps;return{x:function(){var e=Xn(r);if(1===r.rank)for(var n=0;n<o[0];++n)e=e.add(t.slice([n*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(n=0;n<o[0];++n)for(var a=0;a<o[1];++a)e=e.add(t.slice([n*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(n=0;n<o[0];++n)for(a=0;a<o[1];++a)for(var i=0;i<o[2];++i)e=e.add(t.slice([n*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(n=0;n<o[0];++n)for(a=0;a<o[1];++a)for(i=0;i<o[2];++i)for(var s=0;s<o[3];++s)e=e.add(t.slice([n*r.shape[0],a*r.shape[1],i*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return e}}}},{kernelName:"Transpose",gradFunc:function(t,e,n){var r=Rn(n.perm);return{x:function(){return ua(t,r)}}}}];Bf<Pf.length;Bf++){p(Pf[Bf])}var Lf=function(){function t(){}return t.prototype.fetch=function(t,e){return fetch(t,e)},t.prototype.now=function(){return performance.now()},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();i().get("IS_BROWSER")&&i().setPlatform("browser",new Lf);var Wf,Uf=function(){return __webpack_require__(479)},Vf=function(){function t(){this.util=__webpack_require__(478),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=i().global.fetch?i().global.fetch(t,e):(null==Wf&&(Wf=Uf()),Wf(t,e))},t.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)},t}();i().get("IS_NODE")&&i().setPlatform("node",new Vf);var zf={float32:4,int32:4,uint16:2,uint8:1,bool:1},Gf=4;function Hf(t,e){for(var n={},r=0,o=function(e){var o=e.name,a=e.dtype,i=e.shape,s=k(i),u=void 0;if("quantization"in e){var c=e.quantization;if("uint8"!==c.dtype&&"uint16"!==c.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+c.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=zf[c.dtype],h=t.slice(r,r+s*l),f="uint8"===c.dtype?new Uint8Array(h):new Uint16Array(h);if("float32"===a)u=Float32Array.from(f,(function(t){return t*c.scale+c.min}));else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=Int32Array.from(f,(function(t){return Math.round(t*c.scale+c.min)}))}r+=s*l}else if("string"===a){var d=k(e.shape);u=[];for(var p=0;p<d;p++){var v=new Uint32Array(t.slice(r,r+Gf))[0];r+=Gf;var g=new Uint8Array(t.slice(r,r+v));u.push(g),r+=v}}else{var m=zf[a];h=t.slice(r,r+s*m);if("float32"===a)u=new Float32Array(h);else if("int32"===a)u=new Int32Array(h);else{if("bool"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=new Uint8Array(h)}r+=s*m}n[o]=Fn(u,i,a)},a=0,i=e;a<i.length;a++){o(i[a])}return n}function qf(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach((function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)}));var r=new Uint8Array(e),o=0;return n.forEach((function(t){r.set(new Uint8Array(t.buffer),o),o+=t.byteLength})),r.buffer}var Kf="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function jf(t){return Kf?Buffer.byteLength(t):new Blob([t]).size}function Xf(t){var e=0;t.forEach((function(t){e+=t.byteLength}));var n=new Uint8Array(e),r=0;return t.forEach((function(t){n.set(new Uint8Array(t),r),r+=t.byteLength})),n.buffer}function Yf(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function $f(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:jf(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:jf(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var Qf=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var o=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach((function(t){var n=t(e,r);null!==n&&o.push(n)})),o},t}(),Jf="://",Zf=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){C(null!=e,(function(){return"scheme must not be undefined or null."})),e.endsWith(Jf)&&(e=e.slice(0,e.indexOf(Jf))),C(e.length>0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();C(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 td(t){if(-1===t.indexOf(Jf))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Zf.getSchemes().join(","));return{scheme:t.split(Jf)[0],path:t.split(Jf)[1]}}function ed(t,e,o){return void 0===o&&(o=!1),n(this,void 0,void 0,(function(){var n,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return C(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),C((n=Qf.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),C(n.length<2,(function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+t+"."})),a=n[0],C((i=Qf.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),C(i.length<2,(function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+e+"."})),s=i[0],u=td(t).scheme,c=td(t).path,l=u===td(t).scheme,[4,a.load()];case 1:return h=r.sent(),o&&l?[4,Zf.getManager(u).removeModel(c)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[4,s.save(h)];case 4:return f=r.sent(),!o||l?[3,6]:[4,Zf.getManager(u).removeModel(c)];case 5:r.sent(),r.label=6;case 6:return[2,f.modelArtifactsInfo]}}))}))}var nd="models_store",rd="model_info_store";function od(){if(!i().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,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 ad(t){var e=t.result;e.createObjectStore(nd,{keyPath:"modelPath"}),e.createObjectStore(rd,{keyPath:"modelPath"})}var id=function(){function t(t){if(this.indexedDB=od(),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 n(this,void 0,void 0,(function(){return r(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 n(this,void 0,void 0,(function(){return r(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 o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return ad(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(nd,"readonly"),s=i.objectStore(nd).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},i.oncomplete=function(){return a.close()}}else{var u,c=$f(e),l=a.transaction(rd,"readwrite"),h=l.objectStore(rd),f=h.put({modelPath:n.modelPath,modelArtifactsInfo:c});f.onsuccess=function(){var o=(u=a.transaction(nd,"readwrite")).objectStore(nd).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});o.onsuccess=function(){return t({modelArtifactsInfo:c})},o.onerror=function(t){var e=(h=l.objectStore(rd)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)}}},f.onerror=function(t){return a.close(),r(f.error)},l.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},o.onerror=function(t){return r(o.error)}}))},t.URL_SCHEME="indexeddb://",t}(),sd=function(t){return i().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(id.URL_SCHEME)?(e=t.slice(id.URL_SCHEME.length),new id(e)):null;var e};Qf.registerSaveRouter(sd),Qf.registerLoadRouter(sd);var ud=function(){function t(){this.indexedDB=od()}return t.prototype.listModels=function(){return n(this,void 0,void 0,(function(){var t=this;return r(this,(function(e){return[2,new Promise((function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return ad(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(rd,"readonly"),a=o.objectStore(rd).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n<r.length;n++){var o=r[n];t[o.modelPath]=o.modelArtifactsInfo}e(t)},a.onerror=function(e){return t.close(),n(a.error)},o.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}}))]}))}))},t.prototype.removeModel=function(t){return n(this,void 0,void 0,(function(){var e=this;return r(this,(function(n){var r;return t=(r=t).startsWith(id.URL_SCHEME)?r.slice(id.URL_SCHEME.length):r,[2,new Promise((function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return ad(o)},o.onsuccess=function(){var e,a=o.result,i=a.transaction(rd,"readwrite"),s=i.objectStore(rd),u=s.get(t);u.onsuccess=function(){if(null==u.result)return a.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var o=s.delete(t),i=function(){var o=(e=a.transaction(nd,"readwrite")).objectStore(nd).delete(t);o.onsuccess=function(){return n(u.result.modelArtifactsInfo)},o.onerror=function(t){return r(u.error)}};o.onsuccess=i,o.onerror=function(t){return i(),a.close(),r(u.error)}},u.onerror=function(t){return a.close(),r(u.error)},i.oncomplete=function(){null==e?a.close():e.oncomplete=function(){return a.close()}}},o.onerror=function(t){return r(o.error)}}))]}))}))},t}();if(i().getBool("IS_BROWSER"))try{Zf.registerManager(id.URL_SCHEME,new ud)}catch(t){}var cd="/",ld="tensorflowjs_models",hd="info",fd="model_topology",dd="weight_specs",pd="weight_data",vd="model_metadata";function gd(t){return{info:[ld,t,hd].join(cd),topology:[ld,t,fd].join(cd),weightSpecs:[ld,t,dd].join(cd),weightData:[ld,t,pd].join(cd),modelMetadata:[ld,t,vd].join(cd)}}function md(t){var e=t.split(cd);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(cd)}var yd=function(){function t(t){if(!i().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=gd(this.modelPath)}return t.prototype.save=function(t){return n(this,void 0,void 0,(function(){var e,n,o;return r(this,(function(r){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),o=$f(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(t){if(Kf)return Buffer.from(t).toString("base64");for(var e=new Uint8Array(t),n="",r=0,o=e.length;r<o;r++)n+=String.fromCharCode(e[r]);return btoa(n)}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),[2,{modelArtifactsInfo:o}]}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+o.modelTopologyBytes+", weightSpecsBytes="+o.weightSpecsBytes+", weightDataBytes="+o.weightDataBytes+".")}return[2]}))}))},t.prototype.load=function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i,s;return r(this,(function(r){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(o=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=o,null!=(a=this.LS.getItem(this.keys.modelMetadata))&&(i=JSON.parse(a),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy,e.userDefinedMetadata=i.userDefinedMetadata),null==(s=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(Kf){var e=Buffer.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var n=atob(t),r=new Uint8Array(n.length),o=0;o<n.length;++o)r.set([n.charCodeAt(o)],o);return r.buffer}(s),[2,e]}))}))},t.URL_SCHEME="localstorage://",t}(),xd=function(t){return i().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(yd.URL_SCHEME)?(e=t.slice(yd.URL_SCHEME.length),new yd(e)):null;var e};Qf.registerSaveRouter(xd),Qf.registerLoadRouter(xd);var bd=function(){function t(){C(i().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),C("undefined"==typeof window||void 0!==window.localStorage,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return t.prototype.listModels=function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i;return r(this,(function(r){for(t={},e=ld+cd,n=cd+hd,o=0;o<this.LS.length;++o)(a=this.LS.key(o)).startsWith(e)&&a.endsWith(n)&&(i=md(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t]}))}))},t.prototype.removeModel=function(t){return n(this,void 0,void 0,(function(){var e,n;return r(this,(function(r){var o;if(t=(o=t).startsWith(yd.URL_SCHEME)?o.slice(yd.URL_SCHEME.length):o,e=gd(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n]}))}))},t}();if(i().getBool("IS_BROWSER"))try{Zf.registerManager(yd.URL_SCHEME,new bd)}catch(t){}var wd="model",Cd=".json",Ed=".weights.bin";function Rd(t){return new Promise((function(t){return setTimeout(t)})).then(t)}var Id=function(){function t(e){if(!i().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e=wd),this.modelTopologyFileName=e+Cd,this.weightDataFileName=e+Ed}return t.prototype.save=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,i,s;return r(this,(function(r){switch(r.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),(i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,Rd((function(){return i.dispatchEvent(new MouseEvent("click"))}))];case 2:return r.sent(),null==t.weightData?[3,4]:((s=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,Rd((function(){return s.dispatchEvent(new MouseEvent("click"))}))]);case 3:r.sent(),r.label=4;case 4:return[2,{modelArtifactsInfo:$f(t)}]}}))}))},t.URL_SCHEME="downloads://",t}(),kd=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return n(this,void 0,void 0,(function(){var t,e,n=this;return r(this,(function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise((function(r,o){var a=new FileReader;a.onload=function(a){var i=JSON.parse(a.target.result),s=i.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=i.weightsManifest;if(null!=u){var c;try{c=n.checkManifestAndWeightFiles(u,e)}catch(t){return void o(t)}var l=[],h=[],f=[];u.forEach((function(t){t.paths.forEach((function(t){h.push(t),f.push(null)})),l.push.apply(l,t.weights)})),u.forEach((function(t){t.paths.forEach((function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,o=h.indexOf(t);f[o]=n,-1===f.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:Xf(f),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy,userDefinedMetadata:i.userDefinedMetadata})},e.onerror=function(e){return o("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(c[t])}))}))}else o(new Error("weightManifest field is missing from file "+t.name))}else o(new Error("modelTopology field is missing from file "+t.name))},a.onerror=function(e){return o("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},a.readAsText(t)}))]}))}))},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map((function(t){return Yf(t.name)})),o={},a=0,i=t;a<i.length;a++){i[a].paths.forEach((function(t){var a=Yf(t);if(-1!==n.indexOf(a))throw new Error("Duplicate file basename found in weights manifest: '"+a+"'");if(n.push(a),-1===r.indexOf(a))throw new Error("Weight file with basename '"+a+"' is not provided.");o[t]=e[r.indexOf(a)]}))}if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return o},t}();function Sd(t,e,n,r){!function(t){C(null!=t&&Array.isArray(t)&&t.length>0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){C(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),C(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),C(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 o=0;return Promise.all(t.map((function(a){return a.then((function(a){var i=n+ ++o/t.length*(r-n);return e(i),a})),a})))}function Ad(t,e){return n(this,void 0,void 0,(function(){var n,o,a,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?i().platform.fetch:e.fetchFunc,o=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),a=0,s=.5,null!=e.onProgress?[3,2]:[4,Promise.all(o)];case 1:return u=r.sent(),[3,4];case 2:return[4,Sd(o,e.onProgress,a,s)];case 3:u=r.sent(),r.label=4;case 4:return c=u.map((function(t){return t.arrayBuffer()})),l=.5,h=1,null!=e.onProgress?[3,6]:[4,Promise.all(c)];case 5:return f=r.sent(),[3,8];case 6:return[4,Sd(c,e.onProgress,l,h)];case 7:f=r.sent(),r.label=8;case 8:return[2,f]}}))}))}function Td(t){var e=this;return function(o,a,i){return void 0===a&&(a=""),n(e,void 0,void 0,(function(){var e,n,s,u,c,l,h,f,d,p;return r(this,(function(r){switch(r.label){case 0:if(e=o.map((function(){return!1})),n={},s=null!=i?i.map((function(){return!1})):[],u=[],o.forEach((function(t,r){var o=0;t.weights.forEach((function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,c=zf[a]*k(t.shape),l=function(){e[r]=!0,null==n[r]&&(n[r]=[]),n[r].push({manifestEntry:t,groupOffset:o,sizeBytes:c})};null!=i?i.forEach((function(e,n){e===t.name&&(l(),s[n]=!0)})):l(),u.push(t.name),o+=c}))})),!s.every((function(t){return t})))throw c=i.filter((function(t,e){return!s[e]})),new Error("Could not find weights in manifest with names: "+c.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return l=e.reduce((function(t,e,n){return e&&t.push(n),t}),[]),h=[],l.forEach((function(t){o[t].paths.forEach((function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e)}))})),[4,t(h)];case 1:return f=r.sent(),d={},p=0,l.forEach((function(t){for(var e=o[t].paths.length,r=0,a=0;a<e;a++)r+=f[p+a].byteLength;for(var i=new ArrayBuffer(r),s=new Uint8Array(i),u=0,c=0;c<e;c++){var l=new Uint8Array(f[p+c]);s.set(l,u),u+=l.byteLength}n[t].forEach((function(t){var e=Hf(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)d[n]=e[n]})),p+=e})),[2,d]}}))}))}}Qf.registerSaveRouter((function(t){return i().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Id.URL_SCHEME)?function(t){void 0===t&&(t="model");return new Id(t)}(t.slice(Id.URL_SCHEME.length)):null}));var Dd=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(C("function"==typeof e.fetchFunc,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=e.fetchFunc):this.fetch=i().platform.fetch,C(null!=t&&t.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&C(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 n(this,void 0,void 0,(function(){var e,n,o,a;return r(this,(function(r){switch(r.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}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(o)],{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((a=r.sent()).ok)return[2,{modelArtifactsInfo:$f(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},t.prototype.load=function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=r.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.");r.label=2;case 2:return r.trys.push([2,4,,5]),[4,t.json()];case 3:return e=r.sent(),[3,5];case 4:throw r.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(o=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,null==o&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:f=r.sent(),l=f[0],h=f[1],r.label=7;case 7:return[2,{modelTopology:o,weightSpecs:l,weightData:h,userDefinedMetadata:c,generatedBy:i,convertedBy:s,format:u}]}}))}))},t.prototype.loadWeights=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return[r+"/",o]}(e),o=n[0],a=n[1],i=this.weightPathPrefix||o,s=[],u=0,c=t;u<c.length;u++)l=c[u],s.push.apply(s,l.weights);return h=[],t.forEach((function(t){t.paths.forEach((function(t){h.push(i+t+a)}))})),[4,Ad(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return f=r.sent(),[2,[s,Xf(f)]]}}))}))},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function Nd(t){return null!=t.match(Dd.URL_SCHEME_REGEX)}var Fd=function(t,e){if("undefined"==typeof fetch)return null;return(Array.isArray(t)?t.every((function(t){return Nd(t)})):Nd(t))?_d(t,{onProgress:e}):null};function _d(t,e){return new Dd(t,e)}Qf.registerSaveRouter(Fd),Qf.registerLoadRouter(Fd);var Od=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){return[2,this.modelArtifacts]}))}))},t}(),Md=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){return[2,this.saveHandler(t)]}))}))},t}();var Bd=Object.freeze({browserFiles:function(t){return new kd(t)},browserHTTPRequest:function(t,e){return _d(t,e)},concatenateArrayBuffers:Xf,decodeWeights:Hf,encodeWeights:function(t,e){return n(this,void 0,void 0,(function(){var o,a,i,s,u,c=this;return r(this,(function(l){switch(l.label){case 0:for(o=[],a=[],i=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t),s=function(s){var u=i[s],l=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+l.dtype);var h={name:u,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var f=new Promise((function(t){return n(c,void 0,void 0,(function(){var e,n,o,a,i,s,u;return r(this,(function(r){switch(r.label){case 0:return[4,l.bytes()];case 1:for(e=r.sent(),n=e.reduce((function(t,e){return t+e.length}),0)+Gf*e.length,o=new Uint8Array(n),a=0,i=0;i<e.length;i++)s=e[i],u=new Uint8Array(new Uint32Array([s.length]).buffer),o.set(u,a),a+=Gf,o.set(s,a),a+=s.length;return t(o),[2]}}))}))}));a.push(f)}else a.push(l.data());null!=e&&(h.group=e),o.push(h)},u=0;u<i.length;++u)s(u);return[4,Promise.all(a)];case 1:return[2,{data:qf(l.sent()),specs:o}]}}))}))},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Od(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Od({modelTopology:t})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Od({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return Qf.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:$f,getSaveHandlers:function(t){return Qf.getSaveHandlers(t)},http:_d,isHTTPScheme:Nd,loadWeights:function(t,e,o,a){return void 0===e&&(e=""),n(this,void 0,void 0,(function(){return r(this,(function(n){return[2,Td((function(t){return Ad(t,{requestInit:a})}))(t,e,o)]}))}))},registerLoadRouter:function(t){return Qf.registerLoadRouter(t)},registerSaveRouter:function(t){return Qf.registerSaveRouter(t)},weightsLoaderFactory:Td,withSaveHandler:function(t){return new Md(t)},copyModel:function(t,e){return n(this,void 0,void 0,(function(){return r(this,(function(n){return!1,[2,ed(t,e,!1)]}))}))},listModels:function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i,s;return r(this,(function(r){switch(r.label){case 0:t=Zf.getSchemes(),e={},n=0,o=t,r.label=1;case 1:return n<o.length?(a=o[n],[4,Zf.getManager(a).listModels()]):[3,4];case 2:for(s in i=r.sent())e[a+Jf+s]=i[s];r.label=3;case 3:return n++,[3,1];case 4:return[2,e]}}))}))},moveModel:function(t,e){return n(this,void 0,void 0,(function(){return r(this,(function(n){return!0,[2,ed(t,e,!0)]}))}))},removeModel:function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){return e=td(t),[2,Zf.getManager(e.scheme).removeModel(e.path)]}))}))}});var Pd,Ld=An({confusionMatrix_:function(t,e,n){var r=gn(t,"labels","confusionMatrix"),o=gn(e,"predictions","confusionMatrix");C(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),C(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),C(1===o.rank,(function(){return"Expected the rank of predictions to be 1, but got "+o.rank})),C(r.shape[0]===o.shape[0],(function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."})),C(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var a=Rc(r.asType("int32"),n),i=Rc(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),Wd=Object.freeze({confusionMatrix:Ld});var Ud=An({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.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,o=!1,a=!1,i=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)o=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)a=!0;else{if(null==t.getContext)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);i=!0}if(o){if(o&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(null!=l("FromPixels",Lt.backendName))return Lt.runKernel("FromPixels",{pixels:t},{numChannels:e});var s,u,c=o?[t.videoWidth,t.videoHeight]:[t.width,t.height],h=c[0],f=c[1];if(i?s=t.getContext("2d").getImageData(0,0,h,f).data:r||n?s=t.data:(a||o)&&(null==Pd&&(Pd=document.createElement("canvas").getContext("2d")),Pd.canvas.width=h,Pd.canvas.height=f,Pd.drawImage(t,0,0,h,f),s=Pd.getImageData(0,0,h,f).data),4===e)u=new Int32Array(s);else{var d=h*f;u=new Int32Array(d*e);for(var p=0;p<d;p++)for(var v=0;v<e;++v)u[p*e+v]=s[4*p+v]}return Pn(u,[f,h,e],"int32")}}),Vd=Object.freeze({toPixels:function(t,e){return n(this,void 0,void 0,(function(){var n,o,a,i,s,u,c,l,h,f,d,p,v,g,m,y,x,b,w,C,E,R,I;return r(this,(function(r){switch(r.label){case 0:if(n=gn(t,"img","toPixels"),t instanceof wt||(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(o=n.shape.slice(0,2),a=o[0],i=o[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return[4,n.data()];case 1:return u=r.sent(),c=n.min(),l=n.max(),[4,Promise.all([c.data(),l.data()])];case 2:if(h=r.sent(),f=h[0],d=h[1],p=f[0],v=d[0],c.dispose(),l.dispose(),"float32"===n.dtype){if(p<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+p+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(p<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+p+" - "+v+"].")}for(g="float32"===n.dtype?255:1,m=new Uint8ClampedArray(i*a*4),y=0;y<a*i;++y)x=void 0,b=void 0,w=void 0,C=void 0,1===s?(x=u[y]*g,b=u[y]*g,w=u[y]*g,C=255):3===s?(x=u[3*y]*g,b=u[3*y+1]*g,w=u[3*y+2]*g,C=255):4===s&&(x=u[4*y]*g,b=u[4*y+1]*g,w=u[4*y+2]*g,C=u[4*y+3]*g),m[(E=4*y)+0]=Math.round(x),m[E+1]=Math.round(b),m[E+2]=Math.round(w),m[E+3]=Math.round(C);return null!=e&&(e.width=i,e.height=a,R=e.getContext("2d"),I=new ImageData(m,i,a),R.putImageData(I,0,0)),n!==t&&n.dispose(),[2,m]}}))}))},fromPixels:Ud}),zd=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Gd=function(){function t(){this.classNameMap={}}return t.getMap=function(){return null==t.instance&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function Hd(t){C(null!=t.className,(function(){return"Class being registered does not have the static className property defined."})),C("string"==typeof t.className,(function(){return"className is required to be a string, but got type "+typeof t.className})),C(t.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),Gd.register(t)}var qd=Object.freeze({Serializable:zd,SerializationMap:Gd,registerClass:Hd}),Kd="1.7.2";var jd=Object.freeze({gpgpu_util:Rs,webgl_util:Ge,forceHalfFloat:function(){i().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Uu,setWebGLContext:Kt,GPGPUContext:Is}),Xd=function(t){function o(){return null!==t&&t.apply(this,arguments)||this}return e(o,t),o.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,a=r.grads;if(null!=n){var i=n.map((function(t){return{name:t.name,tensor:a[t.name]}}));this.applyGradients(i)}else this.applyGradients(a);return tn(a),e?o:(o.dispose(),null)},Object.defineProperty(o.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),o.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},o.prototype.computeGradients=function(t,e){return ra(t,e)},o.prototype.dispose=function(){null!=this.iterations_&&tn(this.iterations_)},o.prototype.saveIterations=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:On(this.iterations_,"int32")}]}))}))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}))}))},o.prototype.extractIterations=function(t){return n(this,void 0,void 0,(function(){var e;return r(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)]}}))}))},o}(zd);Object.defineProperty(Xd,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var Yd=function(t){function o(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=Lt.backend.epsilon()),o}return e(o,t),o.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 o=Lt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Ze((function(){return Xn(o).variable(!1)}))}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Ze((function(){return Xn(o).variable(!1)}))});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Ze((function(){var t=i.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u)}))}})),this.incrementIterations()},o.prototype.dispose=function(){null!=this.accumulatedUpdates&&(tn(this.accumulatedGrads.map((function(t){return t.variable}))),tn(this.accumulatedUpdates.map((function(t){return t.variable}))))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){var t;return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,!1,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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},o.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},o.className="Adadelta",o}(Xd);Hd(Yd);var $d=function(t){function o(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return e(o,t),o.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 o=Lt.registeredVariables[n];if(null==e.accumulatedGrads[r]){e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Ze((function(){return Hn(o.shape,e.initialAccumulatorValue).variable(!1)}))}}var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable;Ze((function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(Lt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)}))}})),this.incrementIterations()},o.prototype.dispose=function(){null!=this.accumulatedGrads&&tn(this.accumulatedGrads.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),!1,this.accumulatedGrads=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},o.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},o.className="Adagrad",o}(Xd);Hd($d);var Qd=function(t){function o(e,n,r,o){void 0===o&&(o=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],Ze((function(){a.accBeta1=On(n).variable(),a.accBeta2=On(r).variable()})),null==o&&(a.epsilon=Lt.backend.epsilon()),a}return e(o,t),o.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Ze((function(){var r=Oo(1,e.accBeta1),o=Oo(1,e.accBeta2);n.forEach((function(n,a){var i=Lt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Ze((function(){return Xn(i).variable(!1)}))}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:Ze((function(){return Xn(i).variable(!1)}))});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedSecondMoment[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),f=l.div(r),d=h.div(o);u.assign(l),c.assign(h);var p=f.div(d.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(p)}})),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))})),this.incrementIterations()},o.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&tn(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedSecondMoment&&tn(this.accumulatedSecondMoment.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){var t;return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){var e,n=this;return r(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Ze((function(){n.accBeta1.assign(No(n.beta1,n.iterations_+1)),n.accBeta2.assign(No(n.beta2,n.iterations_+1))})),e=t.length/2,!1,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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},o.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},o.className="Adam",o}(Xd);Hd(Qd);var Jd=function(t){function o(e,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.decay=a,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Ze((function(){i.iteration=On(0).variable(),i.accBeta1=On(n).variable()})),null==o&&(i.epsilon=Lt.backend.epsilon()),i}return e(o,t),o.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Ze((function(){var r=Oo(1,e.accBeta1),o=Bo(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach((function(n,a){var i=Lt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Xn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:Xn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedWeightedInfNorm[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2),f=s.abs(),d=h.maximum(f);u.assign(l),c.assign(d);var p=o.div(r).mul(l.div(d.add(e.epsilon))).add(i);i.assign(p)}})),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))})),this.incrementIterations()},o.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&tn(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedWeightedInfNorm&&tn(this.accumulatedWeightedInfNorm.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("getWeights() is not implemented for Adamax yet.")}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("setWeights() is not implemented for Adamax yet.")}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},o.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},o.className="Adamax",o}(Xd);Hd(Jd);var Zd=function(t){function o(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return e(o,t),o.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 o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=Lt.registeredVariables[n];Ze((function(){var t=e.c.mul(o).add(a);a.assign(t)}))}})),this.incrementIterations()},o.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=en(On(-t))},o.prototype.dispose=function(){this.c.dispose()},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate}},o.fromConfig=function(t,e){return new t(e.learningRate)},o.className="SGD",o}(Xd);Hd(Zd);var tp=function(t){function o(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=On(o.momentum),o}return e(o,t),o.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 o=Lt.registeredVariables[n];if(null==e.accumulations[r]){e.accumulations[r]={originalName:n+"/momentum",variable:Ze((function(){return Xn(o).variable(!1)}))}}var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Ze((function(){var t,n=e.m.mul(a).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),a.assign(n),o.assign(t)}))})),this.incrementIterations()},o.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&tn(this.accumulations.map((function(t){return t.variable})))},o.prototype.setMomentum=function(t){this.momentum=t},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),!1,this.accumulations=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},o.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},o.className="Momentum",o}(Zd);Hd(tp);var ep=function(t){function o(e,n,r,o,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===a&&(a=!1);var i=t.call(this)||this;if(i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=o,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=a,null==o&&(i.epsilon=Lt.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.");return i}return e(o,t),o.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 o=Lt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Ze((function(){return Xn(o).variable(!1)}))}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Ze((function(){return Xn(o).variable(!1)}))}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Ze((function(){return Xn(o).variable(!1)}))});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Ze((function(){var t=i.mul(e.decay).add(a.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(a.mul(1-e.decay)),c=s.mul(e.momentum).add(a.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(c);var l=o.sub(c);o.assign(l)}else{var h=i.mul(e.decay).add(a.square().mul(1-e.decay));c=s.mul(e.momentum).add(a.mul(e.learningRate).div(h.add(e.epsilon).sqrt()));i.assign(h),s.assign(c);l=o.sub(c);o.assign(l)}}))}})),this.incrementIterations()},o.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&tn(this.accumulatedMeanSquares.map((function(t){return t.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&tn(this.accumulatedMeanGrads.map((function(t){return t.variable}))),null!=this.accumulatedMoments&&tn(this.accumulatedMoments.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){var t;return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){var e;return r(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,!1,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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},o.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},o.className="RMSProp",o}(Xd);Hd(ep);var np=function(){function t(){}return t.sgd=function(t){return new Zd(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new tp(t,e,n)},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new ep(t,e,n,r,o)},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 Qd(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 Yd(t,e,n)},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new Jd(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new $d(t,e)},t}(),rp={sgd:np.sgd,momentum:np.momentum,adadelta:np.adadelta,adagrad:np.adagrad,rmsprop:np.rmsprop,adamax:np.adamax,adam:np.adam},op="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function ap(){return new Promise((function(t){return op((function(){return t()}))}))}wt.prototype.add=function(t){return Or(this,t)},wt.prototype.broadcastTo=function(t){return fc(this,t)},wt.prototype.div=function(t){return Bo(this,t)},wt.prototype.divNoNan=function(t){return bc(this,t)},wt.prototype.squaredDifference=function(t){return Hc(this,t)},wt.prototype.tile=function(t){return wc(this,t)},wt.prototype.oneHot=function(t,e,n){return void 0===e&&(e=1),void 0===n&&(n=0),Rc(this,t,e,n)},wt.prototype.transpose=function(t){return ua(this,t)},wt.prototype.pad=function(t,e){return Ic(this,t,e)},wt.prototype.batchNorm=function(t,e,n,r,o){return nc(this,t,e,n,r,o)},xt=ff;
//# sourceMappingURL=tf-core.esm.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53), __webpack_require__(87), __webpack_require__(86).Buffer, __webpack_require__(244).setImmediate))
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// CONCATENATED MODULE: ./node_modules/vega-util/src/accessor.js
/* harmony default export */ var accessor = (function(fn, fields, name) {
fn.fields = fields || [];
fn.fname = name;
return fn;
});
function accessorName(fn) {
return fn == null ? null : fn.fname;
}
function accessorFields(fn) {
return fn == null ? null : fn.fields;
}
// CONCATENATED MODULE: ./node_modules/vega-util/src/error.js
/* harmony default export */ var error = (function(message) {
throw Error(message);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/splitAccessPath.js
/* harmony default export */ var splitAccessPath = (function(p) {
var path = [],
q = null,
b = 0,
n = p.length,
s = '',
i, j, c;
p = p + '';
function push() {
path.push(s + p.substring(i, j));
s = '';
i = j + 1;
}
for (i=j=0; j<n; ++j) {
c = p[j];
if (c === '\\') {
s += p.substring(i, j);
s += p.substring(++j, ++j);
i = j;
} else if (c === q) {
push();
q = null;
b = -1;
} else if (q) {
continue;
} else if (i === b && c === '"') {
i = j + 1;
q = c;
} else if (i === b && c === "'") {
i = j + 1;
q = c;
} else if (c === '.' && !b) {
if (j > i) {
push();
} else {
i = j + 1;
}
} else if (c === '[') {
if (j > i) push();
b = i = j + 1;
} else if (c === ']') {
if (!b) error('Access path missing open bracket: ' + p);
if (b > 0) push();
b = 0;
i = j + 1;
}
}
if (b) error('Access path missing closing bracket: ' + p);
if (q) error('Access path missing closing quote: ' + p);
if (j > i) {
j++;
push();
}
return path;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isArray.js
/* harmony default export */ var isArray = (Array.isArray);
// CONCATENATED MODULE: ./node_modules/vega-util/src/isObject.js
/* harmony default export */ var isObject = (function(_) {
return _ === Object(_);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isString.js
/* harmony default export */ var isString = (function(_) {
return typeof _ === 'string';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/stringValue.js
function stringValue_$(x) {
return isArray(x) ? '[' + x.map(stringValue_$) + ']'
: isObject(x) || isString(x) ?
// Output valid JSON and JS source strings.
// See http://timelessrepo.com/json-isnt-a-javascript-subset
JSON.stringify(x).replace('\u2028','\\u2028').replace('\u2029', '\\u2029')
: x;
}
// CONCATENATED MODULE: ./node_modules/vega-util/src/field.js
/* harmony default export */ var src_field = (function(field, name) {
var path = splitAccessPath(field),
code = 'return _[' + path.map(stringValue_$).join('][') + '];';
return accessor(
Function('_', code),
[(field = path.length===1 ? path[0] : field)],
name || field
);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/accessors.js
var accessors_empty = [];
var accessors_id = src_field('id');
var accessors_identity = accessor(function(_) { return _; }, accessors_empty, 'identity');
var accessors_zero = accessor(function() { return 0; }, accessors_empty, 'zero');
var accessors_one = accessor(function() { return 1; }, accessors_empty, 'one');
var accessors_truthy = accessor(function() { return true; }, accessors_empty, 'true');
var accessors_falsy = accessor(function() { return false; }, accessors_empty, 'false');
// CONCATENATED MODULE: ./node_modules/vega-util/src/logger.js
function logger_log(method, level, input) {
var args = [level].concat([].slice.call(input));
console[method].apply(console, args); // eslint-disable-line no-console
}
var None = 0;
var logger_Error = 1;
var Warn = 2;
var Info = 3;
var Debug = 4;
/* harmony default export */ var logger = (function(_, method) {
var level = _ || None;
return {
level: function(_) {
if (arguments.length) {
level = +_;
return this;
} else {
return level;
}
},
error: function() {
if (level >= logger_Error) logger_log(method || 'error', 'ERROR', arguments);
return this;
},
warn: function() {
if (level >= Warn) logger_log(method || 'warn', 'WARN', arguments);
return this;
},
info: function() {
if (level >= Info) logger_log(method || 'log', 'INFO', arguments);
return this;
},
debug: function() {
if (level >= Debug) logger_log(method || 'log', 'DEBUG', arguments);
return this;
}
}
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/mergeConfig.js
const mergeConfig_isLegalKey = key => key !== '__proto__';
function mergeConfig_mergeConfig(...configs) {
return configs.reduce((out, source) => {
for (var key in source) {
if (key === 'signals') {
// for signals, we merge the signals arrays
// source signals take precedence over
// existing signals with the same name
out.signals = mergeConfig_mergeNamed(out.signals, source.signals);
} else {
// otherwise, merge objects subject to recursion constraints
// for legend block, recurse for the layout entry only
// for style block, recurse for all properties
// otherwise, no recursion: objects overwrite, no merging
var r = key === 'legend' ? {layout: 1}
: key === 'style' ? true
: null;
mergeConfig_writeConfig(out, key, source[key], r);
}
}
return out;
}, {});
}
function mergeConfig_writeConfig(output, key, value, recurse) {
if (!mergeConfig_isLegalKey(key)) return;
var k, o;
if (isObject(value) && !isArray(value)) {
o = isObject(output[key]) ? output[key] : (output[key] = {});
for (k in value) {
if (recurse && (recurse === true || recurse[k])) {
mergeConfig_writeConfig(o, k, value[k]);
} else if (mergeConfig_isLegalKey(k)) {
o[k] = value[k];
}
}
} else {
output[key] = value;
}
}
function mergeConfig_mergeNamed(a, b) {
if (a == null) return b;
const map = {}, out = [];
function add(_) {
if (!map[_.name]) {
map[_.name] = 1;
out.push(_);
}
}
b.forEach(add);
a.forEach(add);
return out;
}
// CONCATENATED MODULE: ./node_modules/vega-util/src/peek.js
/* harmony default export */ var peek = (function(array) {
return array[array.length - 1];
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/toNumber.js
/* harmony default export */ var toNumber = (function(_) {
return _ == null || _ === '' ? null : +_;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/transform.js
function transform_exp(sign) {
return function(x) { return sign * Math.exp(x); };
}
function transform_log(sign) {
return function(x) { return Math.log(sign * x); };
}
function transform_symlog(c) {
return function(x) { return Math.sign(x) * Math.log1p(Math.abs(x / c)); };
}
function transform_symexp(c) {
return function(x) { return Math.sign(x) * Math.expm1(Math.abs(x)) * c; };
}
function transform_pow(exponent) {
return function(x) {
return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
};
}
function transform_pan(domain, delta, lift, ground) {
var d0 = lift(domain[0]),
d1 = lift(peek(domain)),
dd = (d1 - d0) * delta;
return [
ground(d0 - dd),
ground(d1 - dd)
];
}
function transform_panLinear(domain, delta) {
return transform_pan(domain, delta, toNumber, accessors_identity);
}
function transform_panLog(domain, delta) {
var sign = Math.sign(domain[0]);
return transform_pan(domain, delta, transform_log(sign), transform_exp(sign));
}
function transform_panPow(domain, delta, exponent) {
return transform_pan(domain, delta, transform_pow(exponent), transform_pow(1/exponent));
}
function transform_panSymlog(domain, delta, constant) {
return transform_pan(domain, delta, transform_symlog(constant), transform_symexp(constant));
}
function transform_zoom(domain, anchor, scale, lift, ground) {
var d0 = lift(domain[0]),
d1 = lift(peek(domain)),
da = anchor != null ? lift(anchor) : (d0 + d1) / 2;
return [
ground(da + (d0 - da) * scale),
ground(da + (d1 - da) * scale)
];
}
function transform_zoomLinear(domain, anchor, scale) {
return transform_zoom(domain, anchor, scale, toNumber, accessors_identity);
}
function transform_zoomLog(domain, anchor, scale) {
var sign = Math.sign(domain[0]);
return transform_zoom(domain, anchor, scale, transform_log(sign), transform_exp(sign));
}
function transform_zoomPow(domain, anchor, scale, exponent) {
return transform_zoom(domain, anchor, scale, transform_pow(exponent), transform_pow(1/exponent));
}
function transform_zoomSymlog(domain, anchor, scale, constant) {
return transform_zoom(domain, anchor, scale, transform_symlog(constant), transform_symexp(constant));
}
// CONCATENATED MODULE: ./node_modules/vega-util/src/quarter.js
function quarter(date) {
return 1 + ~~(new Date(date).getMonth() / 3);
}
function utcquarter(date) {
return 1 + ~~(new Date(date).getUTCMonth() / 3);
}
// CONCATENATED MODULE: ./node_modules/vega-util/src/array.js
/* harmony default export */ var src_array = (function(_) {
return _ != null ? (isArray(_) ? _ : [_]) : [];
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/clampRange.js
/**
* Span-preserving range clamp. If the span of the input range is less
* than (max - min) and an endpoint exceeds either the min or max value,
* the range is translated such that the span is preserved and one
* endpoint touches the boundary of the min/max range.
* If the span exceeds (max - min), the range [min, max] is returned.
*/
/* harmony default export */ var clampRange = (function(range, min, max) {
var lo = range[0],
hi = range[1],
span;
if (hi < lo) {
span = hi;
hi = lo;
lo = span;
}
span = hi - lo;
return span >= (max - min)
? [min, max]
: [
(lo = Math.min(Math.max(lo, min), max - span)),
lo + span
];
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isFunction.js
/* harmony default export */ var isFunction = (function(_) {
return typeof _ === 'function';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/compare.js
/* harmony default export */ var compare = (function(fields, orders) {
var idx = [],
cmp = (fields = src_array(fields)).map(function(f, i) {
if (f == null) {
return null;
} else {
idx.push(i);
return isFunction(f) ? f
: splitAccessPath(f).map(stringValue_$).join('][');
}
}),
n = idx.length - 1,
ord = src_array(orders),
code = 'var u,v;return ',
i, j, f, u, v, d, t, lt, gt;
if (n < 0) return null;
for (j=0; j<=n; ++j) {
i = idx[j];
f = cmp[i];
if (isFunction(f)) {
d = 'f' + i;
u = '(u=this.' + d + '(a))';
v = '(v=this.' + d + '(b))';
(t = t || {})[d] = f;
} else {
u = '(u=a['+f+'])';
v = '(v=b['+f+'])';
}
d = '((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))';
if (ord[i] !== 'descending') {
gt = 1;
lt = -1;
} else {
gt = -1;
lt = 1;
}
code += '(' + u+'<'+v+'||u==null)&&v!=null?' + lt
+ ':(u>v||v==null)&&u!=null?' + gt
+ ':'+d+'!==u&&v===v?' + lt
+ ':v!==v&&u===u?' + gt
+ (i < n ? ':' : ':0');
}
f = Function('a', 'b', code + ';');
if (t) f = f.bind(t);
fields = fields.reduce(function(map, field) {
if (isFunction(field)) {
(accessorFields(field) || []).forEach(function(_) { map[_] = 1; });
} else if (field != null) {
map[field + ''] = 1;
}
return map;
}, {});
return accessor(f, Object.keys(fields));
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/constant.js
/* harmony default export */ var constant = (function(_) {
return isFunction(_) ? _ : function() { return _; };
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/debounce.js
/* harmony default export */ var debounce = (function(delay, handler) {
var tid, evt;
function callback() {
handler(evt);
tid = evt = null;
}
return function(e) {
evt = e;
if (tid) clearTimeout(tid);
tid = setTimeout(callback, delay);
};
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/extend.js
/* harmony default export */ var extend = (function(_) {
for (var x, k, i=1, len=arguments.length; i<len; ++i) {
x = arguments[i];
for (k in x) { _[k] = x[k]; }
}
return _;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/extent.js
/**
* Return an array with minimum and maximum values, in the
* form [min, max]. Ignores null, undefined, and NaN values.
*/
/* harmony default export */ var extent = (function(array, f) {
var i = 0, n, v, min, max;
if (array && (n = array.length)) {
if (f == null) {
// find first valid value
for (v = array[i]; i < n && (v == null || v !== v); v = array[++i]);
min = max = v;
// visit all other values
for (; i<n; ++i) {
v = array[i];
// skip null/undefined; NaN will fail all comparisons
if (v != null) {
if (v < min) min = v;
if (v > max) max = v;
}
}
} else {
// find first valid value
for (v = f(array[i]); i < n && (v == null || v !== v); v = f(array[++i]));
min = max = v;
// visit all other values
for (; i<n; ++i) {
v = f(array[i]);
// skip null/undefined; NaN will fail all comparisons
if (v != null) {
if (v < min) min = v;
if (v > max) max = v;
}
}
}
}
return [min, max];
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/extentIndex.js
/* harmony default export */ var extentIndex = (function(array, f) {
var i = -1,
n = array.length,
a, b, c, u, v;
if (f == null) {
while (++i < n) {
b = array[i];
if (b != null && b >= b) {
a = c = b;
break;
}
}
if (i === n) return [-1, -1];
u = v = i;
while (++i < n) {
b = array[i];
if (b != null) {
if (a > b) {
a = b;
u = i;
}
if (c < b) {
c = b;
v = i;
}
}
}
} else {
while (++i < n) {
b = f(array[i], i, array);
if (b != null && b >= b) {
a = c = b;
break;
}
}
if (i === n) return [-1, -1];
u = v = i;
while (++i < n) {
b = f(array[i], i, array);
if (b != null) {
if (a > b) {
a = b;
u = i;
}
if (c < b) {
c = b;
v = i;
}
}
}
}
return [u, v];
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/hasOwnProperty.js
const hop = Object.prototype.hasOwnProperty;
/* harmony default export */ var src_hasOwnProperty = (function(object, property) {
return hop.call(object, property);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/fastmap.js
var fastmap_NULL = {};
/* harmony default export */ var fastmap = (function(input) {
var obj = {},
map,
test;
function has(key) {
return src_hasOwnProperty(obj, key) && obj[key] !== fastmap_NULL;
}
map = {
size: 0,
empty: 0,
object: obj,
has: has,
get: function(key) {
return has(key) ? obj[key] : undefined;
},
set: function(key, value) {
if (!has(key)) {
++map.size;
if (obj[key] === fastmap_NULL) --map.empty;
}
obj[key] = value;
return this;
},
delete: function(key) {
if (has(key)) {
--map.size;
++map.empty;
obj[key] = fastmap_NULL;
}
return this;
},
clear: function() {
map.size = map.empty = 0;
map.object = obj = {};
},
test: function(_) {
if (arguments.length) {
test = _;
return map;
} else {
return test;
}
},
clean: function() {
var next = {},
size = 0,
key, value;
for (key in obj) {
value = obj[key];
if (value !== fastmap_NULL && (!test || !test(value))) {
next[key] = value;
++size;
}
}
map.size = size;
map.empty = 0;
map.object = (obj = next);
}
};
if (input) Object.keys(input).forEach(function(key) {
map.set(key, input[key]);
});
return map;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/flush.js
/* harmony default export */ var flush = (function(range, value, threshold, left, right, center) {
if (!threshold && threshold !== 0) return center;
var a = range[0],
b = peek(range),
t = +threshold,
l, r;
// swap endpoints if range is reversed
if (b < a) {
l = a; a = b; b = l;
}
// compare value to endpoints
l = Math.abs(value - a);
r = Math.abs(b - value);
// adjust if value is within threshold distance of endpoint
return l < r && l <= t ? left : r <= t ? right : center;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/inherits.js
/* harmony default export */ var inherits = (function(child, parent) {
var proto = (child.prototype = Object.create(parent.prototype));
proto.constructor = child;
return proto;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/inrange.js
/**
* Predicate that returns true if the value lies within the span
* of the given range. The left and right flags control the use
* of inclusive (true) or exclusive (false) comparisons.
*/
/* harmony default export */ var inrange = (function(value, range, left, right) {
var r0 = range[0], r1 = range[range.length-1], t;
if (r0 > r1) {
t = r0;
r0 = r1;
r1 = t;
}
left = left === undefined || left;
right = right === undefined || right;
return (left ? r0 <= value : r0 < value) &&
(right ? value <= r1 : value < r1);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isBoolean.js
/* harmony default export */ var isBoolean = (function(_) {
return typeof _ === 'boolean';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isDate.js
/* harmony default export */ var isDate = (function(_) {
return Object.prototype.toString.call(_) === '[object Date]';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isNumber.js
/* harmony default export */ var isNumber = (function(_) {
return typeof _ === 'number';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/isRegExp.js
/* harmony default export */ var isRegExp = (function(_) {
return Object.prototype.toString.call(_) === '[object RegExp]';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/key.js
/* harmony default export */ var src_key = (function(fields, flat) {
if (fields) {
fields = flat
? src_array(fields).map(function(f) { return f.replace(/\\(.)/g, '$1'); })
: src_array(fields);
}
var fn = !(fields && fields.length)
? function() { return ''; }
: Function('_', 'return \'\'+' +
fields.map(function(f) {
return '_[' + (flat
? stringValue_$(f)
: splitAccessPath(f).map(stringValue_$).join('][')
) + ']';
}).join('+\'|\'+') + ';');
return accessor(fn, fields, 'key');
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/lerp.js
/* harmony default export */ var lerp = (function(array, frac) {
const lo = array[0],
hi = peek(array),
f = +frac;
return !f ? lo : f === 1 ? hi : lo + f * (hi - lo);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/lruCache.js
const lruCache_DEFAULT_MAX_SIZE = 10000;
// adapted from https://github.com/dominictarr/hashlru/ (MIT License)
/* harmony default export */ var lruCache = (function(maxsize) {
maxsize = +maxsize || lruCache_DEFAULT_MAX_SIZE;
let curr, prev, size;
const clear = () => {
curr = {};
prev = {};
size = 0;
};
const update = (key, value) => {
if (++size > maxsize) {
prev = curr;
curr = {};
size = 1;
}
return (curr[key] = value);
};
clear();
return {
clear,
has: key => src_hasOwnProperty(curr, key) || src_hasOwnProperty(prev, key),
get: key => src_hasOwnProperty(curr, key) ? curr[key]
: src_hasOwnProperty(prev, key) ? update(key, prev[key])
: undefined,
set: (key, value) => src_hasOwnProperty(curr, key)
? (curr[key] = value)
: update(key, value)
};
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/merge.js
/* harmony default export */ var merge = (function(compare, array0, array1, output) {
var n0 = array0.length,
n1 = array1.length;
if (!n1) return array0;
if (!n0) return array1;
var merged = output || new array0.constructor(n0 + n1),
i0 = 0, i1 = 0, i = 0;
for (; i0<n0 && i1<n1; ++i) {
merged[i] = compare(array0[i0], array1[i1]) > 0
? array1[i1++]
: array0[i0++];
}
for (; i0<n0; ++i0, ++i) {
merged[i] = array0[i0];
}
for (; i1<n1; ++i1, ++i) {
merged[i] = array1[i1];
}
return merged;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/repeat.js
/* harmony default export */ var repeat = (function(str, reps) {
var s = '';
while (--reps >= 0) s += str;
return s;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/pad.js
/* harmony default export */ var pad = (function(str, length, padchar, align) {
var c = padchar || ' ',
s = str + '',
n = length - s.length;
return n <= 0 ? s
: align === 'left' ? repeat(c, n) + s
: align === 'center' ? repeat(c, ~~(n/2)) + s + repeat(c, Math.ceil(n/2))
: s + repeat(c, n);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/span.js
/**
* Return the numerical span of an array: the difference between
* the last and first values.
*/
/* harmony default export */ var span = (function(array) {
return array && (peek(array) - array[0]) || 0;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/toBoolean.js
/* harmony default export */ var toBoolean = (function(_) {
return _ == null || _ === '' ? null : !_ || _ === 'false' || _ === '0' ? false : !!_;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/toDate.js
function toDate_defaultParser(_) {
return isNumber(_) ? _ : isDate(_) ? _ : Date.parse(_);
}
/* harmony default export */ var toDate = (function(_, parser) {
parser = parser || toDate_defaultParser;
return _ == null || _ === '' ? null : parser(_);
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/toString.js
/* harmony default export */ var src_toString = (function(_) {
return _ == null || _ === '' ? null : _ + '';
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/toSet.js
/* harmony default export */ var toSet = (function(_) {
for (var s={}, i=0, n=_.length; i<n; ++i) s[_[i]] = true;
return s;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/truncate.js
/* harmony default export */ var truncate = (function(str, length, align, ellipsis) {
var e = ellipsis != null ? ellipsis : '\u2026',
s = str + '',
n = s.length,
l = Math.max(0, length - e.length);
return n <= length ? s
: align === 'left' ? e + s.slice(n - l)
: align === 'center' ? s.slice(0, Math.ceil(l/2)) + e + s.slice(n - ~~(l/2))
: s.slice(0, l) + e;
});
// CONCATENATED MODULE: ./node_modules/vega-util/src/visitArray.js
/* harmony default export */ var visitArray = (function(array, filter, visitor) {
if (array) {
var i = 0, n = array.length, t;
if (filter) {
for (; i<n; ++i) {
if (t = filter(array[i])) visitor(t, i, array);
}
} else {
array.forEach(visitor);
}
}
});
// CONCATENATED MODULE: ./node_modules/vega-util/index.js
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "f", function() { return accessor; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "h", function() { return accessorName; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "g", function() { return accessorFields; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "w", function() { return accessors_id; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "x", function() { return accessors_identity; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ka", function() { return accessors_zero; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "O", function() { return accessors_one; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ga", function() { return accessors_truthy; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "r", function() { return accessors_falsy; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "K", function() { return logger; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "d", function() { return None; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "b", function() { return logger_Error; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "e", function() { return Warn; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "c", function() { return Info; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "a", function() { return Debug; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "N", function() { return mergeConfig_mergeConfig; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ja", function() { return mergeConfig_writeConfig; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Q", function() { return transform_panLinear; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "R", function() { return transform_panLog; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "S", function() { return transform_panPow; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "T", function() { return transform_panSymlog; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "La", function() { return transform_zoomLinear; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ma", function() { return transform_zoomLog; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Na", function() { return transform_zoomPow; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Oa", function() { return transform_zoomSymlog; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "V", function() { return quarter; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ha", function() { return utcquarter; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "i", function() { return src_array; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "j", function() { return clampRange; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "k", function() { return compare; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "l", function() { return constant; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "m", function() { return debounce; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "n", function() { return error; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "o", function() { return extend; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "p", function() { return extent; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "q", function() { return extentIndex; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "s", function() { return fastmap; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "t", function() { return src_field; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "u", function() { return flush; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "v", function() { return src_hasOwnProperty; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "y", function() { return inherits; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "z", function() { return inrange; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "A", function() { return isArray; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "B", function() { return isBoolean; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "C", function() { return isDate; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "D", function() { return isFunction; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "E", function() { return isNumber; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "F", function() { return isObject; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "G", function() { return isRegExp; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "H", function() { return isString; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "I", function() { return src_key; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "J", function() { return lerp; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "L", function() { return lruCache; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "M", function() { return merge; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "P", function() { return pad; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "U", function() { return peek; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "W", function() { return repeat; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "X", function() { return span; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Y", function() { return splitAccessPath; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Z", function() { return stringValue_$; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Aa", function() { return toBoolean; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ba", function() { return toDate; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ca", function() { return toNumber; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ea", function() { return src_toString; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Da", function() { return toSet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Fa", function() { return truncate; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Ia", function() { return visitArray; });
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global, process, Buffer, setImmediate) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdadeltaOptimizer", function() { return bd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdagradOptimizer", function() { return wd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdamOptimizer", function() { return Cd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AdamaxOptimizer", function() { return Ed; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataStorage", function() { return xo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ENV", function() { return s; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Environment", function() { return o; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KernelBackend", function() { return bo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MomentumOptimizer", function() { return Id; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Optimizer", function() { return xd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RMSPropOptimizer", function() { return kd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rank", function() { return Ct; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Reduction", function() { return ch; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SGDOptimizer", function() { return Rd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tensor", function() { return wt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TensorBuffer", function() { return gt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Variable", function() { return St; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "abs", function() { return ru; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "acos", function() { return ou; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "acosh", function() { return au; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "add", function() { return rc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addN", function() { return oc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addStrict", function() { return ac; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return Cl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return El; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argMax", function() { return Rl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argMin", function() { return Il; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asin", function() { return iu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "asinh", function() { return su; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atan", function() { return uu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atan2", function() { return ic; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atanh", function() { return cu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avgPool", function() { return fl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "avgPool3d", function() { return vl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backend", function() { return hn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "backend_util", function() { return Uo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "basicLSTMCell", function() { return zl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm", function() { return ju; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm2d", function() { return Xu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm3d", function() { return Yu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNorm4d", function() { return $u; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization", function() { return Ku; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization2d", function() { return Gu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization3d", function() { return Hu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchNormalization4d", function() { return qu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "batchToSpaceND", function() { return vr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "booleanMaskAsync", function() { return Uc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "broadcastTo", function() { return mr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "browser", function() { return id; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return dr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cast", function() { return gr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ceil", function() { return lu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clipByValue", function() { return hu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return yr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "complex", function() { return Dn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat", function() { return Yn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat1d", function() { return $n; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat2d", function() { return Qn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat3d", function() { return Jn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concat4d", function() { return Zn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv1d", function() { return Hc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv2d", function() { return qc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv2dTranspose", function() { return Zc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv3d", function() { return Kc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conv3dTranspose", function() { return tl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cos", function() { return fu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cosh", function() { return du; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cumsum", function() { return xr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "customGrad", function() { return vo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deprecationWarn", function() { return Xe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "depthToSpace", function() { return br; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "depthwiseConv2d", function() { return Yc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "diag", function() { return eh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disableDeprecationWarnings", function() { return je; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dispose", function() { return tn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "disposeVariables", function() { return Ye; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "div", function() { return sc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "divNoNan", function() { return uc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "divStrict", function() { return cc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dot", function() { return nl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dropout", function() { return nh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elu", function() { return _l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableDebugMode", function() { return Ke; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableProdMode", function() { return qe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "engine", function() { return $e; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "env", function() { return i; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equal", function() { return Rc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "equalStrict", function() { return Ic; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "erf", function() { return pu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exp", function() { return vu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expandDims", function() { return wr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "expm1", function() { return mu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "eye", function() { return Cr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fft", function() { return Xl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fill", function() { return Hn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBackend", function() { return un; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBackendFactory", function() { return cn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "floor", function() { return gu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "floorDiv", function() { return lc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frame", function() { return ih; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fused", function() { return zh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gather", function() { return Lc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gatherND", function() { return th; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "gather_util", function() { return Xr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBackend", function() { return an; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getGradient", function() { return h; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getKernel", function() { return l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getKernelsForBackend", function() { return f; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grad", function() { return co; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "grads", function() { return lo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greater", function() { return kc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterEqual", function() { return Sc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterEqualStrict", function() { return Ac; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "greaterStrict", function() { return Dc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hammingWindow", function() { return ah; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hannWindow", function() { return oh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ifft", function() { return Yl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "imag", function() { return Nn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "image", function() { return Oh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inTopKAsync", function() { return lh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "io", function() { return ed; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "irfft", function() { return Ql; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return Du; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isInf", function() { return Au; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return Su; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keep", function() { return en; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "leakyRelu", function() { return Ol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "less", function() { return Tc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessEqual", function() { return Nc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessEqualStrict", function() { return Fc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lessStrict", function() { return _c; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linalg", function() { return Ih; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "linspace", function() { return qn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "localResponseNormalization", function() { return Ul; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return yu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log1p", function() { return xu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSigmoid", function() { return bu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSoftmax", function() { return yo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logSumExp", function() { return kl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalAnd", function() { return Qu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalNot", function() { return Ju; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalOr", function() { return Zu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logicalXor", function() { return tc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "losses", function() { return bh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "matMul", function() { return el; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "math", function() { return od; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return Sl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPool", function() { return hl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maxPool3d", function() { return pl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maximum", function() { return hc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "maximumStrict", function() { return fc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mean", function() { return Al; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "memory", function() { return Qe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return Dl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minimum", function() { return dc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "minimumStrict", function() { return pc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mod", function() { return vc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "modStrict", function() { return mc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "moments", function() { return Tl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "movingAverage", function() { return Hl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mul", function() { return gc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mulStrict", function() { return yc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multiRNNCell", function() { return Gl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "multinomial", function() { return Er; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "neg", function() { return wu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "nextFrame", function() { return Td; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "norm", function() { return Vl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notEqual", function() { return Oc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "notEqualStrict", function() { return Mc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "oneHot", function() { return Rr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ones", function() { return zn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onesLike", function() { return jn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "op", function() { return An; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "outerProduct", function() { return rl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad", function() { return Ir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad1d", function() { return kr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad2d", function() { return Sr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad3d", function() { return Ar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pad4d", function() { return Dr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pool", function() { return dl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pow", function() { return xc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "powStrict", function() { return bc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prelu", function() { return Ml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "print", function() { return pr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prod", function() { return Fl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "profile", function() { return Je; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rand", function() { return Tr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomGamma", function() { return Fr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomNormal", function() { return Nr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomUniform", function() { return _r; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return Kn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ready", function() { return on; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "real", function() { return Tn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reciprocal", function() { return Cu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerBackend", function() { return ln; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerGradient", function() { return p; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerKernel", function() { return d; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relu", function() { return Bl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "relu6", function() { return Pl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeBackend", function() { return sn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reshape", function() { return Or; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse", function() { return ol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse1d", function() { return al; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse2d", function() { return il; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse3d", function() { return sl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reverse4d", function() { return ul; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rfft", function() { return $l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "round", function() { return Eu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rsqrt", function() { return Ru; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scalar", function() { return On; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scatterND", function() { return jl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scatter_util", function() { return to; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selu", function() { return Ll; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "separableConv2d", function() { return Jc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "serialization", function() { return ld; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setBackend", function() { return rn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPlatform", function() { return fn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setdiff1dAsync", function() { return Vr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sigmoid", function() { return Iu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sign", function() { return ku; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "signal", function() { return uh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sin", function() { return Tu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sinh", function() { return Nu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice", function() { return ml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice1d", function() { return gl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice2d", function() { return yl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice3d", function() { return xl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice4d", function() { return bl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "slice_util", function() { return uo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "softmax", function() { return go; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "softplus", function() { return Fu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spaceToBatchND", function() { return Mr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sparseToDense", function() { return Zl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spectral", function() { return Jl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "split", function() { return tr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sqrt", function() { return _u; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "square", function() { return tu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squaredDifference", function() { return nu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squaredDifferenceStrict", function() { return wc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "squeeze", function() { return Br; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stack", function() { return Pr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "step", function() { return Ou; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stft", function() { return sh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stridedSlice", function() { return ql; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sub", function() { return Cc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "subStrict", function() { return Ec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sum", function() { return Nl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sumOutType", function() { return Tt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tan", function() { return Mu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tanh", function() { return Bu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor", function() { return Fn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor1d", function() { return Mn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor2d", function() { return Bn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor3d", function() { return Pn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor4d", function() { return Ln; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor5d", function() { return Wn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor6d", function() { return Un; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tensor_util", function() { return Mt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "test_util", function() { return md; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tidy", function() { return Ze; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tile", function() { return Lr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "time", function() { return nn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "topk", function() { return Kl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "train", function() { return Ad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return Wl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "truncatedNormal", function() { return Wr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregisterGradient", function() { return m; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregisterKernel", function() { return v; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unsortedSegmentSum", function() { return Wc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unstack", function() { return Ur; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "util", function() { return st; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueAndGrad", function() { return ho; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "valueAndGrads", function() { return fo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variable", function() { return Vn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "variableGrads", function() { return po; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version_core", function() { return gd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "webgl", function() { return yd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "where", function() { return ec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "whereAsync", function() { return nc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zeros", function() { return Gn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zerosLike", function() { return Xn; });
/**
* @license
* Copyright 2020 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 t=function(e,n){return(t=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])})(e,n)};function e(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function n(t,e,n,r){return new(n||(n=Promise))((function(o,a){function i(t){try{u(r.next(t))}catch(t){a(t)}}function s(t){try{u(r.throw(t))}catch(t){a(t)}}function u(t){t.done?o(t.value):new n((function(e){e(t.value)})).then(i,s)}u((r=r.apply(t,e||[])).next())}))}function r(t,e){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}var o=function(){function t(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return t.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},t.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r)}},t.prototype.get=function(t){return t in this.flags?this.flags[t]:(this.flags[t]=this.evaluateFlag(t),this.flags[t])},t.prototype.getNumber=function(t){return this.get(t)},t.prototype.getBool=function(t){return this.get(t)},t.prototype.getFlags=function(){return this.flags},Object.defineProperty(t.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),t.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)},t.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},t.prototype.setFlags=function(t){this.flags=Object.assign({},t)},t.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},t.prototype.populateURLFlags=function(){var t=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var e,n,r=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return a(n,e[0],e[1]),e.join("=")})),n);if("tfjsflags"in r)r.tfjsflags.split(",").forEach((function(e){var n=e.split(":"),r=n[0],o=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(r,o)}))}},t}();function a(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}function i(){return s}var s=null;var u=new Map,c=new Map;function l(t,e){var n=g(t,e);return u.get(n)}function h(t){return c.get(t)}function f(t){for(var e=u.entries(),n=[];;){var r=e.next(),o=r.done,a=r.value;if(o)break;var i=a[0],s=a[1];i.split("_")[0]===t&&n.push(s)}return n}function d(t){var e=t.kernelName,n=t.backendName,r=g(e,n);if(u.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");u.set(r,t)}function p(t){var e=t.kernelName;c.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),c.set(e,t)}function v(t,e){var n=g(t,e);if(!u.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is not registered");u.delete(n)}function m(t){if(!c.has(t))throw new Error("The gradient '"+t+"' for backend is not registered");c.delete(t)}function g(t,e){return e+"_"+t}function y(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function x(t,e,n){return Math.max(t,Math.min(e,n))}function b(t){return t%2==0?t:t+1}function w(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function C(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function E(t,e,n){void 0===n&&(n=""),C(S(t,e),(function(){return n+" Shapes "+t+" and "+e+" must match"}))}function R(t){C(null!=t,(function(){return"The input to the tensor constructor must be a non-null value."}))}function I(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||V(t)&&!n)for(var r=0;r<t.length;++r)I(t[r],e,n);else e.push(t);return e}function k(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function S(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function A(t){return t%1==0}function D(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function T(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function N(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function F(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise((function(r,o){var a=0,i=function(){if(t())r();else{a++;var s=e(a);null!=n&&a>=n?o():setTimeout(i,s)}};i()}))}function _(t,e){for(var n=1,r=-1,o=0;o<t.length;++o)if(t[o]>=0)n*=t[o];else if(-1===t[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o}else if(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);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 a=t.slice();return a[r]=e/n,a}function O(t,e){var n=e.length;return C((t=null==t?e.map((function(t,e){return e})):[].concat(t)).every((function(t){return t>=-n&&t<n})),(function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t})),C(t.every((function(t){return A(t)})),(function(){return"All values in axis param must be integers but got axis "+t})),t.map((function(t){return t<0?n+t:t}))}function M(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,a=null==e||o?null:O(e,t).sort(),i=0,s=0;s<t.length;++s){if(null!=a){if(a[i]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==a[i]||a[i]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[i]<=s&&i++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function B(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 P(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 L(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function W(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function U(t,e){return"complex64"!==e&&(("float32"!==e||"complex64"===t)&&(("int32"!==e||"float32"===t||"complex64"===t)&&("bool"!==e||"bool"!==t)))}function V(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function z(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function G(t){if(null==t)return 0;var e=0;return t.forEach((function(t){return e+=t.length})),e}function H(t){return"string"==typeof t||t instanceof String}function q(t){return"boolean"==typeof t}function K(t){return"number"==typeof t}function j(t){return Array.isArray(t)?j(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":K(t)?"float32":H(t)?"string":q(t)?"bool":"float32"}function X(t){return!!(t&&t.constructor&&t.call&&t.apply)}function Y(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function $(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}function Q(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=I(t)),n&&L(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),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+e)}function J(t,e){if(0===t.length)return e[0];var n=t.reduce((function(t,e){return t*e}));if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var o=new Array;if(1===n.length)for(var a=n[0],i=0;i<a;i++)o[i]=r[e+i];else{a=n[0];var s=n.slice(1),u=s.reduce((function(t,e){return t*e}));for(i=0;i<a;i++)o[i]=t(e+i*u,s,r)}return o}(0,t,e)}function Z(t,e){for(var n=tt(t,e),r=0;r<n.length;r++)n[r]=1;return n}function tt(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function et(){return i().platform.now()}function nt(t){t.forEach((function(e){C(Number.isInteger(e)&&e>=0,(function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."}))}))}function rt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",i().platform.encode(t,e)}function ot(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",i().platform.decode(t,e)}function at(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var r=t[t.length-1],o=0;o<t.length-1;++o)r+=n[o]*t[o];return r}function it(t,e,n){if(0===e)return[];if(1===e)return[t];for(var r=new Array(e),o=0;o<r.length-1;++o)r[o]=Math.floor(t/n[o]),t-=r[o]*n[o];return r[r.length-1]=t,r}var st=Object.freeze({shuffle:y,clamp:x,nearestLargerEven:b,sum:w,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<t.length;r++){var o=Number(t[r])-Number(e[r]);n+=o*o}return n},assert:C,assertShapesMatch:E,assertNonNull:R,flatten:I,sizeFromShape:k,isScalarShape:function(t){return 0===t.length},arraysEqual:S,isInt:A,tanh:D,sizeToSquarishShape:T,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return y(e),e},rightPad:N,repeatedTry:F,inferFromImplicitShape:_,parseAxisParam:O,squeezeShape:M,getTypedArrayFromDType:B,getArrayFromDType:P,checkConversionForErrors:L,isValidDtype:W,hasEncodingLoss:U,isTypedArray:V,bytesPerElement:z,bytesFromStringArray:G,isString:H,isBoolean:q,isNumber:K,inferDtype:j,isFunction:X,nearestDivisor:Y,computeStrides:$,toTypedArray:Q,toNestedArray:J,makeOnesTypedArray:Z,makeZerosTypedArray:tt,now:et,assertNonNegativeIntegerDimensions:nt,fetch:function(t,e){return i().platform.fetch(t,e)},encodeString:rt,decodeString:ot,locToIndex:at,indexToLoc:it}),ut=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new ct)}return t.prototype.profileKernel=function(t,e,n){var r,o=this,a=this.backendTimer.time((function(){r=n()}));return r.forEach((function(n){n.data().then((function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var o=t[r];if(isNaN(o)||!isFinite(o))return console.warn("Found "+o+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),a.then((function(a){var i="";null!=a.getExtraProfileInfo&&(i=a.getExtraProfileInfo()),o.logger.logKernelProfile(t,n,r,a.kernelMs,e,i)}))}))})),r},t}();var ct=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o,a){var i="number"==typeof r?N(r+"ms",9):r.error,s=N(t,25),u=e.rank,c=e.size,l=N(e.shape.toString(),14),h="";for(var f in o){var d=o[f].shape||e.shape,p=d.length;h+=f+": "+p+"D "+(p>0?d:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+h+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}();var lt=20,ht=3,ft=7;function dt(t,e,n,r){var o=$(e),a=function(t,e,n,r){var o=k(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?mt(t):t;if(s>1)for(var c=0;c<o/a;c++)for(var l=c*a,h=0;h<a;h++)i[h]=Math.max(i[h],pt(u[l+h],0,n).length);return i}(t,e,n,o),i=e.length,s=function t(e,n,r,o,a,i){void 0===i&&(i=!0);var s="complex64"===r?2:1,u=n[0],c=n.length;if(0===c){return"complex64"===r?[pt(mt(e)[0],0,r)]:"bool"===r?[vt(e[0])]:[e[0].toString()]}if(1===c){if(u>lt){var l=ht*s,h=Array.from(e.slice(0,l)),f=Array.from(e.slice((u-ht)*s,u*s));return"complex64"===r&&(h=mt(h),f=mt(f)),["["+h.map((function(t,e){return pt(t,a[e],r)})).join(", ")+", ..., "+f.map((function(t,e){return pt(t,a[u-ht+e],r)})).join(", ")+"]"]}return["["+("complex64"===r?mt(e):Array.from(e)).map((function(t,e){return pt(t,a[e],r)})).join(", ")+"]"]}var d=n.slice(1),p=o.slice(1),v=o[0]*s,m=[];if(u>lt){for(var g=0;g<ht;g++){var y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),d,r,p,a,!1))}m.push("...");for(g=u-ht;g<u;g++){y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),d,r,p,a,g===u-1))}}else for(g=0;g<u;g++){var x;y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),d,r,p,a,g===u-1))}var b=2===c?",":"";m[0]="["+m[0]+b;for(g=1;g<m.length-1;g++)m[g]=" "+m[g]+b;var w=",\n";for(g=2;g<c;g++)w+="\n";return m[m.length-1]=" "+m[m.length-1]+"]"+(i?"":w),m}(t,e,n,o,a),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+i),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map((function(t){return" "+t})).join("\n")),u.join("\n")}function pt(t,e,n){return N(Array.isArray(t)?parseFloat(t[0].toFixed(ft))+" + "+parseFloat(t[1].toFixed(ft))+"j":H(t)?"'"+t+"'":"bool"===n?vt(t):parseFloat(t.toFixed(ft)).toString(),e)}function vt(t){return 0===t?"false":"true"}function mt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var gt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=k(t),null!=n){var o=n.length;C(o===this.size,(function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+r.size+"'."}))}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||P(e,this.size),this.strides=$(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),C(n.length===this.rank,(function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"}));var o=this.locToIndex(n);this.values[o]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,o=t;r<o.length;r++){var a=o[r];if(a<0||a>=this.shape[n]){var i="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(i)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return yt().makeTensor(this.values,this.shape,this.dtype)},t}(),yt=null,xt=null,bt=null;var wt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=k(t),this.strides=$(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),C(1===this.size,(function(){return"The array must have only 1 element."})),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,o){return this.throwIfDisposed(),this.reshape([t,e,n,r,o])},t.prototype.asType=function(t){return this.throwIfDisposed(),xt.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return n(this,void 0,void 0,(function(){var t;return r(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,xt.buffer(this.shape,this.dtype,t)]}}))}))},t.prototype.bufferSync=function(){return xt.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return n(this,void 0,void 0,(function(){var t;return r(this,(function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,J(this.shape,t)]}}))}))},t.prototype.arraySync=function(){return J(this.shape,this.dataSync())},t.prototype.data=function(){return n(this,void 0,void 0,(function(){var t,e;return r(this,(function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=yt().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map((function(t){return ot(t)}))]}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}n.label=2;case 2:return[2,t]}}))}))},t.prototype.dataSync=function(){this.throwIfDisposed();var t=yt().readSync(this.dataId);if("string"===this.dtype)try{return t.map((function(t){return ot(t)}))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},t.prototype.bytes=function(){return n(this,void 0,void 0,(function(){var t;return r(this,(function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,yt().read(this.dataId)];case 1:return t=e.sent(),"string"===this.dtype?[2,t]:[2,new Uint8Array(t.buffer)]}}))}))},t.prototype.dispose=function(){this.isDisposed||(yt().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),xt.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),xt.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),xt.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),xt.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),xt.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),xt.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),xt.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),dt(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),xt.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),xt.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),xt.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),xt.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),xt.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),xt.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),xt.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),xt.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),xt.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),xt.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),xt.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),xt.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),bt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,o,r,n)},t.prototype.batchNorm=function(t,e,n,r,o){return void 0===o&&(o=.001),this.throwIfDisposed(),xt.batchNorm(this,t,e,n,r,o)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),xt.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),xt.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),xt.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),xt.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),xt.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),xt.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),xt.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),xt.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),xt.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),xt.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),xt.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),xt.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),xt.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),xt.div(this,t)},t.prototype.divNoNan=function(t){return this.throwIfDisposed(),xt.divNoNan(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),xt.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),xt.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),xt.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),xt.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),xt.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),xt.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),xt.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),xt.modStrict(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),xt.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),xt.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),xt.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),xt.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),xt.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),xt.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),xt.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),xt.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),xt.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),xt.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),xt.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),xt.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),xt.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),xt.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),xt.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),xt.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),xt.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),xt.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),xt.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),xt.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),xt.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),xt.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),xt.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),xt.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),xt.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),xt.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),xt.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),xt.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),xt.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),xt.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),xt.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),xt.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),xt.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),xt.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),xt.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),xt.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),xt.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),xt.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),xt.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),xt.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),xt.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),xt.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),xt.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),xt.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),xt.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),xt.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),xt.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),xt.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),xt.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),xt.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),xt.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),xt.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),xt.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),xt.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),xt.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),xt.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),xt.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),xt.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),xt.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),xt.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),xt.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),xt.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),xt.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),xt.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),xt.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),xt.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,o,a){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),xt.conv1d(this,t,e,n,r,o,a)},t.prototype.conv2d=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),xt.conv2d(this,t,e,n,r,o,a)},t.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),xt.conv2dTranspose(this,t,e,n,r,o)},t.prototype.depthwiseConv2D=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),xt.depthwiseConv2d(this,t,e,n,r,o,a)},t.prototype.separableConv2d=function(t,e,n,r,o,a){return void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC"),this.throwIfDisposed(),xt.separableConv2d(this,t,e,n,r,o,a)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),xt.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),xt.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),xt.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),xt.pool(this,t,e,n,r,o)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),yt().makeVariable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),xt.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),xt.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),xt.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),xt.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),xt.stridedSlice(this,t,e,n,r,o,a,i,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),xt.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),xt.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),xt.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),xt.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),xt.spectral.irfft(this)},t}();Object.defineProperty(wt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var Ct,Et,Rt,It,kt,St=function(t){function n(e,n,r,o){var a=t.call(this,e.shape,e.dtype,e.dataId,o)||this;return a.trainable=n,a.name=r,a}return e(n,t),n.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!S(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");yt().disposeTensor(this),this.dataId=t.dataId,yt().incRef(this,null)},n.prototype.dispose=function(){yt().disposeVariable(this),this.isDisposedInternal=!0},n}(wt);Object.defineProperty(St,Symbol.hasInstance,{value:function(t){return t instanceof wt&&null!=t.assign&&t.assign instanceof Function}}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(Ct||(Ct={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(Et||(Et={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(Rt||(Rt={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(It||(It={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(kt||(kt={}));var At={float32:It,int32:Et,bool:Rt,complex64:kt};function Dt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return At[t][e]}function Tt(t){return Dt(t,"int32")}function Nt(t,e){if(t.dtype===e.dtype)return[t,e];var n=Dt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Ft(t,e){C(t.dtype===e.dtype,(function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"}))}function _t(t){var e=[];return function t(e,n,r){if(null==e)return;if(e instanceof wt)return void n.push(e);if(o=e,!Array.isArray(o)&&"object"!=typeof o)return;var o;var a=e;for(var i in a){var s=a[i];r.has(s)||(r.add(s),t(s,n,r))}}(t,e,new Set),e}var Ot,Mt=Object.freeze({makeTypesMatch:Nt,assertTypesMatch:Ft,isTensorInList:function(t,e){return e.some((function(e){return e.id===t.id}))},getTensorsInContainer:_t}),Bt=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},t}(),Pt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Bt}return t.prototype.ready=function(){return n(this,void 0,void 0,(function(){var t,e,n;return r(this,(function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then((function(){}))];if(null!=this.backendInstance)return[2];t=this.getSortedBackends(),e=0,r.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}}))}))},Object.defineProperty(t.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");if(null==this.backendInstance){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods");this.setBackend(e)}return this.backendInstance},enumerable:!0,configurable:!0}),t.prototype.backendNames=function(){return Object.keys(this.registryFactory)},t.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null}return this.registry[t]},t.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},t.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0)},t.prototype.setBackend=function(t){return n(this,void 0,void 0,(function(){var e,n,o;return r(this,(function(r){switch(r.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return o=r.sent(),[3,3];case 2:o=n,r.label=3;case 3:if(!o)return[2,!1];r.label=4;case 4:return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new ut(this.backendInstance),[2,!0]}}))}))},t.prototype.setupRegisteredKernels=function(){var t=this;f(this.backendName).forEach((function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)}))},t.prototype.disposeRegisteredKernels=function(t){var e=this;f(t).forEach((function(n){null!=n.disposeFunc&&n.disposeFunc(e.registry[t])}))},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var o=++this.pendingBackendInitId,a=r.then((function(n){return!(o<e.pendingBackendInitId)&&(e.registry[t]=n,e.pendingBackendInit=null,!0)})).catch((function(n){return!(o<e.pendingBackendInitId)&&(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),!1)}));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}return this.registry[t]=r,{success:!0,asyncInit:!1}}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1}}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority}))},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),o=r.success,a=r.asyncInit;if(a||o)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")},t.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),r=n.backend,o=this.readSync(e);r.disposeData(e),n.backend=t,t.move(e,o,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},t.prototype.tidy=function(t,e){var n,r=this,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t}return this.scopedRun((function(){return r.startScope(o)}),(function(){return r.endScope(n)}),(function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n}))},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.clone=function(t){var e=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],(function(t){return{x:function(){return t.toFloat()}}}),[]),e},t.prototype.runKernel=function(t,e,n,r,o){return this.runKernelFunc(null,e,null,t,n,r,o)},t.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},t.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),o=0;n.forEach((function(t){o+="complex64"===t.dtype?3:1}));var a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-e-o-a;if(i>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+i+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,o,a,i){var s,u=this;void 0===a&&(a=[]),void 0===i&&(i=[]);var c=[],h=this.isTapeOn();null==r&&(r=null!=this.state.activeScope?this.state.activeScope.name:"");var f,d=function(t){h&&(c=t.map((function(t){return u.keep(u.clone(t))})))},p=this.state.numBytes,v=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var m,g=l(r,this.backendName);return f=null!=g?function(){var t=u.backend.numDataIds();m=g.kernelFunc({inputs:e,attrs:o,backend:u.backend});var n=Array.isArray(m)?m:[m];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,t,n);var s=n.map((function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)})),c=s.filter((function(t,e){return i[e]}));return d((a||[]).slice().concat(c)),s}:function(){var e=u.backend.numDataIds();m=u.tidy((function(){return t(u.backend,d)}));var n=Array.isArray(m)?m:[m];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(r,e,n),n},this.scopedRun((function(){return u.state.kernelDepth++}),(function(){return u.state.kernelDepth--}),(function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(r,e,(function(){return f()})):f()})),h&&this.addTapeNode(r,e,s,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-v,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map((function(t){return e[t].shape})),outputShapes:s.map((function(t){return t.shape}))}),Array.isArray(m)?s:s[0]},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var o=t;"string"===n&&H(t[0])&&(o=t.map((function(t){return rt(t)})));var a=r.write(o,e,n),i=new wt(e,n,a,this.nextTensorId());if(this.incRef(i,r),"string"===n){var s=this.state.tensorInfo.get(a),u=G(o);this.state.numBytes+=u-s.bytes,s.bytes=u}return i},t.prototype.makeTensorFromDataId=function(t,e,n,r){var o=new wt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(o,r),o},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var o=new St(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[o.name])throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*z(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof St||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(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 n(this,void 0,void 0,(function(){var e,n;return r(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,r,o){var a=this,i={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:o},s=h(t);null!=s&&(r=s.gradFunc),null!=r&&(i.gradient=function(t){return t=t.map((function(t,e){if(null==t){var r=n[e],o=tt(r.size,r.dtype);return a.makeTensor(o,r.shape,r.dtype)}return t})),r(t.length>1?t:t[0],o)}),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=_t(t),r=new Set(n.map((function(t){return t.id}))),o=0;o<this.state.activeScope.track.length;o++){var a=this.state.activeScope.track[o];a.kept||r.has(a.id)||a.dispose()}var i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach((function(t){t.kept||t.scopeId!==i.id||e.track(t)}))},t.prototype.gradients=function(t,e,n,r){var o=this;if(void 0===r&&(r=!1),C(e.length>0,(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 a=this.scopedRun((function(){return o.startTape()}),(function(){return o.endTape()}),(function(){return o.tidy("forward",t)}));C(a instanceof wt,(function(){return"The result y returned by f() must be a tensor."}));var i=function(t,e,n){for(var r={},o={},a=0;a<e.length;a++)r[e[a].id]=!0;for(a=0;a<t.length;a++){var i=(p=t[a]).inputs;for(var s in i){for(var u=i[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){p.outputs.forEach((function(t){return r[t.id]=!0})),c=!0,o[p.id]=!0;break}if(c)break}}var h={};h[n.id]=!0;var f={};for(a=t.length-1;a>=0;a--)for(i=(p=t[a]).inputs,l=0;l<p.outputs.length;l++)if(h[p.outputs[l].id]){for(var s in i)h[i[s].id]=!0,f[p.id]=!0;break}var d=[];for(a=0;a<t.length;a++){var p;if(o[(p=t[a]).id]&&f[p.id]){var v={};for(var s in p.inputs){var m=p.inputs[s];r[m.id]&&(v[s]=m)}var g=Object.assign({},p);g.inputs=v,g.outputs=p.outputs,d.push(g)}}return d}(this.state.activeTape,e,a);if(!r&&0===i.length&&e.length>0)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[a.id]=null==n?(t=a.shape,r=Z(k(t),"float32"),Lt.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach((function(e){var n=t[e.id];null!=n?a.push(n):a.push(null)})),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.kernelName+".");var i=o.gradient(a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n((function(){return i[e]()}));if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!S(r.shape,a.shape))throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,i,(function(t){return o.tidy(t)}));var u=e.map((function(t){return s[t.id]}));return 0===o.state.gradientDepth&&(o.state.activeTape.forEach((function(t){for(var e=0,n=t.saved;e<n.length;e++){n[e].dispose()}})),o.state.activeTape=null),{value:a,grads:u}}))},t.prototype.customGrad=function(t){var e=this;return C(X(t),(function(){return"The f passed in customGrad(f) must be a function."})),function(){for(var n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];C(r.every((function(t){return t instanceof wt})),(function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}));var a={};return r.forEach((function(t,e){a[e]=t})),e.runKernelFunc((function(e,o){return C((n=t.apply(void 0,r.concat([o]))).value instanceof wt,(function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"})),C(X(n.gradFunc),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."})),n.value}),a,(function(t,e){var o=n.gradFunc(t,e),a=Array.isArray(o)?o:[o];C(a.length===r.length,(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."})),C(a.every((function(t){return t instanceof wt})),(function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}));var i={};return a.forEach((function(t,e){i[e]=function(){return t}})),i}))}},t.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t)},t.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t)},t.prototype.time=function(t){return n(this,void 0,void 0,(function(){var e,n;return r(this,(function(r){switch(r.label){case 0:return e=et(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=et()-e,[2,n]}}))}))},t.prototype.track=function(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t},Object.defineProperty(t.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),t.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Bt,this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},t.nextTensorId=0,t.nextVariableId=0,t}();var Lt=function(){var t=function(){if(null==Ot){var t=void 0;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else if("undefined"!=typeof process)t=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self}Ot=t}return Ot}();if(null==t._tfengine){var e=new o(t);t._tfengine=new Pt(e)}return function(t){s=t}(t._tfengine.ENV),yt=function(){return t._tfengine},t._tfengine}();function Wt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Ut=i();Ut.registerFlag("DEBUG",(function(){return!1}),(function(t){t&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),Ut.registerFlag("IS_BROWSER",(function(){return Wt()})),Ut.registerFlag("IS_NODE",(function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node})),Ut.registerFlag("IS_CHROME",(function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)})),Ut.registerFlag("PROD",(function(){return!1})),Ut.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(function(){return Ut.getBool("DEBUG")})),Ut.registerFlag("DEPRECATION_WARNINGS_ENABLED",(function(){return!0})),Ut.registerFlag("IS_TEST",(function(){return!1}));var Vt,zt,Gt,Ht={},qt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Kt(t,e){Ht[t]=e}function jt(t){t in Ht||(Ht[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=function(t){if("undefined"!=typeof OffscreenCanvas&&2===t)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(t);if(e.addEventListener("webglcontextlost",(function(e){e.preventDefault(),delete Ht[t]}),!1),1===t)return e.getContext("webgl",qt)||e.getContext("experimental-webgl",qt);return e.getContext("webgl2",qt)}(t));var e=Ht[t];return e.isContextLost()?(delete Ht[t],jt(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Ht[t])}function Xt(t,e){return[e,t]}function Yt(t){var e=k(t);return T(Math.ceil(e/4))}function $t(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Qt(t,e){var n,r,o,a,s,u,c,l,h,f=t;return 2===i().getNumber("WEBGL_VERSION")?(n=f.R32F,r=f.R16F,o=f.RGBA16F,a=f.RGBA32F,s=f.RED,u=4,c=1,l=f.HALF_FLOAT,h=f.FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,a=f.RGBA,s=t.RGBA,u=4,c=4,l=null!=e?e.HALF_FLOAT_OES:null,h=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:s,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:l,textureTypeFloat:h}}function Jt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+ne(t,e))}(t),r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(Vt||(Vt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(zt||(zt={})),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"}(Gt||(Gt={}));var Zt=5.96e-8,te=65504;function ee(t){return!!(i().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Zt<Math.abs(t)&&Math.abs(t)<te)}function ne(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e}}function re(t,e,n){return ke(t,e,(function(){return t.getExtension(n)}),'Extension "'+n+'" not supported on this browser.')}function oe(t,e,n){var r=ke(t,e,(function(){return t.createShader(t.VERTEX_SHADER)}),"Unable to create vertex WebGLShader.");if(Jt(t,e,(function(){return t.shaderSource(r,n)})),Jt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function ae(t,e,n){var r=ke(t,e,(function(){return t.createShader(t.FRAGMENT_SHADER)}),"Unable to create fragment WebGLShader.");if(Jt(t,e,(function(){return t.shaderSource(r,n)})),Jt(t,e,(function(){return t.compileShader(r)})),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=ue.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],o=t.split("\n"),a=o.length.toString().length+2,i=o.map((function(t,e){return N((e+1).toString(),a)+t})),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var c=i.slice(0,r-1),l=i.slice(r-1,r),h=i.slice(r);console.log(c.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+N(l[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join("\n"))}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var ie,se,ue=/ERROR: [0-9]+:([0-9]+):/g;function ce(t,e){return ke(t,e,(function(){return t.createProgram()}),"Unable to create WebGLProgram.")}function le(t,e,n){if(Jt(t,e,(function(){return t.linkProgram(n)})),!1===t.getProgramParameter(n,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.")}function he(t,e,n){if(Jt(t,e,(function(){return t.validateProgram(n)})),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function fe(t,e,n){var r=ke(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),Jt(t,e,(function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function de(t,e,n){var r=ke(t,e,(function(){return t.createBuffer()}),"Unable to create WebGLBuffer");return Jt(t,e,(function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)})),Jt(t,e,(function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)})),r}function pe(t,e){return ke(t,e,(function(){return t.createTexture()}),"Unable to create WebGLTexture.")}function ve(t,e){var n=i().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n){r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+("["+n+"x"+n+"]")+".")}}function me(t,e){return ke(t,e,(function(){return t.createFramebuffer()}),"Unable to create WebGLFramebuffer.")}function ge(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,o)})),Jt(t,e,(function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)})),Jt(t,e,(function(){return t.enableVertexAttribArray(u)})),!0)}function ye(t,e,n,r){Se(t,r),Jt(t,e,(function(){return t.activeTexture(t.TEXTURE0+r)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)}))}function xe(t,e,n,r){return ke(t,e,(function(){return t.getUniformLocation(n,r)}),'uniform "'+r+'" not present in program.')}function be(t,e,n){return t.getUniformLocation(e,n)}function we(t,e,n,r,o,a){Jt(t,e,(function(){return ye(t,e,r,a)})),Jt(t,e,(function(){return t.uniform1i(o,a)}))}function Ce(t,e,n,r){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)})),Jt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}))}function Ee(t,e,n){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)})),Jt(t,e,(function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)}))}function Re(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ie(t,e))}function Ie(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 ke(t,e,n,r){var o=Jt(t,e,(function(){return n()}));if(null==o)throw new Error(r);return o}function Se(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+n+"]")+".")}function Ae(t,e){return void 0===e&&(e=2),k(t.slice(0,t.length-e))}function De(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 Te(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ae(t)].concat(De(t))),e}function Ne(t,e){var n;void 0===e&&(e=!1);var r=i().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 o=M(t);t=o.newShape}var a=k(t);if(t.length<=1&&a<=r)return[1,a];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 s=Ae(t),u=2,c=2;return t.length&&(u=(n=De(t))[0],c=n[1]),T(a=s*(u/2)*(c/2)).map((function(t){return 2*t}))}return T(a)}function Fe(t){return t%2==0}function _e(t,e){if(S(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(Fe(n)&&Fe(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Fe(t[0])&&Fe(e[0])}function Oe(t){if(null==ie){var e=jt(t);ie=e.getParameter(e.MAX_TEXTURE_SIZE)}return ie}function Me(t){if(null==se){var e=jt(t);se=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,se)}function Be(t){if(0===t)return 0;var e=jt(t);return Pe(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Pe(e,"EXT_disjoint_timer_query")?1:0}function Pe(t,e){return null!=t.getExtension(e)}function Le(t){try{if(null!=jt(t))return!0}catch(t){return!1}return!1}function We(t){if(0===t)return!1;var e=jt(t);if(1===t){if(!Pe(e,"OES_texture_float"))return!1}else if(!Pe(e,"EXT_color_buffer_float"))return!1;return Ve(e)}function Ue(t){if(0===t)return!1;var e=jt(t);if(1!==t){if(Pe(e,"EXT_color_buffer_float"))return Ve(e);if(Pe(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Qt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var o=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,o),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(o),a}(e,n)}return!1}return!!Pe(e,"OES_texture_float")&&(!!Pe(e,"WEBGL_color_buffer_float")&&Ve(e))}function Ve(t){var e=Qt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n);t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),o}function ze(t){return 2===t&&null!=jt(t).fenceSync}var Ge=Object.freeze({callAndCheck:Jt,canBeRepresented:ee,getWebGLErrorMessage:ne,getExtensionOrThrow:re,createVertexShader:oe,createFragmentShader:ae,createProgram:ce,linkProgram:le,validateProgram:he,createStaticVertexBuffer:fe,createStaticIndexBuffer:de,getNumChannels:function(){return 2===i().getNumber("WEBGL_VERSION")?1:4},createTexture:pe,validateTextureSize:ve,createFramebuffer:me,bindVertexBufferToProgramAttribute:ge,bindTextureUnit:ye,unbindTextureUnit:function(t,e,n){Se(t,n),Jt(t,e,(function(){return t.activeTexture(t.TEXTURE0+n)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))},getProgramUniformLocationOrThrow:xe,getProgramUniformLocation:be,bindTextureToProgramUniformSampler:we,bindCanvasToFramebuffer:function(t,e){Jt(t,e,(function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)})),Jt(t,e,(function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)})),Jt(t,e,(function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)}))},bindColorTextureToFramebuffer:Ce,unbindColorTextureFromFramebuffer:Ee,validateFramebuffer:Re,getFramebufferErrorMessage:Ie,getBatchDim:Ae,getRowsCols:De,getShapeAs3D:Te,getTextureShapeFromLogicalShape:Ne,isReshapeFree:_e,getWebGLMaxTextureSize:Oe,resetMaxTextureSize:function(){ie=null},resetMaxTexturesInShader:function(){se=null},getMaxTexturesInShader:Me,getWebGLDisjointQueryTimerVersion:Be,hasExtension:Pe,isWebGLVersionEnabled:Le,isCapableOfRenderingToFloatTexture:We,isDownloadFloatTextureEnabled:Ue,isWebGLFenceEnabled:ze}),He=i();function qe(){i().set("PROD",!0)}function Ke(){i().set("DEBUG",!0)}function je(){i().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Xe(t){i().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ye(){Lt.disposeVariables()}function $e(){return Lt}function Qe(){return Lt.memory()}function Je(t){return Lt.profile(t)}function Ze(t,e){return Lt.tidy(t,e)}function tn(t){_t(t).forEach((function(t){return t.dispose()}))}function en(t){return Lt.keep(t)}function nn(t){return Lt.time(t)}function rn(t){return Lt.setBackend(t)}function on(){return Lt.ready()}function an(){return Lt.backendName}function sn(t){Lt.removeBackend(t)}function un(t){return Lt.findBackend(t)}function cn(t){return Lt.findBackendFactory(t)}function ln(t,e,n){return void 0===n&&(n=1),Lt.registerBackend(t,e,n)}function hn(){return Lt.backend}function fn(t,e){i().setPlatform(t,e)}function dn(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];i().getBool("IS_TEST")||console.warn.apply(console,t)}function pn(t,e){var n=t;if(V(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||V(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&i().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],!Array.isArray(e)&&!V(e))return void C(0===n.length,(function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"}));C(n.length>0,(function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"})),C(e.length===n[0],(function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"}));for(var o=n.slice(1),a=0;a<e.length;++a)t(e[a],o,r.concat(a))}(t,r,[]),r}function vn(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function mn(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof wt)return vn(r,t.dtype,e,n),t;var o=j(t);if("string"!==o&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),vn(r,o,e,n),null==t||!V(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var a=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+a+"'")}var s=pn(t,o);V(t)||Array.isArray(t)||(t=[t]);var u="string"!==o?Q(t,o,i().getBool("DEBUG")):I(t,[],!0);return Lt.makeTensor(u,s,o)}function gn(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 mn(t,e+"["+r+"]",n)}),r)}function yn(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function xn(t,e,n){for(var r=t.length+e.length,o=[],a=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(t[a++]):o.push(e[i++]);return o}function bn(t,e){for(var n=[],r=t.length,o=0;o<r;o++)-1===e.indexOf(o)&&n.push(t[o]);return[n,e.map((function(e){return t[e]}))]}function wn(t,e){return xn(t,e.map((function(t){return 1})),e)}function Cn(t,e,n){C(yn(e,n),(function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."}))}function En(t,e){if(yn(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach((function(t){return n.push(t)})),n}function Rn(t){return t.map((function(t,e){return[e,t]})).sort((function(t,e){return t[1]-e[1]})).map((function(t){return t[0]}))}function In(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function kn(t,e){var n=t[0].length;t.forEach((function(t,e){C(t.length===n,(function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"}))})),C(e>=0&&e<n,(function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."}));var r=t[0];t.forEach((function(t,o){for(var a=0;a<n;a++)C(a===e||t[a]===r[a],(function(){return"Error in concat"+n+"D: Shape of tensors["+o+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+o+"."}))}))}function Sn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function An(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var o=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Lt.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Lt.endScope(o),o}catch(t){throw Lt.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}He.registerFlag("HAS_WEBGL",(function(){return He.getNumber("WEBGL_VERSION")>0})),He.registerFlag("WEBGL_VERSION",(function(){return Le(2)?2:Le(1)?1:0})),He.registerFlag("WEBGL_BUFFER_SUPPORTED",(function(){return 2===He.get("WEBGL_VERSION")})),He.registerFlag("WEBGL_CPU_FORWARD",(function(){return!0})),He.registerFlag("WEBGL_FORCE_F16_TEXTURES",(function(){return!1})),He.registerFlag("WEBGL_PACK",(function(){return He.getBool("HAS_WEBGL")})),He.registerFlag("WEBGL_PACK_NORMALIZATION",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_CLIP",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_DEPTHWISECONV",(function(){return!1})),He.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_PACK_REDUCE",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_LAZILY_UNPACK",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_CONV_IM2COL",(function(){return He.getBool("WEBGL_PACK")})),He.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(function(){return Oe(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(function(){return Me(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(function(){var t=He.getNumber("WEBGL_VERSION");return 0===t?0:Be(t)})),He.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(function(){return He.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})),He.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(function(){return We(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(function(){return!He.getBool("WEBGL_FORCE_F16_TEXTURES")&&He.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")})),He.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(function(){return Ue(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_FENCE_API_ENABLED",(function(){return ze(He.getNumber("WEBGL_VERSION"))})),He.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(function(){return He.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0})),bt=Xe;var Dn=An({complex_:function(t,e){var n=mn(t,"real","complex"),r=mn(e,"imag","complex");return E(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Lt.runKernelFunc((function(t){return t.complex(n,r)}),{$real:n,$imag:r})}}),Tn=An({real_:function(t){var e=mn(t,"input","real");return Lt.runKernelFunc((function(t){return t.real(e)}),{$input:e})}}),Nn=An({imag_:function(t){var e=mn(t,"input","imag");return Lt.runKernelFunc((function(t){return t.imag(e)}),{$input:e})}});function Fn(t,e,n){return _n(t,e,pn(t,n),n)}function _n(t,e,n,r){if(null==r&&(r=j(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!V(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){nt(e);var o=k(e),a=k(n);C(o===a,(function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+a}));for(var s=0;s<n.length;++s){var u=n[s],c=s!==n.length-1||u!==k(e.slice(s));C(n[s]===e[s]||!c,(function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "}))}}return V(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?Q(t,r,i().getBool("DEBUG")):I(t,[],!0),Lt.makeTensor(t,e,r)}function On(t,e){if((V(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&V(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return _n(t,[],[],e)}function Mn(t,e){R(t);var n=pn(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return _n(t,null,n,e)}function Bn(t,e,n){if(R(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=pn(t,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return _n(t,e,r,n)}function Pn(t,e,n){if(R(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=pn(t,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return _n(t,e,r,n)}function Ln(t,e,n){if(R(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=pn(t,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return _n(t,e,r,n)}function Wn(t,e,n){if(R(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=pn(t,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return _n(t,e,r,n)}function Un(t,e,n){if(R(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=pn(t,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return _n(t,e=e||r,r,n)}function Vn(t,e,n,r){return void 0===e&&(e=!0),Lt.makeVariable(t,e,n,r)}function zn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=zn(t,"float32"),r=Gn(t,"float32");return Dn(n,r)}var o=Z(k(t),e);return Lt.makeTensor(o,t,e)}function Gn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Gn(t,"float32"),r=Gn(t,"float32");return Dn(n,r)}var o=tt(k(t),e);return Lt.makeTensor(o,t,e)}function Hn(t,e,n){return Lt.runKernelFunc((function(r){return r.fill(t,e,n)}),{})}function qn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Lt.runKernelFunc((function(r){return r.linspace(t,e,n)}),{})}function Kn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return Gn([0],r);var o=tt(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+n;return Mn(o,r)}var jn=An({onesLike_:function(t){var e=mn(t,"x","onesLike");if("complex64"===e.dtype){var n=jn(Tn(e)),r=Xn(Nn(e));return Dn(n,r)}return Lt.runKernelFunc((function(t){return t.onesLike(e)}),{$x:e},(function(t,e){return{$x:function(){return Xn(t)}}}))}}),Xn=An({zerosLike_:function(t){var e=mn(t,"x","zerosLike");return Lt.runKernelFunc((function(t){return t.zerosLike(e)}),{$x:e},(function(t,e){return{$x:function(){return Xn(t)}}}))}});var Yn=An({concat_:function(t,e){void 0===e&&(e=0),C(t.length>=1,(function(){return"Pass at least one tensor to concat"}));var n=gn(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach((function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")})),e=O(e,n[0].shape)[0];var r=Sn(n.map((function(t){return t.shape})),e);if(0===k(r))return Fn([],r);if(1===(n=n.filter((function(t){return t.size>0}))).length)return n[0];var o=n.map((function(t){return t.shape}));kn(o,e);var a=n,i={axis:e};return Lt.runKernelFunc((function(t){return t.concat(n,e)}),a,(function(t){var n=o.map((function(t){return t[e]}));return tr(t,n,e).map((function(t){return function(){return t}}))}),"Concat",i)}}),$n=An({concat1d_:function(t){return Yn(t,0)}}),Qn=An({concat2d_:function(t,e){return Yn(t,e)}}),Jn=An({concat3d_:function(t,e){return Yn(t,e)}}),Zn=An({concat4d_:function(t,e){return Yn(t,e)}}),tr=An({split_:function(t,e,n){void 0===n&&(n=0);var r,o=mn(t,"x","split");return n=O(n,o.shape)[0],"number"==typeof e?(C(o.shape[n]%e==0,(function(){return"Number of splits must evenly divide the axis."})),r=new Array(e).fill(o.shape[n]/e)):(C(o.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),Lt.runKernelFunc((function(t){return t.split(o,r,n)}),{$x:o},(function(t){return{$x:function(){return Yn(t,n)}}}))}});"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function er(t,e){return t(e={exports:{}},e.exports),e.exports}var nr=er((function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>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}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.alea=a}(0,t,!1)})),rr=er((function(t){!function(t,e,n){function r(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<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xor128=a}(0,t,!1)})),or=er((function(t){!function(t,e,n){function r(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<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}function o(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 a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xorwow=a}(0,t,!1)})),ar=er((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xorshift7=a}(0,t,!1)})),ir=er((function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=i,t.X=s,t.i=o}(e,t)}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.xor4096=a}(0,t,!1)})),sr=er((function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-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<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n((function(){return a})):this.tychei=a}(0,t,!1)})),ur=er((function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),c=n.pow(2,52),l=2*c,h=a-1;function f(t,h,f){var g=[],y=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==a?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date,o,i,o.screen,m(e)]}}():t,3),g),x=new d(g),b=function(){for(var t=x.g(i),e=u,n=0;t<c;)t=(t+n)*a,e*=a,n=x.g(1);for(;t>=l;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,v(m(x.S),e),(h.pass||f||function(t,e,r,o){return o&&(o.S&&p(o,x),t.state=function(){return p(x,{})}),r?(n[s]=t,e):t})(b,y,"global"in h?h.global:this==n,h.state)}function d(t){var e,n=t.length,r=this,o=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o<a;)s[o]=o++;for(o=0;o<a;o++)s[o]=s[i=h&i+t[o%n]+(e=s[o])],s[i]=e;(r.g=function(t){for(var e,n=0,o=r.i,i=r.j,s=r.S;t--;)e=s[o=h&o+1],n=n*a+s[h&(s[o]=s[i=h&i+e])+(s[i]=e)];return r.i=o,r.j=i,n})(a)}function p(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function v(t,e){for(var n,r=t+"",o=0;o<r.length;)e[h&o]=h&(n^=19*e[h&o])+r.charCodeAt(o++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=f,v(n.random(),e),t.exports){t.exports=f;try{r=__webpack_require__(303)}catch(t){}}}([],Math)}));ur.alea=nr,ur.xor128=rr,ur.xorwow=or,ur.xorshift7=ar,ur.xor4096=ir,ur.tychei=sr;var cr=ur.alea,lr=function(){function t(t,e,n,r,o){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var a=o||Math.random();this.random=cr(a.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var o=void 0,a=void 0,i=void 0;do{i=(o=2*this.random()-1)*o+(a=2*this.random()-1)*a}while(i>=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*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}(),hr=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=cr(o.toString()),this.randn=new lr(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,o,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(o=this.randu())<e||Math.log(o)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),fr=function(){function t(t,e,n,r){var o=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==o.dtype||"float32"===o.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=cr(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 dr(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",nt(t),new gt(t,e,n)}function pr(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var vr=An({batchToSpaceND_:function(t,e,n){var r=mn(t,"x","batchToSpaceND"),o=e.reduce((function(t,e){return t*e}));return C(r.rank>=1+e.length,(function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length})),C(n.length===e.length,(function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length})),C(r.shape[0]%o==0,(function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o})),Lt.runKernelFunc((function(t){return t.batchToSpaceND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}}))}}),mr=An({broadcastTo_:function(t,e){var n=mn(t,"broadcastTo","x"),r=n.shape;if(e.some((function(t){return!(t>0)||t%1!=0})))throw new Error("broadcastTo(): Invalid broadcast shape ["+e+"].");if(e.length<n.rank)throw new Error("broadcastTo(): shape.length="+e.length+" < input.rank="+n.rank+".");if(e.length>n.rank){for(var o=n.shape.slice();o.length<e.length;)o.unshift(1);n=n.reshape(o)}for(var a=Array.from(e),i=e.length-1;i>=0;i--)if(n.shape[i]===e[i])a[i]=1;else if(1!==n.shape[i])throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+e+"].");var s=a.map((function(t,e){return t>1?e:-1})).filter((function(t){return t>=0}));return 0===s.length?n.clone():Lt.runKernelFunc((function(t){return t.tile(n,a)}),{input:n},(function(t){return{input:function(){return t.sum(s,!0)}}}))}}),gr=An({cast_:function(t,e){var n=mn(t,"x","cast");if(!W(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");var r={dtype:e};return Lt.runKernelFunc((function(t){return t.cast(n,e)}),{x:n},(function(t){return{x:function(){return t.clone()}}}),"Cast",r)}}),yr=An({clone_:function(t){var e=mn(t,"x","clone",null);return Lt.runKernelFunc((function(){return Lt.makeTensorFromDataId(e.dataId,e.shape,e.dtype)}),{$x:e},(function(t){return{$x:function(){return t.toFloat()}}}))}}),xr=An({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=mn(t,"x","cumsum"),a=En([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=In(1,o.rank)[0],u=Lt.runKernelFunc((function(t){return t.cumsum(i,s,n,r)}),{permutedX:i},(function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}}));return null!=a&&(u=u.transpose(a)),u}}),br=An({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=mn(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return C(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})),C(a*e>=0,(function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape})),C(i%(e*e)==0,(function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape})),Lt.runKernelFunc((function(t){return t.depthToSpace(r,e,n)}),{$x:r})}}),wr=An({expandDims_:function(t,e){void 0===e&&(e=0);var n=mn(t,"x","expandDims",null);C(e<=n.rank,(function(){return"Axis must be <= rank of the tensor"}));var r=n.shape.slice();return e<0&&(C(-(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),Or(n,r)}}),Cr=An({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=dr([t,e],r),a=t<=e?t:e,i=0;i<a;++i)o.set(1,i,i);var s=o.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return Lr(wr(s,0),[n[0],1,1]);if(2===n.length)return Lr(wr(wr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return Lr(wr(wr(wr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}}),Er=An({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=mn(t,"logits","multinomial"),a=o.size,i=o.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=Lt.runKernelFunc((function(t){return t.multinomial(s,r,e,n)}),{logits2D:s});return 1===i?u.as1D():u}}),Rr=An({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 o=mn(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),Lt.runKernelFunc((function(t){return t.oneHot(o,e,n,r)}),{$indices:o},(function(t){return{$indices:function(){return Gn(o.shape,"float32")}}})).reshape(a)}}),Ir=An({pad_:function(t,e,n){void 0===n&&(n=0);var r=mn(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o={paddings:e,constantValue:n};return Lt.runKernelFunc((function(t){return t.pad(r,e,n)}),{x:r},(function(t){var n=e.map((function(t){return t[0]}));return{x:function(){return t.slice(n,r.shape)}}}),"PadV2",o)}}),kr=An({pad1d_:function(t,e,n){return void 0===n&&(n=0),C(2===e.length,(function(){return"Invalid number of paddings. Must be length of 2."})),Ir(t,[e],n)}}),Sr=An({pad2d_:function(t,e,n){return void 0===n&&(n=0),C(2===e.length&&2===e[0].length&&2===e[1].length,(function(){return"Invalid number of paddings. Must be length of 2 each."})),Ir(t,e,n)}}),Ar=An({pad3d_:function(t,e,n){return void 0===n&&(n=0),C(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."})),Ir(t,e,n)}}),Dr=An({pad4d_:function(t,e,n){return void 0===n&&(n=0),C(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."})),Ir(t,e,n)}}),Tr=An({rand_:function(t,e,n){var r=k(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r)}for(var a=0;a<r;a++)o[a]=e();return Lt.makeTensor(o,t,n)}}),Nr=An({randomNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new lr(e,n,r,!1,o),i=dr(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Fr=An({randomGamma_:function(t,e,n,r,o){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var a=new hr(e,n,r,o),i=dr(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),_r=An({randomUniform_:function(t,e,n,r,o){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var a=dr(t,r),i=new fr(e,n,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),Or=An({reshape_:function(t,e){var n=mn(t,"x","reshape",null);e=_(e,n.size),C(n.size===k(e),(function(){return"new shape and old shape must have the same number of elements."}));var r={shape:e};return Lt.runKernelFunc((function(t){return t.reshape(n,e)}),{x:n},(function(t){return{x:function(){return t.reshape(n.shape)}}}),"Reshape",r)}}),Mr=An({spaceToBatchND_:function(t,e,n){var r=mn(t,"x","spaceToBatchND");return C(r.rank>=1+e.length,(function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length})),C(n.length===e.length,(function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length})),C(r.shape.reduce((function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t}),!0),(function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()})),Lt.runKernelFunc((function(t){return t.spaceToBatchND(r,e,n)}),{$x:r},(function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}}))}}),Br=An({squeeze_:function(t,e){var n=mn(t,"x","squeeze");return Or(n,M(n.shape,e).newShape)}}),Pr=An({stack_:function(t,e){void 0===e&&(e=0);var n=gn(t,"tensors","stack");if(C(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,o=n[0].shape,a=n[0].dtype;C(e<=r,(function(){return"Axis must be <= rank of the tensor"})),n.forEach((function(t){E(o,t.shape,"All tensors passed to stack must have matching shapes")})),n.forEach((function(t){C(a===t.dtype,(function(){return"All tensors passed to stack must have matching dtypes"}))}));var i=n.map((function(t){return t.expandDims(e)}));return Yn(i,e)}}),Lr=An({tile_:function(t,e){var n=mn(t,"x","tile",null);C(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}));var r=[n],o={reps:e};return Lt.runKernelFunc((function(t,r){var o=t.tile(n,e);return r([n]),o}),{x:n},(function(t,n){var r=n[0];return{x:function(){var n=Xn(r);if(1===r.rank)for(var o=0;o<e[0];++o)n=n.add(t.slice([o*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(o=0;o<e[0];++o)for(var a=0;a<e[1];++a)n=n.add(t.slice([o*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(var i=0;i<e[2];++i)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(i=0;i<e[2];++i)for(var s=0;s<e[3];++s)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}}),"Tile",o,r)}}),Wr=An({truncatedNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new lr(e,n,r,!0,o),i=dr(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Ur=An({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=mn(t,"x","unstack");C(e>=-n.shape.length&&e<n.shape.length,(function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")"})),e<0&&(e+=n.shape.length);var r={axis:e};return Lt.runKernelFunc((function(t){return t.unstack(n,e)}),{x:n},(function(t){return{x:function(){return Pr(t,e)}}}),"Unpack",r)}}),Vr=function(t,e){return n(this,void 0,void 0,(function(){var n,o,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return n=mn(t,"x","setdiff1d"),o=mn(e,"y","setdiff1d"),C(n.dtype===o.dtype,(function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+o.dtype+")."})),C(1===n.rank,(function(){return"x should be 1D tensor, but got x ("+n.shape+")."})),C(1===o.rank,(function(){return"y should be 1D tensor, but got y ("+o.shape+")."})),[4,n.data()];case 1:return a=r.sent(),[4,o.data()];case 2:for(i=r.sent(),s=new Set(i),u=0,h=0;h<a.length;h++)s.has(a[h])||u++;for(c=new gt([u],n.dtype),l=new gt([u],"int32"),h=0,f=0;h<a.length;h++)s.has(a[h])||(c.values[f]=a[h],l.values[f]=h,f++);return[2,[c.toTensor(),l.toTensor()]]}}))}))};function zr(t,e,n,r){void 0===r&&(r=!0);var o=[];if(r)(o=o.concat(e.slice(0))).push(t[0]/n),o=o.concat(t.slice(1));else{o=o.concat(t[0]);for(var a=e.length,i=0;i<a;++i)o=o.concat([t[i+1]/e[i],e[i]]);o=o.concat(t.slice(a+1))}return o}function Gr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var o=e+1;o<t;++o)o<=2*e?(r.push(o),r.push(o-(e+1))):r.push(o)}else{var a=[],i=[];for(o=1;o<t;++o)o>=2*e+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i)}return r}function Hr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;a<t.length;++a)a<=e.length?r?o.push(e[a-1]*t[a]):o.push(t[a]/e[a-1]):o.push(t[a]);return o}function qr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function Kr(t,e,n){for(var r=t.slice(0,1),o=0;o<n;++o)r.push(t[o+1]-e[o][0]-e[o][1]);return r}function jr(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.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],o=1,a=0;a<n.length-1;++a)o*=n[a];var i=t.shape,s=n.slice();s.pop();var u=1;for(a=r;a<t.rank;++a)u*=i[a],s.push(i[a]);var c=$(t.shape).map((function(t){return t/u})).concat([1]).slice(0,r);return[s,o,u,c]}var Xr=Object.freeze({prepareAndValidate:jr}),Yr=30;function $r(t){return t<=Yr?t:Y(t,Math.floor(Math.sqrt(t)))}function Qr(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rank<o)throw new Error(a+" update.rank < "+o+". ");if(t.length<r+(n.rank-o))throw new Error(a+" Output shape length < "+(r+(n.rank-o)));if(n.rank!==o+t.length-r)throw new Error(a+" update.rank != "+(o+t.length-r));for(var i=0;i<o;++i)if(n.shape[i]!==e.shape[i])throw new Error(a+" updates.shape["+i+"] ("+n.shape[i]+") != indices.shape["+i+"] ("+e.shape[i]+").");for(i=0;i<n.rank-o;++i)if(n.shape[i+o]!==t[i+r])throw new Error(a+" updates.shape["+(i+o)+"] ("+n.shape[i+o]+") != shape["+(i+o)+"] ("+t[i+o]+")")}function Jr(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)}Qr(n,e,t)}function Zr(t,e,n){for(var r=e.shape.length,o=r>1?e.shape[r-1]:1,a=n.length,i=1,s=o;s<a;++s)i*=n[s];var u=o<1?1:o;return{sliceRank:o,numUpdates:k(e.shape)/u,sliceSize:i,strides:$(n.slice(0,o)).concat([1]),outputSize:k(n)}}var to=Object.freeze({validateUpdateShape:Qr,validateInput:Jr,calculateShapes:Zr});function eo(t,e,n){C(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+")."})),C(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){C(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]+")"}))},o=0;o<t.rank;++o)r(o)}function no(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function ro(t,e,n){for(var r=[],o=0;o<t.length;o++)r[o]=Math.ceil((e[o]-t[o])/n[o]);return r}function oo(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=x(0,a,s-1)}function ao(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=i>0?x(0,a,s):x(-1,a,s-1)}function io(t,e,n){for(var r=n.length,o=0;o<n.length;o++)if(n[o]>1){r=o;break}for(o=r+1;o<n.length;o++)if(e[o]>0||n[o]!==t[o])return!1;return!0}function so(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}var uo=Object.freeze({assertParamsValid:eo,maskToAxes:no,computeOutShape:ro,startForAxis:oo,stopForAxis:ao,isSliceContinous:io,computeFlatOffset:so});function co(t){return C(X(t),(function(){return"The f passed in grad(f) must be a function"})),function(e,n){var r=mn(e,"x","tf.grad",null),o=null!=n?mn(n,"dy","tf.grad"):null;return Lt.tidy((function(){var e=Lt.gradients((function(){return t(r)}),[r],o),n=e.value,a=e.grads;return null!=o&&E(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),mo(a),a[0]}))}}function lo(t){return C(X(t),(function(){return"The f passed in grads(f) must be a function"})),function(e,n){C(Array.isArray(e),(function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"}));var r=gn(e,"args","tf.grads",null),o=null!=n?mn(n,"dy","tf.grads"):null;return Lt.tidy((function(){var e=Lt.gradients((function(){return t.apply(void 0,r)}),r,o),n=e.value,a=e.grads;return null!=o&&E(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),mo(a),a}))}}function ho(t){return C(X(t),(function(){return"The f passed in valueAndGrad(f) must be a function"})),function(e,n){C(e instanceof wt,(function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"})),C(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"}));var r=Lt.gradients((function(){return t(e)}),[e],n),o=r.grads,a=r.value;return mo(o),{grad:o[0],value:a}}}function fo(t){return C(X(t),(function(){return"The f passed in valueAndGrads(f) must be a function"})),function(e,n){C(Array.isArray(e)&&e.every((function(t){return t instanceof wt})),(function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"})),C(null==n||n instanceof wt,(function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"}));var r=Lt.gradients((function(){return t.apply(void 0,e)}),e,n);return null!=n&&E(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),mo(r.grads),r}}function po(t,e){C(X(t),(function(){return"The f passed in variableGrads(f) must be a function"})),C(null==e||Array.isArray(e)&&e.every((function(t){return t instanceof St})),(function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}));var n=null!=e;if(!n)for(var r in e=[],Lt.registeredVariables)e.push(Lt.registeredVariables[r]);var o=n?e.filter((function(t){return!t.trainable})):null,a=e.length;C((e=e.filter((function(t){return t.trainable}))).length>0,(function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."}));var i=Lt.gradients(t,e,null,!0),s=i.value,u=i.grads;C(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()."})),C(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!=o&&o.forEach((function(t){return c[t.name]=null})),{value:s,grads:c}}function vo(t){return Lt.customGrad(t)}function mo(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 go=An({softmax_:function(t,e){void 0===e&&(e=-1);var n=mn(t,"logits","softmax","float32");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 Lt.runKernelFunc((function(t,r){var o=t.softmax(n,e);return r([o]),o}),{logits:n},(function(t,n){var r=n[0],o=t.mul(r);return{logits:function(){return o.sub(o.sum([e],!0).mul(r))}}}),"Softmax",{dim:e},[],[!0])}}),yo=An({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=mn(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 vo((function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());n([a]);return{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}}))(n)}}),xo=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}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.dataIdsCount++,this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),bo=function(){function t(){}return t.prototype.time=function(t){return wo("time")},t.prototype.read=function(t){return wo("read")},t.prototype.readSync=function(t){return wo("readSync")},t.prototype.numDataIds=function(){return wo("numDataIds")},t.prototype.disposeData=function(t){return wo("disposeData")},t.prototype.write=function(t,e,n){return wo("write")},t.prototype.move=function(t,e,n,r){return wo("move")},t.prototype.memory=function(){return wo("memory")},t.prototype.floatPrecision=function(){return wo("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return wo("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights;return wo("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return wo("slice")},t.prototype.stridedSlice=function(t,e,n,r){return wo("stridedSlice")},t.prototype.unstack=function(t,e){return wo("unstack")},t.prototype.reverse=function(t,e){return wo("reverse")},t.prototype.concat=function(t,e){return wo("concat")},t.prototype.neg=function(t){return wo("neg")},t.prototype.add=function(t,e){return wo("add")},t.prototype.addN=function(t){return wo("addN")},t.prototype.subtract=function(t,e){return wo("subtract")},t.prototype.multiply=function(t,e){return wo("multiply")},t.prototype.realDivide=function(t,e){return wo("realDivide")},t.prototype.floorDiv=function(t,e){return wo("floorDiv")},t.prototype.sum=function(t,e){return wo("sum")},t.prototype.prod=function(t,e){return wo("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return wo("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return wo("argMin")},t.prototype.argMax=function(t,e){return wo("argMax")},t.prototype.equal=function(t,e){return wo("equal")},t.prototype.notEqual=function(t,e){return wo("notEqual")},t.prototype.less=function(t,e){return wo("less")},t.prototype.lessEqual=function(t,e){return wo("lessEqual")},t.prototype.greater=function(t,e){return wo("greater")},t.prototype.greaterEqual=function(t,e){return wo("greaterEqual")},t.prototype.logicalNot=function(t){return wo("logicalNot")},t.prototype.logicalAnd=function(t,e){return wo("logicalAnd")},t.prototype.logicalOr=function(t,e){return wo("logicalOr")},t.prototype.where=function(t){return wo("where")},t.prototype.select=function(t,e,n){return wo("select")},t.prototype.topk=function(t,e,n){return wo("topk")},t.prototype.min=function(t,e){return wo("min")},t.prototype.minimum=function(t,e){return wo("minimum")},t.prototype.mod=function(t,e){return wo("mod")},t.prototype.max=function(t,e){return wo("max")},t.prototype.maximum=function(t,e){return wo("maximum")},t.prototype.all=function(t,e){return wo("all")},t.prototype.any=function(t,e){return wo("any")},t.prototype.squaredDifference=function(t,e){return wo("squaredDifference")},t.prototype.ceil=function(t){return wo("ceil")},t.prototype.floor=function(t){return wo("floor")},t.prototype.round=function(t){return wo("round")},t.prototype.sign=function(t){return wo("sign")},t.prototype.isNaN=function(t){return wo("isNaN")},t.prototype.isInf=function(t){return wo("isInf")},t.prototype.isFinite=function(t){return wo("isFinite")},t.prototype.pow=function(t,e){return wo("pow")},t.prototype.exp=function(t){return wo("exp")},t.prototype.expm1=function(t){return wo("expm1")},t.prototype.softmax=function(t,e){return wo("softmax")},t.prototype.log=function(t){return wo("log")},t.prototype.log1p=function(t){return wo("log1p")},t.prototype.sqrt=function(t){return wo("sqrt")},t.prototype.rsqrt=function(t){return wo("rsqrt")},t.prototype.square=function(t){return wo("square")},t.prototype.reciprocal=function(t){return wo("reciprocal")},t.prototype.relu=function(t){return wo("relu")},t.prototype.relu6=function(t){return wo("relu6")},t.prototype.prelu=function(t,e){return wo("prelu")},t.prototype.elu=function(t){return wo("elu")},t.prototype.eluDer=function(t,e){return wo("eluDer")},t.prototype.selu=function(t){return wo("selu")},t.prototype.int=function(t){return wo("int")},t.prototype.clip=function(t,e,n){return wo("clip")},t.prototype.abs=function(t){return wo("abs")},t.prototype.complexAbs=function(t){return wo("complexAbs")},t.prototype.sigmoid=function(t){return wo("sigmoid")},t.prototype.softplus=function(t){return wo("softplus")},t.prototype.sin=function(t){return wo("sin")},t.prototype.cos=function(t){return wo("cos")},t.prototype.tan=function(t){return wo("tan")},t.prototype.asin=function(t){return wo("asin")},t.prototype.acos=function(t){return wo("acos")},t.prototype.atan=function(t){return wo("atan")},t.prototype.atan2=function(t,e){return wo("atan2")},t.prototype.sinh=function(t){return wo("sinh")},t.prototype.cosh=function(t){return wo("cosh")},t.prototype.tanh=function(t){return wo("tanh")},t.prototype.asinh=function(t){return wo("asinh")},t.prototype.acosh=function(t){return wo("acosh")},t.prototype.atanh=function(t){return wo("atanh")},t.prototype.erf=function(t){return wo("erf")},t.prototype.step=function(t,e){return wo("step")},t.prototype.fusedConv2d=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;return wo("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return wo("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return wo("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return wo("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights;return wo("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return wo("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return wo("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return wo("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return wo("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return wo("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return wo("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return wo("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return wo("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return wo("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return wo("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return wo("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return wo("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return wo("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return wo("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return wo("reshape")},t.prototype.cast=function(t,e){return wo("cast")},t.prototype.tile=function(t,e){return wo("tile")},t.prototype.pad=function(t,e,n){return wo("pad")},t.prototype.transpose=function(t,e){return wo("transpose")},t.prototype.gather=function(t,e,n){return wo("gather")},t.prototype.gatherND=function(t,e){return wo("gatherND")},t.prototype.scatterND=function(t,e,n){return wo("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return wo("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return wo("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return wo("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return wo("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return wo("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return wo("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,o,a){return wo("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){return wo("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){return wo("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return wo("multinomial")},t.prototype.oneHot=function(t,e,n,r){return wo("oneHot")},t.prototype.cumsum=function(t,e,n,r){return wo("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return wo("nonMaxSuppression")},t.prototype.fft=function(t){return wo("fft")},t.prototype.ifft=function(t){return wo("ifft")},t.prototype.complex=function(t,e){return wo("complex")},t.prototype.real=function(t){return wo("real")},t.prototype.imag=function(t){return wo("imag")},t.prototype.cropAndResize=function(t,e,n,r,o,a){return wo("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return wo("depthToSpace")},t.prototype.split=function(t,e,n){return wo("split")},t.prototype.sparseToDense=function(t,e,n,r){return wo("sparseToDense")},t.prototype.diag=function(t){return wo("diag")},t.prototype.fill=function(t,e,n){return wo("fill")},t.prototype.onesLike=function(t){return wo("onesLike")},t.prototype.zerosLike=function(t){return wo("zerosLike")},t.prototype.linspace=function(t,e,n){return wo("linspace")},t.prototype.dispose=function(){return wo("dispose")},t}();function wo(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function Co(t,e){for(var n=t.length,r=[],o=0;o<n;o++){var a=n-1-o,i=t[a]||1;(e[e.length-1-o]||1)>1&&1===i&&r.unshift(a)}return r}function Eo(t,e){for(var n=[],r=0;r<e.length;r++){var o=t[t.length-r-1],a=e.length-r-1,i=e[a];(null==o||1===o&&i>1)&&n.unshift(a)}return n}function Ro(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;o<r;o++){var a=t[t.length-o-1];null==a&&(a=1);var i=e[e.length-o-1];if(null==i&&(i=1),1===a)n.unshift(i);else if(1===i)n.unshift(a);else{if(a!==i)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(a)}}return n}function Io(t,e,n,r,o,a,i){void 0===i&&(i="channelsLast");var s,u=To(e),c=u[0],l=u[1];if("channelsLast"===i)s=[c,l,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[c,l,t[1],t[1]]}return So(t,s,n,r,o,a,!1,i)}function ko(t,e,n,r,o,a,i){void 0===i&&(i="NDHWC");var s,u,c=No(e),l=c[0],h=c[1],f=c[2];if("NDHWC"===i)u="channelsLast",s=[l,h,f,t[4],t[4]];else{if("NCDHW"!==i)throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[l,h,f,t[1],t[1]]}return Ao(t,s,n,r,o,!1,u,a)}function So(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3];if("channelsLast"===s)c=t[0],l=t[1],h=t[2],f=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);c=t[0],f=t[1],l=t[2],h=t[3]}var d,p=e[0],v=e[1],m=e[3],g=To(n),y=g[0],x=g[1],b=To(r),w=b[0],E=b[1],R=Fo(p,w),I=Fo(v,E),k=function(t,e,n,r,o,a,i,s){var u,c,l;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var h=function(t,e,n,r,o){null==r&&(r=Do(t,e,n));var a=t[0],i=t[1],s=_o((a-e+2*r)/n+1,o);C(A(s),(function(){return"The output # of rows ("+s+") must be an integer. Change the stride and/or zero pad parameters"}));var u=_o((i-e+2*r)/n+1,o);return C(A(u),(function(){return"The output # of columns ("+u+") must be an integer. Change the stride and/or zero pad parameters"})),[s,u]}([e,n],a,r,t,s);c=h[0],l=h[1]}else if("same"===t){c=Math.ceil(e/r),l=Math.ceil(n/o);var f=Math.max(0,(c-1)*r+a-e),d=Math.max(0,(l-1)*o+i-n),p=Math.floor(f/2),v=f-p,m=Math.floor(d/2);u={top:p,bottom:v,left:m,right:d-m,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-a+1)/r),l=Math.ceil((n-i+1)/o)}return{padInfo:u,outHeight:c,outWidth:l}}(o,l,h,y,x,R,I,a),S=k.padInfo,D=k.outHeight,T=k.outWidth,N=i?m*f:m;return"channelsFirst"===s?d=[c,N,D,T]:"channelsLast"===s&&(d=[c,D,T,N]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:h,inChannels:f,outHeight:D,outWidth:T,outChannels:N,padInfo:S,strideHeight:y,strideWidth:x,filterHeight:p,filterWidth:v,effectiveFilterHeight:R,effectiveFilterWidth:I,dilationHeight:w,dilationWidth:E,inShape:t,outShape:d,filterShape:e}}function Ao(t,e,n,r,o,a,i,s){void 0===a&&(a=!1),void 0===i&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],l=u[1],h=u[2],f=u[3],d=u[4];if("channelsLast"===i)c=t[0],l=t[1],h=t[2],f=t[3],d=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);c=t[0],d=t[1],l=t[2],h=t[3],f=t[4]}var p,v=e[0],m=e[1],g=e[2],y=e[4],x=No(n),b=x[0],w=x[1],E=x[2],R=No(r),I=R[0],k=R[1],S=R[2],D=Fo(v,I),T=Fo(m,k),N=Fo(g,S),F=function(t,e,n,r,o,a,i,s,u,c,l){var h,f,d,p;if("number"==typeof t){h={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var v=function(t,e,n,r,o,a){null==o&&(o=Do(t,e,r));var i=t[0],s=t[1],u=t[2],c=_o((i-e+2*o)/r+1,a);C(A(c),(function(){return"The output # of depths ("+c+") must be an integer. Change the stride and/or zero pad parameters"}));var l=_o((s-e+2*o)/r+1,a);C(A(l),(function(){return"The output # of rows ("+l+") must be an integer. Change the stride and/or zero pad parameters"}));var h=_o((u-e+2*o)/r+1,a);return C(A(h),(function(){return"The output # of columns ("+h+") must be an integer. Change the stride and/or zero pad parameters"})),[c,l,h,n]}([e,n,r,1],s,1,o,t,l);f=v[0],d=v[1],p=v[2]}else if("same"===t){f=Math.ceil(e/o),d=Math.ceil(n/a),p=Math.ceil(r/i);var m=(f-1)*o+s-e,g=(d-1)*a+u-n,y=(p-1)*i+c-r,x=Math.floor(m/2),b=m-x,w=Math.floor(g/2),E=g-w,R=Math.floor(y/2);h={top:w,bottom:E,left:R,right:y-R,front:x,back:b,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},f=Math.ceil((e-s+1)/o),d=Math.ceil((n-u+1)/a),p=Math.ceil((r-c+1)/i)}return{padInfo:h,outDepth:f,outHeight:d,outWidth:p}}(o,l,h,f,b,w,E,D,T,N,s),_=F.padInfo,O=F.outDepth,M=F.outHeight,B=F.outWidth,P=a?y*d:y;return"channelsFirst"===i?p=[c,P,O,M,B]:"channelsLast"===i&&(p=[c,O,M,B,P]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:h,inWidth:f,inChannels:d,outDepth:O,outHeight:M,outWidth:B,outChannels:P,padInfo:_,strideDepth:b,strideHeight:w,strideWidth:E,filterDepth:v,filterHeight:m,filterWidth:g,effectiveFilterDepth:D,effectiveFilterHeight:T,effectiveFilterWidth:N,dilationDepth:I,dilationHeight:k,dilationWidth:S,inShape:t,outShape:p,filterShape:e}}function Do(t,e,n,r){void 0===r&&(r=1);var o=Fo(e,r);return Math.floor((t[0]*(n-1)-n+o)/2)}function To(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function No(t){return"number"==typeof t?[t,t,t]:t}function Fo(t,e){return e<=1?t:t+(t-1)*(e-1)}function _o(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e)}}function Oo(t){var e=To(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Mo(t,e){return Oo(t)||Oo(e)}function Bo(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function Po(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=Gn(t.shape),o=t.toFloat(),a=n.complex(o,r);return r.dispose(),o.dispose(),a}if(!U(t.dtype,e))return Lt.makeTensorFromDataId(t.dataId,t.shape,e);if("complex64"===t.dtype){var i=n.real(t);a=i.cast(e);return i.dispose(),a}if("int32"===e)return n.int(t);if("bool"===e){var s=On(0,t.dtype);a=n.notEqual(t,s);return s.dispose(),a}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function Lo(t,e){return Lt.makeTensorFromDataId(t.dataId,e,t.dtype)}function Wo(t,e,n){var r=(e-t)/(n-1),o=tt(n,"float32");o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+r;return Mn(o,"float32")}var Uo=Object.freeze({castTensor:Po,reshapeTensor:Lo,linspaceImpl:Wo,upcastType:Dt,axesAreInnerMostDims:yn,combineLocations:xn,computeOutAndReduceShapes:bn,expandShapeToKeepDim:wn,assertAxesAreInnerMostDims:Cn,getAxesPermutation:En,getUndoAxesPermutation:Rn,getInnerMostAxes:In,getBroadcastDims:Co,getReductionAxes:Eo,assertAndGetBroadcastShape:Ro,assertParamsConsistent:kn,computeOutShape:Sn,computePool2DInfo:Io,computePool3DInfo:ko,computeConv2DInfo:So,computeConv3DInfo:Ao,computeDefaultPad:Do,tupleValuesAreOne:Oo,eitherStridesOrDilationsAreOne:Mo,convertConv2DDataFormat:Bo,PARALLELIZE_THRESHOLD:Yr,computeOptimalWindowSize:$r});function Vo(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n}function zo(t,e){return{real:t[2*e],imag:t[2*e+1]}}function Go(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function Ho(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function qo(t,e,n){var r=function(t,e,n){return function(t,e,n){var r=0,o=t.length,a=0,i=!1;for(;r<o;){var s=n(e,t[a=r+(o-r>>>1)]);s>0?r=a+1:(o=a,i=!s)}return i?r:-r-1}(t,e,n||Ko)}(t,e,n),o=r<0?-(r+1):r;t.splice(o,0,e)}function Ko(t,e){return t>e?1:t<e?-1:0}function jo(t,e,n,r,o){return Yo(t,e,n,r,o,0).selectedIndices}function Xo(t,e,n,r,o,a){var i=Yo(t,e,n,r,o,a,!0);return i.numValidOutputs.dispose(),{selectedIndices:i.selectedIndices,selectedScores:i.selectedScores}}function Yo(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1);for(var u=Array.from(e).map((function(t,e){return{score:t,boxIndex:e,suppressBeginIndex:0}})).filter((function(t){return t.score>o})).sort(Jo),c=a>0?-.5/a:0,l=[],h=[];l.length<n&&u.length>0;){var f=u.pop(),d=f.score,p=f.boxIndex,v=f.suppressBeginIndex;if(d<o)break;for(var m=!1,g=l.length-1;g>=v;--g){var y=$o(t,p,l[g]);if(y>=r){m=!0;break}if(f.score=f.score*Qo(r,c,y),f.score<=o)break}f.suppressBeginIndex=l.length,m||(f.score===d?(l.push(p),h.push(f.score)):f.score>o&&qo(u,f,Jo))}var x=l.length;return s&&(l.fill(0,x),h.fill(0,x)),{selectedIndices:Mn(l,"int32"),selectedScores:Mn(h,"float32"),numValidOutputs:On(x,"int32")}}function $o(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),f=Math.max(o[1],o[3]),d=(s-a)*(u-i),p=(h-c)*(f-l);if(d<=0||p<=0)return 0;var v=Math.max(a,c),m=Math.max(i,l),g=Math.min(s,h),y=Math.min(u,f),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(d+p-x)}function Qo(t,e,n){var r=Math.exp(e*n*n);return n<=t?r:0}function Jo(t,e){return t.score-e.score||t.score===e.score&&e.boxIndex-t.boxIndex}function Zo(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map((function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a}))}function ta(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=dr(n,t.dtype);for(r=0;r<o.values.length;++r){for(var a=o.indexToLoc(r),i=new Array(t.rank),s=0;s<i.length;s++)i[s]=a[s]%t.shape[s];var u=t.locToIndex(i);o.values[r]=t.values[u]}return o.toTensor()}function ea(t,e,n,r,o){for(var a=e[e.length-1],i=[t.length/a,a],s=i[0],u=i[1],c=B(n,s*r),l=B("int32",s*r),h=0;h<s;h++){for(var f=h*u,d=t.subarray(f,f+u),p=[],v=0;v<d.length;v++)p.push({value:d[v],index:v});p.sort((function(t,e){return e.value-t.value}));var m=h*r,g=c.subarray(m,m+r),y=l.subarray(m,m+r);for(v=0;v<r;v++)g[v]=p[v].value,y[v]=p[v].index}var x=e.slice();return x[x.length-1]=r,[Fn(c,x,n),Fn(l,x,"int32")]}function na(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=dr(t,"int32"),a=dr([n.length,t.length],"int32");for(r=0;r<n.length;r++){var i=o.indexToLoc(n[r]),s=r*t.length;a.values.set(i,s)}return a.toTensor()}var ra=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 "},oa=function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!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 "},aa=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,o=t.batchSize,a=t.inSize,i=Math.ceil(a/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[o,i];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 "};function ia(t,e){return["x","y","z","w","u","v"].slice(0,e).map((function(e){return t+"."+e}))}function sa(t,e){return 1===e?[t]:ia(t,e)}function ua(){var t,e,n,r,o,a,s,u,c,l;return 2===i().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",a="outputColor",s="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",c="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",o="texture2D",a="gl_FragColor",s="",u="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",c="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:a,defineOutput:s,defineSpecialNaN:u,defineSpecialInf:c,defineRound:l}}function ca(t,e,n){void 0===n&&(n="index");var r=$(e);return r.map((function(e,o){return"int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";"})).join("")}function la(t){var e=$(t).map((function(t){return t.toString()}));return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var ha="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function fa(t,e,n,r){var o=[];t.forEach((function(t){var e=k(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"))}));var a,i,s=o.join("\n"),u=t.map((function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?pa(t):da(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=Co(t.shapeInfo.logicalShape,e.logicalShape),c=wa(s),l=s-i,h=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map((function(t){return"coords."+h[t+l]+" = 0;"})).join("\n");var f="";f=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+h[e+l]})).join(", ");var d="return outputValue;",p=1===k(t.shapeInfo.logicalShape),v=1===k(e.logicalShape);if(1!==i||p||v){if(p&&!v)d=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var m=i-2,g=i-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?d="return vec4(outputValue.x);":u.indexOf(m)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+c+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+f+");\n "+d+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&S(i,a))return"\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var c,l=wa(u),h=Co(t.shapeInfo.logicalShape,e.logicalShape),f=u-s,d=["x","y","z","w","u","v"];c=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map((function(t){return"coords."+d[t+f]+" = 0;"})).join("\n");var p="";p=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map((function(t,e){return"coords."+d[e+f]})).join(", ");return"\n float "+o+"() {\n "+l+" coords = getOutputCoords();\n "+c+"\n return get"+r+"("+p+");\n }\n "}(t,e));return r}(t,e,r)})).join("\n"),c=e.texShape,l=ua(),h=function(t){return"\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(l),f=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 "+t.defineSpecialNaN+"\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 "+va+"\n "+ma+"\n "+ga+"\n "}(l);return e.isPacked?(a=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)];if(1===n[0])return"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ";if(1===n[1])return"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ";return"\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(S(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,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Math.ceil(n[2]/2),i=a*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+o[0]+", "+o[1]+"));\n int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 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),o=r*Math.ceil(t[t.length-2]/2),a=o,i="",s="b, r, c",u=2;u<t.length-1;u++)a*=t[t.length-u-1],i="\n int b"+u+" = index / "+a+";\n index -= b"+u+" * "+a+";\n "+i,s="b"+u+", "+s;return"\n ivec"+t.length+" getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n "+i+"\n\n int b = index / "+o+";\n index -= b * "+o+";\n\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec"+t.length+"("+s+");\n }\n "}(t,e)}var n,r,o,a,i}(e.logicalShape,c),i=function(t){return"\n void setOutput(vec4 val) {\n "+t.output+" = val;\n }\n "}(l)):(a=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){if(1===e[0])return"\n int getOutputCoords() {\n return int(resultUV.x * "+e[1]+".0);\n }\n ";if(1===e[1])return"\n int getOutputCoords() {\n return int(resultUV.y * "+e[0]+".0);\n }\n ";return"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n return resTexRC.x * "+e[1]+" + resTexRC.y;\n }\n "}(0,e);case 2:return function(t,e){if(S(t,e))return"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n }\n ";if(1===t[1])return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ";if(1===t[0])return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ";return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n int r = index / "+t[1]+";\n int c = index - r * "+t[1]+";\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=e,r=ca(["r","c","d"],t),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n "+r+"\n return ivec3(r, c, d);\n }\n ";case 4:return function(t,e){var n=ca(["r","c","d","d2"],t);return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n "+n+"\n return ivec4(r, c, d, d2);\n }\n "}(t,e);case 5:return function(t,e){var n=ca(["r","c","d","d2","d3"],t);return"\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n "+e[1]+"));\n\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n "}(t,e);case 6:return function(t,e){var n=ca(["r","c","d","d2","d3","d4"],t);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}var n,r}(e.logicalShape,c),i=function(t){return"\n void setOutput(float val) {\n "+t.output+" = vec4(val, 0, 0, 0);\n }\n "}(l)),r&&(f+=ya),[f,h,i,s,a,u,n].join("\n")}function da(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===o&&1===a)return"\n float "+n+"() {\n return sampleTexture("+e+", halfCR);\n }\n ";var i=t.shapeInfo.texShape,s=i[0],u=i[1],c=xa(e);return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+s+", "+u+", "+c+");\n return sampleTexture("+e+", uv);\n }\n "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n float "+n+"(int index) {\n "+ba(t)+"\n }\n ";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===a&&1===o)return"\n float "+n+"(int index) {\n return sampleTexture("+e+", halfCR);\n }\n ";var i=xa(e);if(1===a)return"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+i+") + 0.5) / "+o+".0);\n return sampleTexture("+e+", uv);\n }\n ";if(1===o)return"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+i+") + 0.5) / "+a+".0, 0.5);\n return sampleTexture("+e+", uv);\n }\n ";return"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+o+", "+a+", index + "+i+");\n return sampleTexture("+e+", uv);\n }\n "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape;if(null!=o&&S(e,o)){var a=o[0],i=o[1];return"\n float "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n return sampleTexture("+n+", uv);\n }\n "}var s=M(e),u=s.newShape,c=s.keptDims,l=u;if(l.length<e.length){var h=Ca(t,l);return"\n "+da(h)+"\n float "+r+"(int row, int col) {\n return "+r+"("+Ea(["row","col"],c)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col) {\n int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n "+ba(t)+"\n }\n ";var f=o[0],d=o[1],p=xa(n);if(1===d)return"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+p+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(1===f)return"\n float "+r+"(int row, int col) {\n float index = dot(vec3(row, col, "+p+"), vec3("+e[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+d+".0, 0.5);\n return sampleTexture("+n+", uv);\n }\n ";return"\n float "+r+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+e[1]+" + col + "+p+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+n+", uv);\n }\n"}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[1]*e[2],a=e[2],i=M(e),s=i.newShape,u=i.keptDims,c=s;if(c.length<e.length){var l=Ca(t,c);return"\n "+da(l)+"\n float "+r+"(int row, int col, int depth) {\n return "+r+"("+Ea(["row","col","depth"],u)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3("+o+", "+a+", 1)));\n "+ba(t)+"\n }\n ";var h=t.shapeInfo.texShape,f=h[0],d=h[1],p=t.shapeInfo.flatOffset;if(d===o&&null==p)return"\n float "+r+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+a+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+d+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(d===a&&null==p)return"\n float "+r+"(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+d+".0, "+f+".0);\n return sampleTexture("+n+", uv);\n }\n ";var v=xa(n);return"\n float "+r+"(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+o+" + col * "+a+" + depth + "+v+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[3],a=e[2]*o,i=e[1]*a,s=M(e),u=s.newShape,c=s.keptDims;if(u.length<e.length){var l=Ca(t,u);return"\n "+da(l)+"\n float "+r+"(int row, int col, int depth, int depth2) {\n return "+r+"("+Ea(["row","col","depth","depth2"],c)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4("+i+", "+a+", "+o+", 1)));\n "+ba(t)+"\n }\n ";var h=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,d=f[0],p=f[1];if(p===i&&null==h)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3("+a+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+p+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(p===o&&null==h)return"\n float "+r+"(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3("+e[1]*e[2]+", "+e[2]+", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+p+".0, "+d+".0);\n return sampleTexture("+n+", uv);\n }\n ";var v=xa(n);return"\n float "+r+"(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+i+" + col * "+a+" +\n depth * "+o+" + depth2;\n vec2 uv = uvFromFlat("+d+", "+p+", index + "+v+");\n return sampleTexture("+n+", uv);\n }\n "}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[4],a=e[3]*o,i=e[2]*a,s=e[1]*i,u=M(e),c=u.newShape,l=u.keptDims;if(c.length<e.length){var h=Ca(t,c);return"\n "+da(h)+"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n return "+r+"("+Ea(["row","col","depth","depth2","depth3"],l)+");\n }\n "}if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4("+s+", "+i+", "+a+", "+o+")) +\n depth3;\n "+ba(t)+"\n }\n ";var f=t.shapeInfo.flatOffset,d=t.shapeInfo.texShape,p=d[0],v=d[1];if(v===s&&null==f)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+i+", "+a+", "+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(v===o&&null==f)return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4("+e[1]*e[2]*e[3]+",\n "+e[2]*e[3]+", "+e[3]+", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+p+".0);\n return sampleTexture("+n+", uv);\n }\n ";var m=xa(n);return"\n float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+s+" + col * "+i+" + depth * "+a+" +\n depth2 * "+o+" + depth3 + "+m+";\n vec2 uv = uvFromFlat("+p+", "+v+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=M(e),a=o.newShape,i=o.keptDims;if(a.length<e.length){var s=Ca(t,a);return"\n "+da(s)+"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+r+"("+Ea(["row","col","depth","depth2","depth3","depth4"],i)+");\n }\n "}var u=e[5],c=e[4]*u,l=e[3]*c,h=e[2]*l,f=e[1]*h;if(t.shapeInfo.isUniform)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4("+f+", "+h+", "+l+", "+c+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+u+", 1)));\n "+ba(t)+"\n }\n ";var d=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,v=p[0],m=p[1];if(m===f&&null==d)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4("+h+", "+l+", "+c+", "+u+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+v+".0);\n return sampleTexture("+n+", uv);\n }\n ";if(m===u&&null==d)return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4("+e[1]*e[2]*e[3]*e[4]+",\n "+e[2]*e[3]*e[4]+",\n "+e[3]*e[4]+",\n "+e[4]+")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+v+".0);\n return sampleTexture("+n+", uv);\n }\n ";var g=xa(n);return"\n float "+r+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+f+" + col * "+h+" + depth * "+l+" +\n depth2 * "+c+" + depth3 * "+u+" + depth4 + "+g+";\n vec2 uv = uvFromFlat("+v+", "+m+", index);\n return sampleTexture("+n+", uv);\n }\n "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function pa(t){var e,n,r;switch(t.shapeInfo.logicalShape.length){case 0:return e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=ua(),"\n vec4 "+n+"() {\n return "+r.texture2D+"("+e+", 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,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=ua();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+o[0]+", "+o[1]+", index);\n return "+a.texture2D+"("+e+", uv);\n }\n "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=o[0],i=o[1],s=ua();if(null!=o&&S(e,o))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=Math.ceil(e[1]/2);return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+c+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===e[0]){var i=e.slice(1),s=Ca(t,i);return"\n "+pa(s)+"\n vec4 "+r+"(int b, int row, int col) {\n return "+r+"("+Ea(["b","row","col"],[1,2])+");\n }\n "}var u=a[0],c=a[1],l=Math.ceil(e[2]/2),h=l*Math.ceil(e[1]/2),f=ua();return"\n vec4 "+r+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+u+", "+c+", "+h+", "+l+", b, row, col);\n return "+f.texture2D+"("+n+", uv);\n }\n "}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=i[0],u=i[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),h="int b, int row, int col",f="b * "+l+" + (row / 2) * "+c+" + (col / 2)",d=2;d<n-1;d++)h="int b"+d+", "+h,l*=e[n-d-1],f="b"+d+" * "+l+" + "+f;var p=ua();return"\n vec4 "+o+"("+h+") {\n int index = "+f+";\n int texR = index / "+u+";\n int texC = index - texR * "+u+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n return "+p.texture2D+"("+r+", uv);\n }\n "}(t)}}var va="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ma="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ga="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ya="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function xa(t){return"offset"+t}function ba(t){var e=t.name,n=k(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n for (int i = 0; i < "+n+"; i++) {\n if (i == index) {\n return "+e+"[i];\n }\n }\n "}function wa(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function Ca(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function Ea(t,e){return e.map((function(e){return t[e]})).join(", ")}var Ra=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,C(t.length>2,(function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."}));var o=t[t.length-1],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,l=wa(c),h=sa("coords",c);if(1===a){var f=wa(s=c+1);i="\n "+f+" sourceLocR = "+f+"("+h.join()+", 0);\n ++"+h[c-1]+";\n "+f+" sourceLocG = "+f+"("+h.join()+", 0);\n ++"+h[c-2]+";\n "+f+" sourceLocA = "+f+"("+h.join()+", 0);\n --"+h[c-1]+";\n "+f+" sourceLocB = "+f+"("+h.join()+", 0);\n --"+h[c-2]+";"}else s=c,i="\n "+l+" sourceLocR = coords;\n ++"+h[c-1]+";\n "+l+" sourceLocG = coords;\n ++"+h[c-2]+";\n "+l+" sourceLocA = coords;\n --"+h[c-1]+";\n "+l+" sourceLocB = coords;\n --"+h[c-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),p="."+d[s-1],v=d.map((function(t){return"int "+t})),m=sa("sourceLocR",s-1).concat("inIdx.r"),g=sa("sourceLocG",s-1).concat("inIdx.g"),y=sa("sourceLocB",s-1).concat("inIdx.b"),x=sa("sourceLocA",s-1).concat("inIdx.a"),b="max"===n?"greaterThan":"lessThan",w=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+")));",E="vec4(\n getAChannel("+m.join()+"),\n hasNextCol ? getAChannel("+g.join()+") : 0.,\n hasNextRow ? getAChannel("+y.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",R=r?"":"\n float getBestIndicesAChannel("+v.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+v.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+R+"\n void main() {\n "+l+" coords = getOutputCoords();\n bool hasNextCol = "+h[c-1]+" < "+(u[c-1]-1)+";\n bool hasNextRow = "+h[c-2]+" < "+(u[c-2]-1)+";\n "+i+"\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 = "+E+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+w+"\n vec4 candidate = "+E+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+b+"(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 "},Ia=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+c+", "+l+");\n const float avgMultiplier = float("+h+");\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 += "+a+") {\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+= "+i+") {\n float dyC = float(dyCCorner + wC) / "+o+".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 "},ka=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=l-1-t.padInfo.front,p=h-1-t.padInfo.top,v=f-1-t.padInfo.left,m=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+d+", "+p+", "+v+");\n const float avgMultiplier = float("+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+o+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+a+".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 for (int wC = 0; wC < "+f+";\n wC += "+c+") {\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(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Sa=function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Ro(t,e),Ro(t,n);var i="0.0";null!=r&&(Ro(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Ro(t,o),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 = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Aa=function(t,e,n,r,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Ro(t,e),Ro(t,n);var i="vec4(0.0)";null!=r&&(Ro(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Ro(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+i+";\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("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},Da="return areal * breal - aimag * bimag;",Ta="return areal * bimag + aimag * breal;",Na=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Ro(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},Fa="return a + b;",_a="return a - b;",Oa="return a * b;",Ma="return (a < 0.) ? b * a : a;",Ba=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Ro(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},Pa="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",La=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Ro(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===k(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+wa(o)+" coords = getOutputCoords();\n ",1===o)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var i=sa("coords",o);a+="\n bool nextRowOutOfBounds =\n ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+i[o-1]+" + 1) >= "+this.outputShape[o-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 "+a+"\n\n setOutput(result);\n }\n "},Wa=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ua=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\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(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Va=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 "},za=function(t){this.outputShape=[],this.outputShape=Sn(t,1),this.variableNames=t.map((function(t,e){return"T"+e}));var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var o=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+o+"));")}var a=e.length,i=e[e.length-1];r.push("else setOutput(getT"+a+"(yR, yC-"+i+"));"),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n "+r.join("\n ")+"\n }\n "},Ga=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Sn(t,e);var n=this.outputShape,r=n.length,o=wa(r),a=sa("coords",r),i=["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;u<s.length;u++)s[u]=s[u-1]+t[u][e];var c=i[e],l=i.slice(-2),h=i.join(),f="if ("+c+" < "+s[0]+") {\n return getChannel(\n getT0("+h+"), vec2("+l.join()+"));\n }";for(u=1;u<s.length;u++){var d=s[u-1];f+="\n if ("+c+" < "+s[u]+" && "+c+" >= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+Ha(i,c,d)+"),\n vec2("+Ha(l,c,d)+"));\n }"}var p=s.length,v=s[s.length-1];f+="\n return getChannel(\n getT"+p+"("+Ha(i,c,v)+"),\n vec2("+Ha(l,c,v)+"));",this.userCode="\n float getValue("+i.map((function(t){return"int "+t}))+") {\n "+f+"\n }\n\n void main() {\n "+o+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n\n "+a[r-1]+" = "+a[r-1]+" + 1;\n if ("+a[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+a+");\n }\n\n "+a[r-2]+" = "+a[r-2]+" + 1;\n if ("+a[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+a+");\n }\n\n "+a[r-1]+" = "+a[r-1]+" - 1;\n if ("+a[r-2]+" < "+n[r-2]+" &&\n "+a[r-1]+" < "+n[r-1]+") {\n result.b = getValue("+a+");\n }\n setOutput(result);\n }\n "};function Ha(t,e,n){var r=t.indexOf(e);return t.map((function(t,e){return e===r?t+" - "+n:t})).join()}var qa=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a="channelsLast"===t.dataFormat;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+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ka=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a="channelsLast"===t.dataFormat,i=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,c=a?2:3,l=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+l+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+c+"]) - 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) / "+o+".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\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},ja=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=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+" - "+o+";\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+" - "+a+";\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+" - "+i+";\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 "},Xa=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=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) / "+o+".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) / "+a+".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) / "+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 = "+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 "},Ya=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a=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 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: 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+" - "+o+";\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 "},$a=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\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) / "+o+".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 // TO DO: 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 "},Qa=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.padInfo.top,a=t.padInfo.left,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4,p="channelsLast"===t.dataFormat,v=p?1:2,m=p?2:3,g=p?3:1,y="",x="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",x="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+i+", "+s+");\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+g+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+v+"], coords["+m+"]) * 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 < "+l+"; 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 < "+h+"; 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 < "+f+"; d1 += 4) {\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 if ("+p+") {\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 dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===d)+") {\n\n if ("+p+") {\n dotProd +=\n getX(batch, xR, xC, "+f+") *\n getW(wR, wC, "+f+", d2);\n } else {\n dotProd +=\n getX(batch, "+f+", xR, xC) *\n getW(wR, wC, "+f+", d2);\n }\n\n } else if ("+(2===d)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2)\n );\n\n if ("+p+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===d)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+f+", d2),\n getW(wR, wC, "+f+" + 1, d2),\n getW(wR, wC, "+f+" + 2, d2)\n );\n\n if ("+p+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+f+"),\n getX(batch, xR, xC, "+f+" + 1),\n getX(batch, xR, xC, "+f+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+f+", xR, xC),\n getX(batch, "+f+" + 1, xR, xC),\n getX(batch, "+f+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+b+"\n "+x+"\n setOutput(result);\n }\n "},Ja=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,h=t.filterHeight,f=t.filterWidth,d=4*Math.floor(t.inChannels/4),p=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+o+", "+a+", "+i+");\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 < "+h+"; 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 < "+f+"; 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 < "+d+"; 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, "+d+") *\n getW(wF, wR, wC, "+d+", d2);\n } else if ("+(2===p)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+d+"),\n getX(batch, xF, xR, xC, "+d+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+d+", d2),\n getW(wF, wR, wC, "+d+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===p)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+d+"),\n getX(batch, xF, xR, xC, "+d+" + 1),\n getX(batch, xF, xR, xC, "+d+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+d+", d2),\n getW(wF, wR, wC, "+d+" + 1, d2),\n getW(wF, wR, wC, "+d+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Za=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,p=t.outChannels/t.inChannels,v="",m="";n&&(v=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",m="result = activation(result);");var g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+v+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+p+";\n int q = d2 - d1 * "+p+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+f+"; wR++) {\n int xR = xRCorner + wR * "+l+";\n\n if (xR < 0 || xR >= "+o+") {\n continue;\n }\n\n for (int wC = 0; wC < "+d+"; wC++) {\n int xC = xCCorner + wC * "+h+";\n\n if (xC < 0 || xC >= "+a+") {\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\n float result = dotProd;\n "+g+"\n "+m+"\n setOutput(result);\n }\n "},ti=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,p=d,v="int xR; int xC; int xCOffset;",m=0;m<f;m++)for(var g=0;g<d;g++)v+="\n vec4 xTexelR"+m+"C"+2*g+" = vec4(0.);\n vec4 wR"+m+"C"+g+" = vec4(0.);\n vec4 xR"+m+"C"+g+" = vec4(0.);";for(m=0;m<f;m++)for(var y=0;y<p;y++){if(v+="\n xR = xRCorner + "+m*l+";\n xC = xCCorner + "+(g=2*y)*h+";\n ",1===c){if(g<d&&(v+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+a+") {\n xTexelR"+m+"C"+g+".zw = vec2(0.);\n }\n } else {\n xTexelR"+m+"C"+g+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if(xCOffset + 1 >= "+a+") {\n previous.zw = vec2(0.);\n }\n\n xR"+m+"C"+g+" = vec4(previous.zw, xTexelR"+m+"C"+g+".xy);\n } else {\n xR"+m+"C"+g+" = vec4(0, 0, xTexelR"+m+"C"+g+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+o+" && xC >= 0 && xC < "+a+") {\n xTexelR"+m+"C"+g+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+m+"C"+g+" = vec4(0.);\n }\n\n xR"+m+"C"+g+" = xTexelR"+m+"C"+g+";\n ",g+1<d)){var x=s%2==0?b(h):h;h%2==0&&s%2==1||h%2!=0&&s%2!=1?(v+="\n xCOffset = xC + "+s%2+" + "+x+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",h>1&&(v+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+m+"C"+g+" = vec4(0.);\n }\n "),v+="\n xR"+m+"C"+(g+1)+" = vec4(\n xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".xy);\n "):v+="\n xCOffset = xC + "+x+";\n\n if(xR >= 0 && xR < "+o+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+m+"C"+(g+1)+" = xTexelR"+m+"C"+(g+2)+";\n "}}else g<d&&(v+="\n if(xR >= 0 && xR < "+o+") {\n ",s%2==1?(v+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+m+"C"+g+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+a+") {\n xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+m+"C"+(g+2)+" = vec4(0.);\n }\n\n xR"+m+"C"+g+" = vec4(\n xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n ",g+1<d&&(v+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+m+"C"+(g+1)+" = vec4(xTexelR"+m+"C"+(g+2)+".xy, final.xy);\n ")):(v+="\n if(xC >= 0 && xC < "+a+") {\n xTexelR"+m+"C"+g+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+m+"C"+g+" = vec4(0.);\n }\n\n xCOffset = xC + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+m+"C"+(g+2)+" = vec4(0.);\n }\n\n xR"+m+"C"+g+" = vec4(\n xTexelR"+m+"C"+g+".xy, xTexelR"+m+"C"+(g+2)+".xy);\n ",g+1<d&&(v+="\n xR"+m+"C"+(g+1)+" = vec4(\n xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n ")),v+="}");g<d&&(v+="\n vec4 wTexelR"+m+"C"+g+" = getW("+m+", "+g+", d1, q);\n wR"+m+"C"+g+" = vec4(wTexelR"+m+"C"+g+".xz, wTexelR"+m+"C"+g+".xz);\n ",g+1<d&&(v+="\n vec4 wTexelR"+m+"C"+(g+1)+" = getW("+m+", "+(g+1)+", d1, q);\n wR"+m+"C"+(g+1)+" =\n vec4(wTexelR"+m+"C"+(g+1)+".xz, wTexelR"+m+"C"+(g+1)+".xz);"))}for(m=0;m<f;m++)for(g=0;g<d;g++)v+="dotProd += xR"+m+"C"+g+" * wR"+m+"C"+g+";";var w="",C="";n&&(w=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",C="result = activation(result);");var E=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+w+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2;\n int q = 0;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n vec4 dotProd = vec4(0.);\n\n "+v+"\n\n vec4 result = dotProd;\n "+E+"\n "+C+"\n setOutput(result);\n }\n "},ei=function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=t[0],i=t[1],s=t[2],u=t[3],c=e[0],l=n[0],h=n[1];this.outputShape=[c,l,h,u];var f="bilinear"===r?1:0,d=[i-1+".0",s-1+".0"],p=d[0],v=d[1],m=l>1?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],g=m[0],y=m[1],x=m[2],b=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n const float height_ratio = float("+g+");\n const float width_ratio = float("+w+");\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 >= "+a+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+x+";\n if( in_y < 0.0 || in_y > "+p+" ) {\n setOutput(float("+o+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+v+" ) {\n setOutput(float("+o+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+f+" == 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 "},ni=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+wa(r)+" coords = getOutputCoords();\n int end = "+ri(r,"coords")+";\n float val = 0.0;\n for (int i = "+o+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+a+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+ri(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 "};function ri(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 oi=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=ua();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ca(["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 "},ai=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Vt.DENSE;var e=Yt(t),n=ua();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ca(["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 "},ii=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}(),si=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},ui=function(t){this.variableNames=["A"],this.outTexUsage=zt.DOWNLOAD;var e=ua();this.outputShape=t,this.userCode="\n "+ha+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},ci=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=zt.DOWNLOAD;var e=ua();this.outputShape=t,this.userCode="\n "+ha+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},li=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=ua(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n "+la(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".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("+i+", 0., 0., 0.);\n }\n "},hi=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=ua(),o=e[0],a=e[1];this.outputShape=t;var i="",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;i+="\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 = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".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 "+la(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 "+i+"\n\n "+r.output+" = "+s+";\n }\n "},fi="return real * expR - imag * expI;",di="return real * expI + imag * expR;",pi=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+o+";\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) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},vi=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}(),mi=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=wa(this.rank),a=function(t,e){var n=t.length;if(n>4)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"],o=[],a=0;a<t.length;a++)a===e?o.push("int(getIndices("+r[a]+"))"):o.push(""+r[a]);return o.join()}(t,n);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "};var gi=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=wa(e.length),o=wa(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+o+" 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 * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function yi(t,e){var n=ua();return oe(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 xi(t,e){return fe(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 bi(t,e){return de(t,e,new Uint16Array([0,1,2,2,1,3]))}function wi(t,e,n,r,o,a,i){ve(n,r);var s=pe(t,e),u=t.TEXTURE_2D;return Jt(t,e,(function(){return t.bindTexture(u,s)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)})),Jt(t,e,(function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)})),Jt(t,e,(function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)})),s}function Ci(t,e,n,r,o){var a=Xt(n,r);return wi(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function Ei(t,e,n,r,o){var a=Xt(n,r);return wi(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function Ri(t,e,n,r,o){var a=Xt(n,r);return wi(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Ii(t,e,n,r,o){var a=$t(n,r);return wi(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function ki(t,e,n,r,o){var a=$t(n,r);return wi(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function Si(t,e,n,r){return Jt(t,e,(function(){return t.bindBuffer(t.ARRAY_BUFFER,r)})),ge(t,e,n,"clipSpacePos",r,3,20,0)&&ge(t,e,n,"uv",r,2,20,12)}function Ai(t,e,n,r,o,a,i){var s,u,c;Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,c=i.internalFormatPackedFloat),s.set(a),Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,o,0,t.RGBA,u,s)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function Di(t,e,n,r){Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,n)})),r.data instanceof Uint8Array?Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)})):Jt(t,e,(function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)})),Jt(t,e,(function(){return t.bindTexture(t.TEXTURE_2D,null)}))}function Ti(t,e,n,r,o){var a=t.createBuffer();Jt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)}));var i=16*n*r;return Jt(t,e,(function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)})),Jt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)})),Jt(t,e,(function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)})),a}function Ni(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o}function Fi(t,e,n,r,o){var a=Xt(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return Jt(t,e,(function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)})),new Float32Array(u.buffer)}function _i(t,e,n,r,o,a,i,s){var u=t,c=new Float32Array(function(t,e){var n=$t(t,e);return n[0]*n[1]*4}(a,i));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 Oi(t,e,n,r){var o=new Float32Array(n*r*4);return Jt(t,e,(function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)})),o}var Mi=Object.freeze({createVertexShader:yi,createVertexBuffer:xi,createIndexBuffer:bi,createFloat32MatrixTexture:Ci,createFloat16MatrixTexture:Ei,createUnsignedBytesMatrixTexture:Ri,createPackedMatrixTexture:Ii,createFloat16PackedMatrixTexture:ki,bindVertexProgramAttributeStreams:Si,uploadDenseMatrixToTexture:Ai,uploadPixelDataToTexture:Di,createBufferFromOutputTexture:Ti,downloadFloat32MatrixFromBuffer:Ni,downloadByteEncodedFloatMatrixFromOutputTexture:Fi,downloadPackedMatrixFromBuffer:_i,downloadMatrixFromPackedOutputTexture:Oi}),Bi=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=i().getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Kt(e,t)):this.gl=jt(e);var n="WEBGL_color_buffer_float";if(1===i().getNumber("WEBGL_VERSION")){if(this.textureFloatExtension=re(this.gl,this.debug,"OES_texture_float"),Pe(this.gl,"OES_texture_half_float"))this.textureHalfFloatExtension=re(this.gl,this.debug,"OES_texture_half_float");else if(i().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Pe(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=re(this.gl,this.debug,"EXT_color_buffer_half_float");else if(i().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Pe(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Pe(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=xi(this.gl,this.debug),this.indexBuffer=bi(this.gl,this.debug),this.framebuffer=me(this.gl,this.debug),this.textureConfig=Qt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return i().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;Jt(e,this.debug,(function(){return e.finish()})),Jt(e,this.debug,(function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)})),Jt(e,this.debug,(function(){return e.deleteFramebuffer(t.framebuffer)})),Jt(e,this.debug,(function(){return e.bindBuffer(e.ARRAY_BUFFER,null)})),Jt(e,this.debug,(function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)})),Jt(e,this.debug,(function(){return e.deleteBuffer(t.indexBuffer)})),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Ci(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Ei(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Ri(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Di(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Ai(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ki(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Ii(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(Ee(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Jt(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 Fi(r.gl,r.debug,e,n,r.textureConfig)}))},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return _i(this.gl,t,0,0,0,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Ni(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Ti(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(i().getBool("WEBGL_FENCE_API_ENABLED")){var o=t,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(a,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=a}else i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,i().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 Oi(r.gl,r.debug,e,n)}))},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=ae(e,this.debug,t),r=yi(e,this.debug),o=ce(e,this.debug);return Jt(e,this.debug,(function(){return e.attachShader(o,r)})),Jt(e,this.debug,(function(){return e.attachShader(o,n)})),le(e,this.debug,o),this.debug&&he(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=Si(e,this.debug,this.program,this.vertexBuffer)),o},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Jt(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&&he(this.gl,this.debug,this.program),Jt(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?xe(this.gl,this.debug,t,e):be(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Jt(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(),we(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=$t(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a)},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&&he(this.gl,this.debug,this.program),Re(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Jt(t,this.debug,(function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)}))},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return t.gl.finish()}))},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=re(this.gl,this.debug,2===i().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===i().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(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o},t.prototype.endQuery=function(){if(2!==i().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 n(this,void 0,void 0,(function(){var e=this;return r(this,(function(n){switch(n.label){case 0:return[4,F((function(){return e.disposed||e.isQueryAvailable(t,i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}))];case 1:return n.sent(),[2,this.getQueryTime(t,i().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(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!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;e<t.length;++e){if(!t[e]())break}return e-1}(this.itemsToPoll.map((function(t){return t.isDoneFn}))),e=0;e<=t;++e){(0,this.itemsToPoll[e].resolveFn)()}this.itemsToPoll=this.itemsToPoll.slice(t+1)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||F((function(){return n.pollItems(),0===n.itemsToPoll.length}))},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),Ce(this.gl,this.debug,t,this.framebuffer),this.debug&&Re(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(Ce(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&Re(this.gl)):Ee(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;Ce(r,this.debug,t,this.framebuffer),this.debug&&Re(r),this.outputTexture=t,Jt(r,this.debug,(function(){return r.viewport(0,0,e,n)})),Jt(r,this.debug,(function(){return r.scissor(0,0,e,n)}))},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Jt(this.gl,this.debug,(function(){return o.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 Pi(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,o=e[n],a=o.shape;if(!S(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!S(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}}))}var Li=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,h=n.dataFormat,f=s.left,d=s.top,p=o*r,v=ua(),m="channelsLast"===h,g=m?0:1,y=m?1:2,x="",b=0;b<=1;b++)for(var w=0;w<=1;w++)x+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+b+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+i+" - "+d+";\n d0 = offsetY + "+l+" * (pos / "+p+");\n\n if(d0 < "+e[g]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+f+".);\n d1 = offsetX + "+c+" * (int(mod(float(pos), "+p+".) / "+o+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+o+".));\n\n if ("+m+") {\n innerDims = vec2(d1, ch);\n result["+(2*b+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*b+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+x+"\n\n "+v.output+" = result;\n }\n "},Wi=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 = -"+i+"; j <= "+i+"; 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 * "+a+";\n setOutput(val);\n }\n "},Ui=function(t,e,n,r,o){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=o,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("+o+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+o+");\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 "},Vi=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",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 - "+i+";\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 = - "+i+"; j <= "+i+"; 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 * "+a+";\n setOutput(result);\n }\n "},zi=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+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 < "+o+";\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 < "+a+"; 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 * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Gi=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=s-1-t.padInfo.front,h=u-1-t.padInfo.top,f=c-1-t.padInfo.left,d=s*u*c-1;this.userCode="\n const ivec3 pads = ivec3("+l+", "+h+", "+f+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+o+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".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 for (int wC = 0; wC < "+c+";\n wC += "+i+") {\n float dyC = float(dyCCorner + wC) / "+r+".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(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+d+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+c+" +\n wR * "+c+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Hi=function(t,e,n,r,o,a,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),c=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",h=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],d="",p="";a&&(d=i?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",p="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+d+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+c+");\n vec4 b = getMatrixB(rc.x, "+l+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+h[0]+" * "+f[0]+");\n result += ("+h[1]+" * "+f[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+v+"\n\n "+p+"\n\n setOutput(result);\n }\n "},qi=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}(),Ki=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 "},ji=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=sa("rc",e),r=wa(e),o=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=t-2;o<t;o++)r+=n[o]+" >= "+e[o],o<t-1&&(r+="||");return r}(e,t,n),a=function(t,e,n,r){if(1===t)return"";var o=r.slice(-2);return"\n int r = "+o[0]+";\n int c = "+o[1]+";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i<t;i++)a=e[e.length-1-i]+","+a;n.push(a)}return n}(n,e);return 1===n?"getA(rc),\n rc + 1 >= "+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("+o+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+i+"));\n }\n }\n "}};var Xi=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));var r=t.length,o=wa(r),a=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+o+" start = "+o+"("+a+");\n "+o+" end = "+o+"("+i+");\n\n void main() {\n "+o+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+o+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Yi=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((function(e,n){return e[0]+t[n]+e[1]}));for(var r=t.length,o=wa(r),a=e.map((function(t){return t[0]})).join(","),i=e.map((function(e,n){return e[0]+t[n]})).join(","),s=sa("rc",r),u=sa("source",r),c=s[r-1]+" < "+this.outputShape[r-1],l=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n if("+c+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+c+") {"],f=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",p=0,v=1===r?2:4;p<v;p++)d+="\n "+h[p]+"\n if ("+f+") {\n result["+p+"] = float("+n+");\n } else {\n "+o+" source = rc - start;\n result["+p+"] = getChannel(getX("+u.join()+"), "+l+");\n }\n ";d+=1===r?"} ":"}}",this.userCode="\n const "+o+" start = "+o+"("+a+");\n const "+o+" end = "+o+"("+i+");\n\n void main() {\n "+o+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+d+"\n setOutput(result);\n }\n "},$i=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var f="avg"===e,d="0.0";if(f||(d="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+o+", "+a+");\n const ivec2 pads = ivec2("+l+", "+h+");\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 += "+i+") {\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 v=4*Math.floor(r/4),m=r%4,g="\n if ("+f+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+a+");\n const ivec2 pads = ivec2("+l+", "+h+");\n const float initializationValue = "+d+";\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("+d+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+v+"; 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 "+g+"\n }\n\n int xC = xCCorner + "+v+";\n if ("+(1===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(2===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(3===m)+") {\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 "+g+"\n }\n }\n setOutput("+p+");\n }\n "}},Qi=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,h=t.effectiveFilterHeight,f=t.effectiveFilterWidth,d=t.padInfo.front,p=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;var m="avg"===e,g="0.0";if(m||(g="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+d+", "+p+", "+v+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+";\n wC += "+c+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\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 =\n wD * "+h+" * "+f+" +\n wR * "+f+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var x=4*Math.floor(r/4),b=r%4,w="\n if ("+m+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+d+", "+p+", "+v+");\n const float initializationValue = "+g+";\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 xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+g+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+l+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+x+"; wC += 4) {\n int xC = xCCorner + wC * "+c+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n getValue(batch, xD, xR, xC + 3 * "+c+", ch)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+x+";\n if ("+(1===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===b)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+c+", ch),\n getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n }\n "}},Ji=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var c=4*Math.floor(n/4),l=n%4,h="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",f="vec4";"all"===e?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",f="bvec4"):"any"===e&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",f="bvec4");var d="";o%n>0&&(d="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+d+"\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("+i+");\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 "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+h+"\n }\n\n int inIdx = inOffset + "+c+";\n if ("+(1===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(3===l)+") {\n "+f+" values = "+f+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+h+"\n }\n setOutput("+u+");\n }\n "},Zi=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n "+o+"\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 "+ca(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+la(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 "};var ts=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],d=1/h,p=1/f,v=2*Math.ceil(d)+2,m=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("+h+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+p+");\n\n const int winHeight = int("+v+");\n const int winWidth = int("+m+");\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), "+(o-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), "+(a-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 "},es=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],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("+a+".0, "+i+".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 "},ns=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],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("+a+".0, "+i+".0,\n "+i+".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 "},rs=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=c[0]/l[0],f=c[1]/l[1],d=1/h,p=1/f,v=2*Math.ceil(d)+2,m=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("+h+");\n const float widthScale = float("+f+");\n\n const float invHeightScale = float("+d+");\n const float invWidthScale = float("+p+");\n\n const int winHeight = int("+v+");\n const int winWidth = int("+m+");\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("+o+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+a+") - 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 "},os=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],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("+a+".0, "+i+".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 "},as=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(","),o=wa(n);this.userCode="\n void main() {\n "+o+" 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 "},is=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=sa("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=wa(n);function s(n){var r=t.map((function(r,o){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(o,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("+o+"){\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 "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(r.slice())+";\n if("+o+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+a+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+o+") {\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 "},ss=function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=wa(o.length),u=wa(a.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var f="getUpdates("+h+")",d=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+o+");\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 * "+d+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+f+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},us=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,c="\n sumValue += dot(values, segFilter);\n ",l="";o%n>0&&(l="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n ");var h="";o%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+o+") {\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 "+h+"\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 "+a+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\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 "},cs=function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<e.length;u++)s.push(""+a[u]),u<t&&i.push(""+a[u]);r=i.join(),o=s.join()}var c=wa(n);this.userCode="\n void main() {\n "+c+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n "},ls=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=wa(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return hs.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."+hs[e]+" = start["+e+"] + coords."+hs[e]+";"})).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+o+"));\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}(),hs=["x","y","z","w","u","v"];var fs=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=wa(this.rank),n=sa("coords",this.rank),r=sa("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n result.x = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+a+";\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 = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+a+";\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 "+i+"\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}(),ds=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=wa(n.length),a=wa(n.length),i="";if(1===r)i="coords * strides + begin";else{var s=0;i=n.map((function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"})).join(",")}this.userCode="\n "+o+" begin = "+o+"("+t+");\n "+o+" strides = "+o+"("+e+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+i+"));\n }\n "},ps=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,o=vs(e,n),a=ms(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===Gt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Gt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Gt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Gt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Gt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=ms(e,vs(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,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 vs(t,e){if(t===zt.UPLOAD)return Gt.PACKED_2X2_FLOAT32;if(t===zt.RENDER||null==t)return function(t){return i().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?Gt.PACKED_2X2_FLOAT32:Gt.UNPACKED_FLOAT32:t?Gt.PACKED_2X2_FLOAT16:Gt.UNPACKED_FLOAT16}(e);if(t===zt.DOWNLOAD||t===zt.PIXELS)return Gt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function ms(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var gs=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var o=wa(this.rank),a=function(t){var e=t.length;if(e>5)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=[],o=0;o<t.length;o++)r.push("imod("+n[o]+", "+t[o]+")");return r.join()}(t);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "};var ys=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var o=wa(this.rank),a=function(t){var e=t.length;if(e>6)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),o=0;o<t.length;o++)r[t[o]]=n[o];return r.join()}(e);this.userCode="\n void main() {\n "+o+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "};var xs=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=wa(this.rank),a=ia("rc",this.rank),i=new Array(this.rank);for(r=0;r<e.length;r++)i[e[r]]=a[r];var s="vec2("+i.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+n[this.rank-1],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = "+c+";\n if("+u+") {\n result[1] = "+c+";\n }\n --"+a[this.rank-1]+";\n if(++"+a[this.rank-2]+" < "+n[this.rank-2]+") {\n result[2] = "+c+";\n if("+u+") {\n result[3] = "+c+";\n }\n }\n setOutput(result);\n }\n "},bs=1.7580993408473768,ws=1.0507009873554805,Cs=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 "},Es="if (isnan(x)) return x;",Rs="return x;",Is="return abs(x);",ks=Es+"\n return (x < 0.0) ? 0.0 : x;\n",Ss=Es+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",As="return (x >= 0.0) ? x : (exp(x) - 1.0);",Ds="\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = "+bs+";\n float scale = "+ws+";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var Ts="return -x;",Ns="return ceil(x);",Fs="return floor(x);",_s="return exp(x);",Os="return exp(x) - 1.0;",Ms=Es+"\n return sin(x);\n",Bs=Es+"\n return cos(x);\n",Ps=Es+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n",Ls=Es+"\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n",Ws=Es+"\n return atan(x);\n",Us=Es+"return log(x + sqrt(x * x + 1.0));",Vs=Es+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",zs=Es+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Gs="return x;",Hs="return x;",qs="\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",Ks="\n vec4 result = min(x, vec4(6.)) * 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",js="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",Xs=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!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 "},Ys=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=sa("rc",e),r=wa(e),o=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),a=n.slice(-2),i=e<=1?"rc":"vec2("+a.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+o+");\n\n setOutput(getChannel(packedInput, "+i+"));\n }\n "},$s={};function Qs(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Hs:Rs;if("relu"===t)return e?qs:ks;if("elu"===t)return e?js:As;if("relu6"===t)return e?Ks:Ss;if("prelu"===t)return e?Pa:Ma;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var Js=600;var Zs=function(t){function o(e){var n,r=t.call(this)||this;if(r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!i().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var o=jt(i().getNumber("WEBGL_VERSION"));r.binaryCache=(n=i().getNumber("WEBGL_VERSION"))in $s?$s[n]:($s[n]={},$s[n]),r.gpgpu=new Bi(o),r.canvas=o.canvas,r.gpgpuCreatedLocally=!0}else r.gpgpu=e,r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new ps(r.gpgpu),r.numMBBeforeWarning=null==i().global.screen?1024:i().global.screen.height*i().global.screen.width*window.devicePixelRatio*Js/1024/1024,r.texData=new xo(r,Lt),r}return e(o,t),o.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},o.prototype.write=function(t,e,n){if(i().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:e,dtype:n,values:t,usage:zt.UPLOAD}),r},o.prototype.move=function(t,e,n,r){if(i().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:e,usage:zt.UPLOAD})},o.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,o=e.complexTensors,a=e.slice,i=e.shape,s=e.isPacked;if(null!=a){var u=void 0;u=s?new Xs(i,Gs):new Cs(i,Gs);var c=this.runWebGLProgram(u,[{dataId:t,shape:i,dtype:r}],r),l=this.readSync(c.dataId);return this.disposeData(c.dataId),l}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var h,f,d=null!=this.activeTimers;(d&&(h=et()),"complex64"===r)?f=Vo(o.real.dataSync(),o.imag.dataSync()):f=this.getValuesFromTexture(t);return d&&(this.downloadWaitMs+=et()-h),this.convertAndCacheOnCPU(t,f)},o.prototype.read=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,s,u,c,l,h,f,d,p,v,m,g,y,x,b,w,C,E,R;return r(this,(function(r){switch(r.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise((function(t){return e.push(t)}))];if(n=this.texData.get(t),o=n.values,a=n.shape,s=n.slice,u=n.dtype,c=n.complexTensors,l=n.isPacked,null!=s)return h=void 0,h=l?new Xs(a,Gs):new Cs(a,Gs),f=this.runWebGLProgram(h,[{dataId:t,shape:a,dtype:u}],u),d=this.read(f.dataId),this.disposeData(f.dataId),[2,d];if(null!=o)return[2,this.convertAndCacheOnCPU(t)];if(!i().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===i().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return p=null,"complex64"!==u&&i().get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(t),m=this.texData.get(v.dataId),p=(R=this.gpgpu).createBufferFromTexture.apply(R,[m.texture].concat(Yt(a)))),this.pendingRead.set(t,[]),"complex64"===u?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:r.sent(),r.label=2;case 2:return"complex64"!==u?[3,4]:[4,Promise.all([c.real.data(),c.imag.data()])];case 3:return y=r.sent(),x=y[0],b=y[1],g=Vo(x,b),[3,5];case 4:null==p?g=this.getValuesFromTexture(t):(w=k(a),g=this.gpgpu.downloadFloat32MatrixFromBuffer(p,w)),r.label=5;case 5:return null!=v&&this.disposeData(v.dataId),C=this.convertAndCacheOnCPU(t,g),E=this.pendingRead.get(t),this.pendingRead.delete(t),E.forEach((function(t){return t(C)})),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,C]}}))}))},o.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e<t.length;e++){var n=t[e];if(!ee(n)){if(i().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},o.prototype.getValuesFromTexture=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.isPacked,s=k(r);if(i().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var u=this.decode(t),c=this.texData.get(u.dataId),l=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[c.texture].concat(Yt(r))).subarray(0,s);return this.disposeData(u.dataId),l}var h=i().getBool("WEBGL_PACK")&&!0===a,f=h?Te(r):r,d=h?new ci(f):new ui(f),p=this.runWebGLProgram(d,[{shape:f,dtype:o,dataId:t}],"float32"),v=this.texData.get(p.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,s);return this.disposeData(p.dataId),m},o.prototype.time=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,s,u,c;return r(this,(function(r){switch(r.label){case 0:return e=this.activeTimers,n=[],o=!1,null==this.programTimersStack?(this.programTimersStack=n,o=!0):this.activeTimers.push(n),this.activeTimers=n,t(),a=I(this.activeTimers.map((function(t){return t.query}))).filter((function(t){return null!=t})),s=I(this.activeTimers.map((function(t){return t.name}))).filter((function(t){return null!=t})),this.activeTimers=e,o&&(this.programTimersStack=null),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[4,Promise.all(a)]:[3,2];case 1:return c=r.sent(),u.kernelMs=w(c),u.getExtraProfileInfo=function(){return c.map((function(t,e){return{name:s[e],ms:t}})).map((function(t){return t.name+": "+t.ms})).join(", ")},[3,3];case 2:u.kernelMs={error:"WebGL query timers are not supported in this environment."},r.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}}))}))},o.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},o.prototype.startTimer=function(){return i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:et(),endMs:null}},o.prototype.endTimer=function(t){return i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=et(),t)},o.prototype.getQueryTime=function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){return i().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]}))}))},o.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;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)}}},o.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,a=e.usage,i=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(o,r),this.textureManager.releaseTexture(n,o,a,i)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},o.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},o.prototype.getDataInfo=function(t){return this.texData.get(t)},o.prototype.getCPUBackend=function(){return i().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Lt.findBackend("cpu")),this.cpuBackend):null},o.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.size<e}))},o.prototype.getGPGPUContext=function(){return this.gpgpu},o.prototype.complex=function(t,e){var n=this.makeOutput(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Lt.keep(t.clone()),imag:Lt.keep(e.clone())},n},o.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},o.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},o.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===k(n))return Fn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,o=io(t.shape,e,n);if(r||!o){var a=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fs(n):new ls(n),s=a.getCustomSetupFunc(e);return this.compileAndRun(a,[t],null,s)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},o.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),o=this.makeOutput(n,t.dtype),a=this.texData.get(o.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var i=so(e,t.strides);r.slice&&(i+=r.slice.flatOffset),a.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),o},o.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var o=ro(e,n,r);if(o.some((function(t){return 0===t})))return Fn([],o);var a=new ds(e,r,o);return this.compileAndRun(a,[t])},o.prototype.reverse=function(t,e){var n=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new is(t.shape,e):new as(t.shape,e);return this.compileAndRun(n,[t])},o.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map((function(t){return Tn(t)})),r=t.map((function(t){return Nn(t)}));return Dn(this.concat(n,e),this.concat(r,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>i().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(t.length/2),a=this.concat(t.slice(0,o),e),s=this.concat(t.slice(o),e);return this.concat([a,s],e)}if(i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var u=new Ga(t.map((function(t){return t.shape})),e);return this.compileAndRun(u,t)}var c=Sn(t.map((function(t){return t.shape})),e),l=t.map((function(t){return t.as2D(-1,k(t.shape.slice(e)))})),h=new za(l.map((function(t){return t.shape})));return this.compileAndRun(h,l).reshape(c)},o.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Ts,t.dtype);var e=new Cs(t.shape,Ts);return this.compileAndRun(e,[t])},o.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,i,1),c=1===a?2:1,l=1===a?e.as3D(s,1,i):e;return this.multiply(u,l).sum(c,!0)}var h=Dt(t.dtype,e.dtype),f=new Hi(t.shape,[s,o,a],n,r);return this.compileAndRun(f,[t,e],h)},o.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],c=o?n.shape[1]:n.shape[2],l=e.shape[0],h=Dt(e.dtype,n.dtype),f=null!=a,d=null!=s,p=i?Qs(i,!0):null,v=new Hi(e.shape,[l,u,c],r,o,f,p,d),m=[e,n];return a&&m.push(a),s&&m.push(s),this.compileAndRun(v,m,h)},o.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new Na(Da,t.shape,e.shape),a=new Na(Ta,t.shape,e.shape),s=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],u=this.compileAndRun(o,s),c=this.compileAndRun(a,s),l=this.complex(u,c);return u.dispose(),c.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Oa,t.dtype);var h=new Ba(Oa,t.shape,e.shape);return this.compileAndRun(h,[t,e],t.dtype)},o.prototype.batchNormalization=function(t,e,n,r,o,a){var s=[t,e,n],u=null;null!=a&&(u=a.shape,s.push(a));var c=null;if(null!=o&&(c=o.shape,s.push(o)),i().getBool("WEBGL_PACK_NORMALIZATION")){var l=new Aa(t.shape,e.shape,n.shape,u,c,r);return this.compileAndRun(l,s)}var h=new Sa(t.shape,e.shape,n.shape,u,c,r);return this.compileAndRun(h,s)},o.prototype.localResponseNormalization4D=function(t,e,n,r,o){var a=i().getBool("WEBGL_PACK_NORMALIZATION")?new Vi(t.shape,e,n,r,o):new Wi(t.shape,e,n,r,o);return this.compileAndRun(a,[t])},o.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new Ui(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t])},o.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map((function(t){return ot(t)}));return ta(dr(t.shape,t.dtype,n),e)}var r=new gs(t.shape,e);return this.compileAndRun(r,[t])},o.prototype.pad=function(t,e,n){var r=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Yi(t.shape,e,n):new Xi(t.shape,e,n);return this.compileAndRun(r,[t])},o.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=i().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xs(t.shape,e):new ys(t.shape,e);return this.compileAndRun(n,[t])},o.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new mi(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},o.prototype.batchToSpaceND=function(t,e,n){C(t.rank<=4,(function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"}));var r=e.reduce((function(t,e){return t*e})),o=zr(t.shape,e,r),a=Gr(o.length,e.length),i=Hr(t.shape,e,r),s=qr(n,e.length),u=Kr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},o.prototype.spaceToBatchND=function(t,e,n){C(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})),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=zr(i.shape,e,r,!1),u=Gr(s.length,e.length,!1),c=Hr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},o.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],a=$r(o),i=new Ji({windowSize:a,inSize:o,batchSize:r},e),s=this.compileAndRun(i,[t],n);return 1===s.shape[1]?s:this.reduce(s,e,n)},o.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],o=t.shape[1];null!=n&&(r=n.shape[0],o=n.shape[1]);var a=$r(o),i=new aa({windowSize:a,inSize:o,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(i,s,"int32");return 1===u.shape[1]?u:this.argReduce(t,e,u)},o.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,o=$r(r[r.length-1]),a=new Ra(r,o,e,null==n),i=null==n?[t]:[t,n],s=this.compileAndRun(a,i,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},o.prototype.sum=function(t,e){Cn("sum",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o),i=Tt(t.dtype);return this.reduce(a,"sum",i).reshape(r)},o.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o),i=Tt(t.dtype);return this.reduce(a,"prod",i).reshape(r)},o.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=En([r],t.rank),a=t;null!=o&&(a=t.transpose(o),r=In(1,t.rank)[0]);var i=function(t,e,n){for(var r=[],o=t.length,a=0;a<o;a++)a!==e?r.push(t[a]):r.push(n);return r}(a.shape,r,n),s=k([a.shape[r]]),u=a.as2D(-1,s),c=Tt(t.dtype),l=this.segOpCompute(u,"unsortedSegmentSum",e,c,n).reshape(i);return null!=o&&(l=l.transpose(Rn(o))),l},o.prototype.segOpCompute=function(t,e,n,r,o){var a=t.shape[0],i=t.shape[1],s=function(t,e){var n,r=!1;for(t<=Yr?(n=t,r=!0):n=Y(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=Y(t,n+1);return n}(i,o),u=new us({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),c=this.compileAndRun(u,[t,n],r);return c.shape[1]===o?c:(n=Kn(0,o).tile([i/s]),this.segOpCompute(c,e,n,r,o))},o.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(Cn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!i().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=bn(t.shape,r),a=o[0],s=k(o[1]),u=t.as2D(-1,s);return this.argReduce(u,n).reshape(a)}return this.argReducePacked(t,n)},o.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},o.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},o.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 o=new ni(t.shape,n,r);return this.compileAndRun(o,[t])},o.prototype.equal=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Ba("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.notEqual=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Ba("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Ba("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.lessEqual=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Ba("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Ba("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.greaterEqual=function(t,e){if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Ba("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.logicalNot=function(t){var e=new Cs(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},o.prototype.logicalAnd=function(t,e){if(i().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 Ba("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.logicalOr=function(t,e){if(i().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 Ba("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},o.prototype.select=function(t,e,n){var r=new cs(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],Dt(e.dtype,n.dtype))},o.prototype.where=function(t){dn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return na(t.shape,e)},o.prototype.topk=function(t,e,n){return ea(t.dataSync(),t.shape,t.dtype,e)},o.prototype.min=function(t,e){Cn("min",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},o.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("\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 Ba("\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])},o.prototype.mod=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("\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 Ba("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},o.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);Cn("max",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},o.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("\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 Ba("\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])},o.prototype.all=function(t,e){Cn("all",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},o.prototype.any=function(t,e){Cn("any",e,t.rank);var n=bn(t.shape,e),r=n[0],o=k(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},o.prototype.realDivide=function(t,e){if(i().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(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0)}var n=new Ba("\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape);return this.compileAndRun(n,[t,e],"float32")},o.prototype.floorDiv=function(t,e){if(i().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 Ba("\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);return this.compileAndRun(n,[t,e],"int32")},o.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Fa);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=Dt(t.dtype,e.dtype);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Fa,n);var r=new Ba(Fa,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},o.prototype.packedUnaryOp=function(t,e,n){var r=new Xs(t.shape,e);return this.compileAndRun(r,[t],n)},o.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new La(n,t.shape,e.shape,o);return this.compileAndRun(a,[t,e],r)},o.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map((function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorInfo(t,a),u=r.makeComplexComponentTensorInfo(e,i),c=new Ba(n,t.shape,e.shape);return r.compileAndRun(c,[s,u],Dt(a.dtype,i.dtype))})),s=i[0],u=i[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},o.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},o.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>i().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 o=t.map((function(t){return t.dtype})).reduce((function(t,e){return Dt(t,e)})),a=t.map((function(t){return t.shape})),s=i().getBool("WEBGL_PACK")?new oa(t[0].shape,a):new ra(t[0].shape,a);return this.compileAndRun(s,t,o)},o.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,_a);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=Dt(t.dtype,e.dtype);if(i().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,_a,t.dtype);var r=new Ba(_a,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},o.prototype.pow=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("\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 // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\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 Ba("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),r=Dt(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},o.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Ns,t.dtype);var e=new Cs(t.shape,Ns);return this.compileAndRun(e,[t])},o.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Fs,t.dtype);var e=new Cs(t.shape,Fs);return this.compileAndRun(e,[t])},o.prototype.sign=function(t){var e=new Cs(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},o.prototype.isNaN=function(t){var e=new Cs(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},o.prototype.isInf=function(t){var e=new Cs(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},o.prototype.isFinite=function(t){var e=new Cs(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},o.prototype.round=function(t){var e=new Cs(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])},o.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,_s,t.dtype);var e=new Cs(t.shape,_s);return this.compileAndRun(e,[t])},o.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Os,t.dtype);var e=new Cs(t.shape,Os);return this.compileAndRun(e,[t])},o.prototype.softmax=function(t,e){var n=O([e],t.shape),r=this.max(t,n),o=wn(r.shape,n),a=this.subtract(t,r.reshape(o)),i=this.exp(a),s=this.sum(i,n).reshape(o);return this.realDivide(i,s)},o.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\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",t.dtype);var e=new Cs(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},o.prototype.log1p=function(t){var e=new Cs(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},o.prototype.sqrt=function(t){var e=new Cs(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},o.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Cs(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},o.prototype.reciprocal=function(t){var e=new Cs(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},o.prototype.relu=function(t){var e;return e=i().getBool("WEBGL_PACK")?new Xs(t.shape,qs):new Cs(t.shape,ks),this.compileAndRun(e,[t])},o.prototype.relu6=function(t){var e;return e=i().getBool("WEBGL_PACK")?new Xs(t.shape,Ks):new Cs(t.shape,Ss),this.compileAndRun(e,[t])},o.prototype.prelu=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La(Pa,t.shape,e.shape):new Ba(Ma,t.shape,e.shape);return this.compileAndRun(n,[t,e])},o.prototype.elu=function(t){if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,js,t.dtype);var e=new Cs(t.shape,As);return this.compileAndRun(e,[t])},o.prototype.eluDer=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("\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 Ba("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},o.prototype.selu=function(t){var e=new Cs(t.shape,Ds);return this.compileAndRun(e,[t])},o.prototype.int=function(t){var e=new Cs(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},o.prototype.clip=function(t,e,n){var r,o=(r=i().getBool("WEBGL_PACK_CLIP")?new Ua(t.shape):new Wa(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},o.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(i().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Is,t.dtype);var e=new Cs(t.shape,Is);return this.compileAndRun(e,[t])},o.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Va(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},o.prototype.sigmoid=function(t){var e=new Cs(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},o.prototype.softplus=function(t){var e=new Cs(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])},o.prototype.sin=function(t){var e=new Cs(t.shape,Ms);return this.compileAndRun(e,[t])},o.prototype.cos=function(t){var e=new Cs(t.shape,Bs);return this.compileAndRun(e,[t])},o.prototype.tan=function(t){var e=new Cs(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},o.prototype.asin=function(t){var e=new Cs(t.shape,Ps);return this.compileAndRun(e,[t])},o.prototype.acos=function(t){var e=new Cs(t.shape,Ls);return this.compileAndRun(e,[t])},o.prototype.atan=function(t){var e=new Cs(t.shape,Ws);return this.compileAndRun(e,[t])},o.prototype.atan2=function(t,e){var n=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("\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 Ba("\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])},o.prototype.sinh=function(t){var e=new Cs(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},o.prototype.cosh=function(t){var e=new Cs(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},o.prototype.tanh=function(t){var e=new Cs(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])},o.prototype.asinh=function(t){var e=new Cs(t.shape,Us);return this.compileAndRun(e,[t])},o.prototype.acosh=function(t){var e=new Cs(t.shape,Vs);return this.compileAndRun(e,[t])},o.prototype.atanh=function(t){var e=new Cs(t.shape,zs);return this.compileAndRun(e,[t])},o.prototype.erf=function(t){var e=new Cs(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 sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},o.prototype.step=function(t,e){var n=new Cs(t.shape,function(t){return void 0===t&&(t=0),Es+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},o.prototype.conv2dByMatMul=function(t,e,n,r,o,a){var s=t.shape,u=this.texData.get(t.dataId),c=n.inChannels,l=s[0]*s[1]*s[2],h=n.outChannels,f="channelsLast"===n.dataFormat,d=(1===l||1===h)&&c>1e3,p=s[2]%2!=0&&!!u.isPacked;if(d||!i().getBool("WEBGL_LAZILY_UNPACK")||!i().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!p){var v=f?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],m=this.reshape(t,[1,v,n.inChannels]),g=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:m,b:g,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),n.outShape)}var y=f?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),x={dataId:t.dataId,shape:[1,y,n.inChannels],dtype:t.dtype},b=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,C(_e(u.shape,x.shape),(function(){return"packed reshape "+u.shape+" to "+x.shape+" isn't free"}));var w=this.reshape(e,[1,n.inChannels,n.outChannels]),E=this.fusedBatchMatMul({a:x,b:w,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),R=this.texData.get(E.dataId);return C(R.isPacked,(function(){return"batchMatMul result is expected to be packed"})),u.shape=b,R.shape=n.outShape,Lt.makeTensorFromDataId(E.dataId,n.outShape,E.dtype)},o.prototype.conv2dWithIm2Row=function(t,e,n,r,o,a){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,c=n.outWidth,l=n.outHeight,h="channelsLast"===n.dataFormat,f=i*s*u,d=l*c,p=[f,d],v=t.squeeze([0]),m=e.reshape([1,f,-1]),g=new Li(p,v.shape,n),y=this.compileAndRun(g,[v]).reshape([1,p[0],p[1]]),x=null!=r,b=null!=a,w=o?Qs(o,!0):null,C=new Hi(y.shape,[1,d,n.outChannels],!0,!1,x,w,b),E=[y,m];r&&E.push(r),b&&E.push(a);var R=this.compileAndRun(C,E);return h?R.reshape([1,l,c,n.outChannels]):R.reshape([1,n.outChannels,l,c])},o.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,s=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,o,a,s);if(i().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,a,s);var u=null!=o,c=null!=s,l=a?Qs(a,!1):null,h=new Qa(r,u,l,c),f=[e,n];return o&&f.push(o),s&&f.push(s),this.compileAndRun(h,f)},o.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(i().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Qa(n);return this.compileAndRun(r,[t,e])},o.prototype.conv2dDerInput=function(t,e,n){var r=new Ka(n);return this.compileAndRun(r,[t,e])},o.prototype.conv2dDerFilter=function(t,e,n){var r=new qa(n);return this.compileAndRun(r,[t,e])},o.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,o=t.convInfo,a=t.bias,s=t.activation,u=t.preluActivationWeights,c=i().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,l=s?Qs(s,c):null,h=[n,r],f=null!=a,d=null!=u;return f&&h.push(a),d&&h.push(u),c?(e=new ti(o,f,l,d),this.compileAndRun(e,h)):(e=new Za(o,f,l,d),this.compileAndRun(e,h))},o.prototype.depthwiseConv2D=function(t,e,n){var r;return i().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new ti(n),this.compileAndRun(r,[t,e])):(r=new Za(n),this.compileAndRun(r,[t,e]))},o.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new $a(n);return this.compileAndRun(r,[t,e])},o.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Ya(n);return this.compileAndRun(r,[t,e])},o.prototype.conv3d=function(t,e,n){var r=new Ja(n);return this.compileAndRun(r,[t,e])},o.prototype.conv3dDerInput=function(t,e,n){var r=new Xa(n);return this.compileAndRun(r,[t,e])},o.prototype.conv3dDerFilter=function(t,e,n){var r=new ja(n);return this.compileAndRun(r,[t,e])},o.prototype.maxPool=function(t,e){var n=new $i(e,"max",!1);return this.compileAndRun(n,[t])},o.prototype.avgPool=function(t,e){var n=new $i(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},o.prototype.maxPoolBackprop=function(t,e,n,r){var o=new $i(r,"max",!0),a=this.compileAndRun(o,[e]),i=new zi(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},o.prototype.avgPoolBackprop=function(t,e,n){var r=new Ia(n);return this.compileAndRun(r,[t],e.dtype)},o.prototype.cast=function(t,e){return Po(t,e,this)},o.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},o.prototype.avgPool3d=function(t,e){var n=new Qi(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},o.prototype.avgPool3dBackprop=function(t,e,n){var r=new ka(n);return this.compileAndRun(r,[t],e.dtype)},o.prototype.maxPool3d=function(t,e){var n=new Qi(e,"max",!1);return this.compileAndRun(n,[t],"float32")},o.prototype.maxPool3dBackprop=function(t,e,n,r){var o=new Qi(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Gi(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},o.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!_e(t.shape,e)&&(null===n.texture||!_e(n.shape,e))){var r=this.packedReshape(t,e);return Lt.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return Lo(t,e)},o.prototype.resizeBilinear=function(t,e,n,r){var o=i().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ns(t.shape,e,n,r):new es(t.shape,e,n,r);return this.compileAndRun(o,[t],"float32")},o.prototype.resizeBilinearBackprop=function(t,e,n){var r=new ts(t,e,n);return this.compileAndRun(r,[t])},o.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new os(t.shape,e,n,r);return this.compileAndRun(o,[t])},o.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new rs(t,e,n);return this.compileAndRun(r,[t])},o.prototype.multinomial=function(t,e,n,r){var o=e?t:go(t),a=o.shape[0],i=o.shape[1],s=new qi(a,i,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],"int32",u)},o.prototype.oneHot=function(t,e,n,r){var o=new Ki(t.size,e,n,r);return this.compileAndRun(o,[t])},o.prototype.diag=function(t){var e=new si(t.size);return this.compileAndRun(e,[t])},o.prototype.nonMaxSuppression=function(t,e,n,r,o){return dn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),jo(t.dataSync(),e.dataSync(),n,r,o)},o.prototype.cropAndResize=function(t,e,n,r,o,a){var i=new ei(t.shape,e.shape,r,o,a);return this.compileAndRun(i,[t,e,n],"float32")},o.prototype.depthToSpace=function(t,e,n){C(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,c=i/(e*e),l=new ii("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},o.prototype.split=function(t,e,n){return Zo(t,e,n)},o.prototype.scatterND=function(t,e,n){var r=Zr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/i,i],l=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return Lo(Fn([]),n);var f=On(0),d=new ss(a,o,l.rank,h.rank,s,c);return this.compileAndRun(d,[h,l,f]).reshape(n)},o.prototype.sparseToDense=function(t,e,n,r){var o=Zr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,c=new ss(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},o.prototype.fft=function(t){return this.fftImpl(t,!1)},o.prototype.ifft=function(t){return this.fftImpl(t,!0)},o.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new pi(fi,t.shape,e),o=new pi(di,t.shape,e),a=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},o.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=jr(t,e),a=o[0],i=o[1],s=o[2],u=o[3],c=e.reshape([i,r]),l=t.reshape([t.size/s,s]),h=new gi(r,u,[i,s]);return this.compileAndRun(h,[l,c]).reshape(a)},o.prototype.fill=function(t,e,n){if("string"===(n=n||j(e))){var r=P(n,k(t));return r.fill(e),Lt.makeTensor(r,t,n,this)}var o=new vi(t,e),a=o.getCustomSetupFunc(e);return this.compileAndRun(o,[],n,a)},o.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)},o.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},o.prototype.linspace=function(t,e,n){return Wo(t,e,n)},o.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},o.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return Lt.makeTensorFromDataId(n,t,e,this)},o.prototype.unpackTensor=function(t){var e=new Ys(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},o.prototype.packTensor=function(t){var e=new ji(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},o.prototype.packedReshape=function(t,e){var n=[Ae(t.shape)].concat(De(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},o=[Ae(e)].concat(De(e)),a=new Zi(o,n),i=this.runWebGLProgram(a,[r],t.dtype,null,!0);return{dataId:i.dataId,shape:e,dtype:i.dtype}},o.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=Te(o);e=r?new ai(i):new oi(i);return{dtype:a,shape:o,dataId:this.runWebGLProgram(e,[{shape:i,dtype:a,dataId:t}],a,null,!0).dataId}},o.prototype.runWebGLProgram=function(t,e,n,r,o){var a=this;void 0===o&&(o=!1);var s=this.makeTensorInfo(t.outputShape,n),u=this.texData.get(s.dataId);if(t.packedOutput&&(u.isPacked=!0),t.outPackingScheme===Vt.DENSE){var c=Yt(t.outputShape);u.texShape=c.map((function(t){return 2*t}))}if(null!=t.outTexUsage&&(u.usage=t.outTexUsage),0===k(s.shape))return u.values=B(s.dtype,0),s;var l=[],h=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=a.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&k(e.shape)<=i().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?a.unpackTensor(e):a.packTensor(e),l.push(e),n=a.texData.get(e.dataId);else if(n.isPacked&&!_e(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=a.packedReshape(e,o),l.push(e),n=a.texData.get(e.dataId),r.shape=o}return a.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}}));this.uploadToGPU(s.dataId);var f,d={shape:s.shape,texData:u,isUniform:!1},p=function(t,e,n){var r="";e.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 o=t.userCode,a=t.constructor.name;return a+="_"+r+"_"+o}(t,h,d),v=this.getAndSaveBinary(p,(function(){return function(t,e,n,r){var o=e.userCode,a=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}})),s=a.map((function(t){return t.shapeInfo})),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=fa(a,u,o,e.packedInputs),l=t.createProgram(c),h=null,f=t.getUniformLocation(l,"NAN",!1);1===i().getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(l,"INFINITY",!1));for(var d={},p=0;p<e.variableNames.length;p++){var v=e.variableNames[p];d[v]=t.getUniformLocation(l,v,!1),d["offset"+v]=t.getUniformLocation(l,"offset"+v,!1)}return{program:e,source:c,webGLProgram:l,uniformLocations:d,inShapeInfos:s,outShapeInfo:u,infLoc:h,nanLoc:f}}(a.gpgpu,t,h,d)})),m=null!=this.activeTimers;if(m&&(f=this.startTimer()),function(t,e,n,r,o){Pi(e.inShapeInfos,n),Pi([e.outShapeInfo],[r]);var a=r.texData.texture,s=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(a,s[0],s[1]):t.setOutputMatrixTexture(a,s[0],s[1]),t.setProgram(e.webGLProgram),1===i().getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach((function(n,r){var o=e.program.variableNames[r],a=e.uniformLocations[o],i=e.uniformLocations["offset"+o];if(null!=a)if(n.isUniform)if(k(n.shape)<2)t.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(a,s)}else null!=n.texData.slice&&null!=i&&t.gl.uniform1i(i,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,a,r)})),null!=o&&o(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,v,h,d,r),l.forEach((function(t){return a.disposeData(t.dataId)})),m&&(f=this.endTimer(f),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(f)})),!i().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&!1===o){var g=this.unpackTensor(s);return this.disposeData(s.dataId),g}return s},o.prototype.compileAndRun=function(t,e,n,r,o){void 0===o&&(o=!1),n=n||e[0].dtype;var a=this.runWebGLProgram(t,e,n,r,o);return Lt.makeTensorFromDataId(a.dataId,a.shape,a.dtype)},o.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},o.prototype.getTextureManager=function(){return this.textureManager},o.prototype.dispose=function(){var t=this;if(!this.disposed){if(!i().getBool("IS_TEST"))Object.keys(this.binaryCache).forEach((function(e){t.gpgpu.deleteProgram(t.binaryCache[e].webGLProgram),delete t.binaryCache[e]}));this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}},o.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Ze((function(){if(!i().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=i().getBool("DEBUG");i().set("DEBUG",!1);var n=t.abs(On(1e-8)).dataSync()[0];if(i().set("DEBUG",e),n>0)return 32}return 16}))),this.floatPrecisionValue},o.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},o.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var c,l=null!=this.activeTimers;l&&(c=et());var h=n.texShape;if(null==h&&(h=Ne(r,u),n.texShape=h),null!=a){var f=Te(r),d=void 0,p=h[1],v=h[0],m=a instanceof Uint8Array;u?(p=(e=$t(h[0],h[1]))[0],v=e[1],d=new hi(f,[v,p],m)):d=new li(f,[v,p],m);var g=this.makeTensorInfo([v,p],o);this.texData.get(g.dataId).usage=m?zt.PIXELS:zt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),p,v,a);var y=this.runWebGLProgram(d,[g],o,null,!0),x=this.texData.get(y.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(g.dataId),this.texData.delete(y.dataId),n.values=null,l&&(this.uploadWaitMs+=et()-c)}else{var b=this.acquireTexture(h,s,o,u);n.texture=b}}},o.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;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,r)),n.values},o.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},o.prototype.computeBytes=function(t,e){return t[0]*t[1]*z(e)},o}(bo);Wt()&&Lt.registerBackend("webgl",(function(){return new Zs}),2);var tu=An({square_:function(t){var e=mn(t,"x","square"),n=[e];return Lt.runKernelFunc((function(t,n){return n([e]),t.square(e)}),{x:e},null,"Square",{},n,[])}}),eu="SquaredDifference";var nu=An({squaredDifference_:function(t,e){var n,r=mn(t,"a","squaredDifference"),o=mn(e,"b","squaredDifference");n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape);var a={a:r,b:o},i=[r,o];return Lt.runKernelFunc((function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n}),a,(function(t,e){var n=e[0],r=e[1],o=On(2);return{a:function(){return t.mul(n.sub(r).mul(o))},b:function(){return t.mul(r.sub(n).mul(o))}}}),eu,{},i,[])}});var ru=An({abs_:function(t){var e=mn(t,"x","abs");return"complex64"===e.dtype?Lt.runKernelFunc((function(t){return t.complexAbs(e)}),{$x:e}):Lt.runKernelFunc((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))}}}),"Abs")}}),ou=An({acos_:function(t){var e=mn(t,"x","acos");return Lt.runKernelFunc((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(On(1).sub(n.toFloat().square()).sqrt()).neg()}}}))}}),au=An({acosh_:function(t){var e=mn(t,"x","acosh");return Lt.runKernelFunc((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())}}}))}}),iu=An({asin_:function(t){var e=mn(t,"x","asin");return Lt.runKernelFunc((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(On(1).sub(n.toFloat().square()).sqrt())}}}))}}),su=An({asinh_:function(t){var e=mn(t,"x","asinh");return Lt.runKernelFunc((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(On(1).add(n.toFloat().square()).sqrt())}}}))}}),uu=An({atan_:function(t){var e=mn(t,"x","atan");return Lt.runKernelFunc((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))}}}))}}),cu=An({atanh_:function(t){var e=mn(t,"x","atanh");return Lt.runKernelFunc((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(On(1).sub(n.toFloat().square()))}}}))}}),lu=An({ceil_:function(t){var e=mn(t,"x","ceil");return Lt.runKernelFunc((function(t){return t.ceil(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),hu=An({clipByValue_:function(t,e,n){var r=mn(t,"x","clipByValue");C(e<=n,(function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}));var o=[r],a={min:e,max:n};return Lt.runKernelFunc((function(t,o){var a=t.clip(r,e,n);return o([r]),a}),{x:r},(function(t,r){var o=r[0];return{x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),Xn(t))}}}),"ClipByValue",a,o)}}),fu=An({cos_:function(t){var e=mn(t,"x","cos"),n=[e];return Lt.runKernelFunc((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)}}}),"Cos",{},n)}}),du=An({cosh_:function(t){var e=mn(t,"x","cosh");return Lt.runKernelFunc((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)}}}))}}),pu=An({erf_:function(t){var e=mn(t,"x","erf");return C("int32"===e.dtype||"float32"===e.dtype,(function(){return"Input dtype must be `int32` or `float32`."})),"int32"===e.dtype&&(e=e.toFloat()),Lt.runKernelFunc((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)))}}}))}}),vu=An({exp_:function(t){var e=mn(t,"x","exp");return Lt.runKernelFunc((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])}}}),"Exp",{},[],[!0])}}),mu=An({expm1_:function(t){var e=mn(t,"x","expm1");return Lt.runKernelFunc((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())}}}))}}),gu=An({floor_:function(t){var e=mn(t,"x","floor");return Lt.runKernelFunc((function(t){return t.floor(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),yu=An({log_:function(t){var e=mn(t,"x","log"),n=[e];return Lt.runKernelFunc((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())}}}),"Log",{},n)}}),xu=An({log1p_:function(t){var e=mn(t,"x","log1p");return Lt.runKernelFunc((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))}}}))}}),bu=An({logSigmoid_:function(t){var e=mn(t,"x","logSigmoid");return Lt.runKernelFunc((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())}}}))}}),wu=An({neg_:function(t){var e=mn(t,"x","neg"),n=[e];return Lt.runKernelFunc((function(t){return t.neg(e)}),{x:e},(function(t){return{x:function(){return t.neg()}}}),"Neg",{},n)}}),Cu=An({reciprocal_:function(t){var e=mn(t,"x","reciprocal");return Lt.runKernelFunc((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())}}}))}}),Eu=An({round_:function(t){var e=mn(t,"x","round");return Lt.runKernelFunc((function(t){return t.round(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Ru=An({rsqrt_:function(t){var e=mn(t,"x","rsqrt"),n=[e];return Lt.runKernelFunc((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()}}}),"Rsqrt",{},n)}}),Iu=An({sigmoid_:function(t){var e=mn(t,"x","sigmoid");return Lt.runKernelFunc((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(On(1).sub(n)))}}}),"Sigmoid")}}),ku=An({sign_:function(t){var e=mn(t,"x","sign");return Lt.runKernelFunc((function(t){return t.sign(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Su=An({isNaN_:function(t){var e=mn(t,"x","isNaN");return Lt.runKernelFunc((function(t){return t.isNaN(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Au=An({isInf_:function(t){var e=mn(t,"x","isInf");return Lt.runKernelFunc((function(t){return t.isInf(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Du=An({isFinite_:function(t){var e=mn(t,"x","isFinite");return Lt.runKernelFunc((function(t){return t.isFinite(e)}),{$x:e},(function(t){return{$x:function(){return Xn(t)}}}))}}),Tu=An({sin_:function(t){var e=mn(t,"x","sin"),n=[e];return Lt.runKernelFunc((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)}}}),"Sin",{},n)}}),Nu=An({sinh_:function(t){var e=mn(t,"x","sinh");return Lt.runKernelFunc((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)}}}))}}),Fu=An({softplus_:function(t){var e=mn(t,"x","softplus");return Lt.runKernelFunc((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())}}}))}}),_u=An({sqrt_:function(t){var e=mn(t,"x","sqrt");return Lt.runKernelFunc((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))}}}))}}),Ou=An({step_:function(t,e){void 0===e&&(e=0);var n=mn(t,"x","step");return Lt.runKernelFunc((function(t){return t.step(n,e)}),{$x:n},(function(t){return{$x:function(){return Xn(t)}}}))}}),Mu=An({tan_:function(t){var e=mn(t,"x","tan");return Lt.runKernelFunc((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())}}}))}}),Bu=An({tanh_:function(t){var e=mn(t,"x","tanh");return Lt.runKernelFunc((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 On(1).sub(n.square()).mulStrict(t)}}}),"Tanh",{},null,[!0])}});function Pu(t,e,n,r,o,a){var i,s,u=mn(t,"x","batchNorm"),c=mn(e,"mean","batchNorm"),l=mn(n,"variance","batchNorm");return null!=o&&(i=mn(o,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),C(2===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),C(2===c.rank||1===c.rank,(function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."})),C(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!=i&&C(2===i.rank||1===i.rank,(function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."})),null!=s&&C(2===s.rank||1===s.rank,(function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."})),Uu(u,c,l,s,i,a)}function Lu(t,e,n,r,o,a){var i,s,u=mn(t,"x","batchNorm"),c=mn(e,"mean","batchNorm"),l=mn(n,"variance","batchNorm");return null!=o&&(i=mn(o,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),C(3===u.rank,(function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."})),C(3===c.rank||1===c.rank,(function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."})),C(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!=i&&C(3===i.rank||1===i.rank,(function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."})),null!=s&&C(3===s.rank||1===s.rank,(function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."})),Uu(u,c,l,s,i,a)}function Wu(t,e,n,r,o,a){var i,s,u=mn(t,"x","batchNorm"),c=mn(e,"mean","batchNorm"),l=mn(n,"variance","batchNorm");return null!=o&&(i=mn(o,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),C(4===u.rank,(function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."})),C(4===c.rank||1===c.rank,(function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."})),C(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!=i&&C(4===i.rank||1===i.rank,(function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."})),null!=s&&C(4===s.rank||1===s.rank,(function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."})),Uu(u,c,l,s,i,a)}function Uu(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,c=mn(t,"x","batchNorm"),l=mn(e,"mean","batchNorm"),h=mn(n,"variance","batchNorm");null!=o&&(i=mn(o,"scale","batchNorm")),null!=r&&(s=mn(r,"offset","batchNorm")),C(l.rank===h.rank,(function(){return"Batch normalization gradient requires mean and variance to have equal ranks."})),C(null==s||l.rank===s.rank,(function(){return"Batch normalization gradient requires mean and offset to have equal ranks."})),C(null==i||l.rank===i.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;var f=[c,l,h,i];return Lt.runKernelFunc((function(t,e){var n=t.batchNormalization(u,Vu(l),Vu(h),a,Vu(i),Vu(s));return e([c,l,h,i]),n}),{x:c,mean:l,variance:h,scale:i,offset:s},(function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],c=null==s?On(1):s,l=Eo(o.shape,u.shape),h=[];if(1===o.rank){for(var f=0;f<u.shape.length-1;++f)h.push(u.shape[f]);h.push(1)}var d=r.sub(o),p=t.mul(c),v=Ru(i.add(On(a))),m=v.mul(v).mul(v).mul(On(-.5));return{x:function(){return 1===o.rank?t.mul(Lr(v.as4D(1,1,1,o.shape[0]),h)).mul(c).reshape(r.shape):t.mul(v).mul(c).reshape(r.shape)},mean:function(){var t=v.mul(On(-1)).mul(p);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},variance:function(){var t=m.mul(d).mul(p);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},scale:function(){var e=d.mul(v),n=t.mul(e);return 1===o.rank&&(n=n.sum(l)),n.reshape(o.shape)},offset:function(){var e=t;return 1===o.rank&&(e=e.sum(l)),e.reshape(o.shape)}}}),"BatchNormalization",{varianceEpsilon:a},f).reshape(c.shape)}function Vu(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function zu(){Xe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var Gu=An({batchNormalization2d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),zu(),Pu(t,e,n,a,o,r)}}),Hu=An({batchNormalization3d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),zu(),Lu(t,e,n,a,o,r)}}),qu=An({batchNormalization4d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),zu(),Wu(t,e,n,a,o,r)}}),Ku=An({batchNormalization_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),zu(),Uu(t,e,n,a,o,r)}}),ju=An({batchNorm_:Uu}),Xu=An({batchNorm2d_:Pu}),Yu=An({batchNorm3d_:Lu}),$u=An({batchNorm4d_:Wu});var Qu=An({logicalAnd_:function(t,e){var n=mn(t,"a","logicalAnd","bool"),r=mn(e,"b","logicalAnd","bool");return Ro(n.shape,r.shape),Lt.runKernelFunc((function(t){return t.logicalAnd(n,r)}),{a:n,b:r},null,"LogicalAnd")}}),Ju=An({logicalNot_:function(t){var e=mn(t,"x","logicalNot","bool");return Lt.runKernelFunc((function(t){return t.logicalNot(e)}),{$x:e})}}),Zu=An({logicalOr_:function(t,e){var n=mn(t,"a","logicalOr","bool"),r=mn(e,"b","logicalOr","bool");return Ro(n.shape,r.shape),Lt.runKernelFunc((function(t){return t.logicalOr(n,r)}),{$a:n,$b:r})}}),tc=An({logicalXor_:function(t,e){var n=mn(t,"a","logicalXor","bool"),r=mn(e,"b","logicalXor","bool");return Ro(n.shape,r.shape),Zu(t,e).logicalAnd(Qu(t,e).logicalNot())}}),ec=An({where_:function(t,e,n){var r=mn(e,"a","where"),o=mn(n,"b","where"),a=mn(t,"condition","where","bool");return E(r.shape,o.shape,"Error in where: "),1===a.rank?C(a.shape[0]===r.shape[0],(function(){return"The first dimension of `a` must match the size of `condition`."})):E(a.shape,o.shape,"Error in where: "),Lt.runKernelFunc((function(t,e){var n=t.select(a,r,o);return e([a]),n}),{$condition:a,$a:r,$b:o},(function(t,e){var n=e[0];return{$condition:function(){return Xn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}}))}}),nc=function(t){return n(this,void 0,void 0,(function(){var e,n,o;return r(this,(function(r){switch(r.label){case 0:return[4,(e=mn(t,"condition","whereAsync","bool")).data()];case 1:return n=r.sent(),o=na(e.shape,n),t!==e&&e.dispose(),[2,o]}}))}))};var rc=An({add_:function(t,e){var n,r=mn(t,"a","add"),o=mn(e,"b","add");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t){return t.add(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Eo(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Eo(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}}),"Add")}}),oc=An({addN_:function(t){C(Array.isArray(t),(function(){return"The argument passed to tf.addN() must be a list of tensors"})),C(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 mn(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(!S(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));var r=e;return Lt.runKernelFunc((function(t){return t.addN(e)}),r,(function(t){var n={};return e.forEach((function(e,r){n[r]=function(){return t.clone()}})),n}),"AddN")}}),ac=An({addStrict_:function(t,e){var n=mn(t,"a","addStrict"),r=mn(e,"b","addStrict");return E(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),ic=An({atan2_:function(t,e){var n,r=mn(t,"a","atan2"),o=mn(e,"b","atan2");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.atan2(r,o);return e([r,o]),n}),{$a:r,$b:o},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=rc(n.square(),r.square()),o=t.mul(r.div(e)),i=Eo(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$b:function(){var e=rc(n.square(),r.square()),o=wu(t.mul(n.div(e))),i=Eo(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}}))}}),sc=An({div_:function(t,e){var n,r=mn(t,"a","div"),o=mn(e,"b","div");if(n=Nt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return lc(r,o);var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.realDivide(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),o=Eo(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Eo(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"Div")}}),uc=An({divNoNan_:function(t,e){var n,r=mn(t,"a","div"),o=mn(e,"b","div");r=(n=Nt(r,o))[0],o=n[1];var a=sc(r,o),i=Xn(a),s=o.equal(i);return ec(s,i,a)}}),cc=An({divStrict_:function(t,e){var n=mn(t,"a","div"),r=mn(e,"b","div");return E(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),lc=An({floorDiv_:function(t,e){var n,r=mn(t,"a","floorDiv"),o=mn(e,"b","floorDiv");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),o=Eo(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Eo(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}}),"FloorDiv")}}),hc=An({maximum_:function(t,e){var n,r=mn(t,"a","maximum"),o=mn(e,"b","maximum");return n=Nt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Ro(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.maximum(r,o);return e([r,o]),n}),{a:r,b:o},(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())}}}),"Maximum")}}),fc=An({maximumStrict_:function(t,e){var n=mn(t,"a","maximumStrict"),r=mn(e,"b","maximumStrict");return E(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),dc=An({minimum_:function(t,e){var n,r=mn(t,"a","minimum"),o=mn(e,"b","minimum");return n=Nt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Ro(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.minimum(r,o);return e([r,o]),n}),{a:r,b:o},(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())}}}),"Minimum")}}),pc=An({minimumStrict_:function(t,e){var n=mn(t,"a","minimumStrict"),r=mn(e,"b","minimumStrict");return E(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),vc=An({mod_:function(t,e){var n,r=mn(t,"a","mod"),o=mn(e,"b","mod");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.mod(r,o);return e([r,o]),n}),{$a:r,$b:o},(function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Eo(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Eo(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}}))}}),mc=An({modStrict_:function(t,e){var n=mn(t,"a","modStrict"),r=mn(e,"b","modStrict");return E(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),gc=An({mul_:function(t,e){var n,r=mn(t,"a","mul"),o=mn(e,"b","mul");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t,e){var n=t.multiply(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.mul(r.toFloat()),o=Eo(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=Eo(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}}),"Mul")}}),yc=An({mulStrict_:function(t,e){var n=mn(t,"a","mul"),r=mn(e,"b","mul");return E(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),xc=An({pow_:function(t,e){var n,r=mn(t,"base","pow"),o=mn(e,"exp","pow");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape),i=[r,o];return Lt.runKernelFunc((function(t,e){var n=t.pow(r,o);return e([r,o,n]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1],o=e[2];return{a:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(On(1))))),i=Eo(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},b:function(){var e=n.greater(0),i=n.log().where(e,Xn(n)),s=t.mul(o.mul(i)),u=Eo(r.shape,a);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}}),"Pow",{},i,[!0])}}),bc=An({powStrict_:function(t,e){return E(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),wc=An({squaredDifferenceStrict_:function(t,e){var n=mn(t,"a","squaredDifferenceStrict"),r=mn(e,"b","squaredDifferenceStrict");return E(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Cc=An({sub_:function(t,e){var n,r=mn(t,"a","sub"),o=mn(e,"b","sub");n=Nt(r,o),r=n[0],o=n[1];var a=Ro(r.shape,o.shape);return Lt.runKernelFunc((function(t){return t.subtract(r,o)}),{a:r,b:o},(function(t){return{a:function(){var e=t,n=Eo(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=Eo(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}}),"Sub")}}),Ec=An({subStrict_:function(t,e){var n=mn(t,"a","subStrict"),r=mn(e,"b","subStrict");return E(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var Rc=An({equal_:function(t,e){var n,r=mn(t,"a","equal"),o=mn(e,"b","equal");return n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.equal(r,o)}),{$a:r,$b:o})}}),Ic=An({equalStrict_:function(t,e){var n=mn(t,"a","equalStrict"),r=mn(e,"b","equalStrict");return E(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),kc=An({greater_:function(t,e){var n,r=mn(t,"a","greater"),o=mn(e,"b","greater");return n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.greater(r,o)}),{a:r,b:o},null,"Greater")}}),Sc=An({greaterEqual_:function(t,e){var n,r=mn(t,"a","greaterEqual"),o=mn(e,"b","greaterEqual");return n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.greaterEqual(r,o);return e([r,o]),n}),{a:r,b:o},(function(t,e){var n=e[0],r=e[1];return{a:function(){return Xn(n)},b:function(){return Xn(r)}}}),"GreaterEqual")}}),Ac=An({greaterEqualStrict_:function(t,e){var n=mn(t,"a","greaterEqualStrict"),r=mn(e,"b","greaterEqualStrict");return E(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),Dc=An({greaterStrict_:function(t,e){var n=mn(t,"a","greaterStrict"),r=mn(e,"b","greaterStrict");return E(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),Tc=An({less_:function(t,e){var n,r=mn(t,"a","less"),o=mn(e,"b","less");return n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.less(r,o)}),{a:r,b:o},null,"Less")}}),Nc=An({lessEqual_:function(t,e){var n,r=mn(t,"a","lessEqual"),o=mn(e,"b","lessEqual");return n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape),Lt.runKernelFunc((function(t,e){var n=t.lessEqual(r,o);return e([r,o]),n}),{a:r,b:o},null,"LessEqual")}}),Fc=An({lessEqualStrict_:function(t,e){var n=mn(t,"a","lessEqualStrict"),r=mn(e,"b","lessEqualStrict");return E(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),_c=An({lessStrict_:function(t,e){var n=mn(t,"a","lessStrict"),r=mn(e,"b","lessStrict");return E(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Oc=An({notEqual_:function(t,e){var n,r=mn(t,"a","notEqual"),o=mn(e,"b","notEqual");return n=Nt(r,o),r=n[0],o=n[1],Ro(r.shape,o.shape),Lt.runKernelFunc((function(t){return t.notEqual(r,o)}),{a:r,b:o},null,"NotEqual")}}),Mc=An({notEqualStrict_:function(t,e){var n=mn(t,"a","notEqualStrict"),r=mn(e,"b","notEqualStrict");return E(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Bc(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Pc(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e}var Lc=An({gather_:function(t,e,n){void 0===n&&(n=0);var r=mn(t,"x","gather"),o=mn(e,"indices","gather","int32");n=O(n,r.shape)[0];var a=function(t,e,n){for(var r=t.shape[n],o=[],a=1,i=1,s=0;s<n;s++)o.push(t.shape[s]),a*=t.shape[s];for(s=0;s<e.rank;s++)o.push(e.shape[s]);for(s=n+1;s<t.rank;s++)o.push(t.shape[s]),i*=t.shape[s];return{batchSize:a,sliceSize:i,dimSize:r,outputShape:o}}(r,o,n);return Lt.runKernelFunc((function(t,e){var a=t.gather(r,o.flatten(),n);return e([o]),a}),{x:r,indices:o},(function(t,e){var o=e[0];return{x:function(){var e=r.shape,a=o.size,i=e.slice(0,n),s=i.length,u=e.slice(n,e.length).slice(1),c=u.length,l=Bc(0,s),h=Bc(s+1,s+1+c),f=Pc([i,[a],u]),d=t.reshape(f),p=o.reshape([a]),v=Pc([[s],l,h]),m=d.transpose(v),g=Wc(m,p,r.shape[n]),y=Rn(v);return g=g.transpose(y)},indices:function(){return o}}}),"Gather",{axis:n}).reshape(a.outputShape)}}),Wc=An({unsortedSegmentSum_:function(t,e,n){var r=mn(t,"x","unsortedSegmentSum"),o=mn(e,"segmentIds","unsortedSegmentSum","int32");return C(A(n),(function(){return"numSegments must be of dtype int"})),Lt.runKernelFunc((function(t,e){var a=t.unsortedSegmentSum(r,o,n);return e([o]),a}),{$x:r},(function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=hc(e,Xn(e)),r=Lc(t,n),o=Sc(e,On(0,"int32")),a=r.rank-o.rank,i=0;i<a;++i)o=wr(o,i+1);o=Qu(o,zn(r.shape,"bool"));var s=Xn(r);return ec(o,r,s)}(t,n)}}}))}});var Uc=function(t,e,o){return n(this,void 0,void 0,(function(){var n,a,i,s,u,c,l,h,f,d,p,v,m;return r(this,(function(r){switch(r.label){case 0:for(n=mn(t,"tensor","boolMask"),a=mn(e,"mask","boolMask","bool"),i=null==o?0:o,s=a.rank,u=n.shape,C(s>0,(function(){return"mask cannot be scalar"})),E(u.slice(i,i+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),c=1,l=i;l<i+s;l++)c*=u[l];return h=u.slice(0,i).concat([c],u.slice(i+s)),f=n.reshape(h),d=a.reshape([-1]),[4,nc(d)];case 1:return p=r.sent(),v=p.squeeze([1]),m=Lc(f,v,i),t!==n&&n.dispose(),e!==a&&a.dispose(),v.dispose(),f.dispose(),d.dispose(),p.dispose(),[2,m]}}))}))};function Vc(t,e,n,r,o,a,i){void 0===a&&(a="NHWC"),C(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var s=t,u=e,c=!1;3===e.rank&&(c=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),C(4===s.length,(function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."})),C(4===u.rank,(function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank})),C(4===n.rank,(function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}));var l="NHWC"===a?s[3]:s[1],h="NHWC"===a?u.shape[3]:u.shape[1];C(l===n.shape[2],(function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."})),C(h===n.shape[3],(function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+n.shape[3]+"."})),null!=i&&C(A(o),(function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var f=Bo(a),d=So(s,n.shape,r,1,o,i,!1,f),p=Lt.runKernelFunc((function(t,e){var r=t.conv2dDerInput(u,n,d);return e([n,u]),r}),{dy4D:u,filter:n},(function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return qc(t,n,r,o,a,1,i)},filter:function(){return jc(t,s,n.shape,r,o,a,i)}}}));return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function zc(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Gc(t,e,n,r,o){C(t.length===e.rank,(function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"}));var a=t,i=e,s=!1;4===e.rank&&(s=!0,i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),a=[1,t[0],t[1],t[2],t[3]]);var u=a[4],c=i.shape[4];C(5===a.length,(function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."})),C(5===i.rank,(function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank})),C(5===n.rank,(function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank})),C(u===n.shape[3],(function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."})),C(c===n.shape[4],(function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[4]+"."}));var l=Ao(a,n.shape,r,1,o),h=Lt.runKernelFunc((function(t){return t.conv3dDerInput(i,n,l)}),{dy5D:i});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var Hc=An({conv1d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NWC"),void 0===a&&(a=1);var s=mn(t,"x","conv1d"),u=mn(e,"filter","conv1d"),c=s,l=!1;2===s.rank&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),C(3===c.rank,(function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."})),C(3===u.rank,(function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."})),null!=i&&C(A(r),(function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."})),C(c.shape[2]===u.shape[1],(function(){return"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+u.shape[1]+"."})),C(Mo(n,a),(function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'"})),C("NWC"===o,(function(){return"Error in conv1d: got dataFormat of "+o+" but only NWC is currently supported."}));var h=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),f=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),d=qc(f,h,[1,n],r,"NHWC",[1,a],i);return l?d.as2D(d.shape[2],d.shape[3]):d.as3D(d.shape[0],d.shape[2],d.shape[3])}}),qc=An({conv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=mn(t,"x","conv2d"),u=mn(e,"filter","conv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(4===c.rank,(function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."})),C(4===u.rank,(function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."})),null!=i&&C(A(r),(function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var h="NHWC"===o?c.shape[3]:c.shape[1];C(h===u.shape[2],(function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."})),C(Mo(n,a),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}));var f=Bo(o),d=So(c.shape,u.shape,n,a,r,i,!1,f),p=[u,c],v=Lt.runKernelFunc((function(t,e){var n=t.conv2d(c,u,d);return e([u,c]),n}),{x:c,filter:u},(function(t,e){var i=e,s=i[0],u=i[1];return C(Oo(a),(function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"})),{x:function(){return Xc(u.shape,t,s,n,r,o)},filter:function(){return jc(u,t,s.shape,n,r,o)}}}),"Conv2D",d,p);return l?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),Kc=An({conv3d_:function(t,e,n,r,o,a){void 0===o&&(o="NDHWC"),void 0===a&&(a=[1,1,1]);var i=mn(t,"x","conv3d"),s=mn(e,"filter","conv3d"),u=i,c=!1;4===i.rank&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),C(5===u.rank,(function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."})),C(5===s.rank,(function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."})),C(u.shape[4]===s.shape[3],(function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."})),C(function(t,e){return zc(t)||zc(e)}(n,a),(function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),C("NDHWC"===o,(function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."}));var l=Ao(u.shape,s.shape,n,a,r),h=Lt.runKernelFunc((function(t,e){var n=t.conv3d(u,s,l);return e([u,s]),n}),{x:u,$filter:s},(function(t,e){C(zc(a),(function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"}));var o=e[0],i=e[1];return{x:function(){return Gc(o.shape,t,i,n,r)},$filter:function(){return function(t,e,n,r,o){var a=t;4===t.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var i=e;4===i.rank&&(i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]));C(5===a.rank,(function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+"."})),C(5===i.rank,(function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."})),C(5===n.length,(function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."})),C(a.shape[4]===n[3],(function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+"."})),C(i.shape[4]===n[4],(function(){return"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+n[4]+")."}));var s=Ao(a.shape,n,r,1,o);return Lt.runKernelFunc((function(t){return t.conv3dDerFilter(a,i,s)}),{x5D:a,dy5D:i})}(o,t,i.shape,n,r)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),jc=An({conv2dDerFilter_:function(t,e,n,r,o,a,i){void 0===a&&(a="NHWC");var s=t;3===t.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var u=e;3===u.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),C(4===s.rank,(function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."})),C(4===u.rank,(function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."})),C(4===n.length,(function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}));var c="NHWC"===a?s.shape[3]:s.shape[1],l="NHWC"===a?u.shape[3]:u.shape[1];C(c===n[2],(function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+n[2]+"."})),C(l===n[3],(function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+n[3]+")."})),null!=i&&C(A(o),(function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."}));var h=Bo(a),f=So(s.shape,n,r,1,o,i,!1,h);return Lt.runKernelFunc((function(t){return t.conv2dDerFilter(s,u,f)}),{x4D:s,dy4D:u})}}),Xc=An({conv2dDerInput_:Vc}),Yc=An({depthwiseConv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=mn(t,"x","depthwiseConv2d"),u=mn(e,"filter","depthwiseConv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),C(4===c.rank,(function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."})),C(4===u.rank,(function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."})),C(c.shape[3]===u.shape[2],(function(){return"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."})),null==a&&(a=[1,1]),C(Mo(n,a),(function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"})),null!=i&&C(A(r),(function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}));var h=So(c.shape,u.shape,n,a,r,i,!0),f=[c,u],d=Lt.runKernelFunc((function(t,e){var n=t.depthwiseConv2D(c,u,h);return e([c,u]),n}),{x:c,filter:u},(function(t,e){C(Oo(a),(function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+a+"'"}));var n=e[0],r=e[1];return{x:function(){return $c(n.shape,t,r,h)},filter:function(){return Qc(n,t,r.shape,h)}}}),"DepthwiseConv2dNative",h,f);return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}}),$c=An({depthwiseConv2dDerInput_:function(t,e,n,r){var o=e,a=!1;3===e.rank&&(a=!0,o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=Lt.runKernelFunc((function(t){return t.depthwiseConv2DDerInput(o,n,r)}),{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),Qc=An({depthwiseConv2dDerFilter_:function(t,e,n,r){var o=t;3===t.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var a=e;return 3===a.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Lt.runKernelFunc((function(t){return t.depthwiseConv2DDerFilter(o,a,r)}),{x4D:o,dy4D:a})}}),Jc=An({separableConv2d_:function(t,e,n,r,o,a,i){void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC");var s=mn(t,"x","separableConv2d"),u=mn(e,"depthwiseFilter","separableConv2d"),c=mn(n,"pointwiseFilter","separableConv2d"),l=s,h=!1;if(3===s.rank&&(h=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");C(4===l.rank,(function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."})),C(4===u.rank,(function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."})),C(4===c.rank,(function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."})),C(1===c.shape[0],(function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+c.shape[0]+"."})),C(1===c.shape[1],(function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."}));var f=u.shape[2],d=u.shape[3];C(c.shape[2]===f*d,(function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+f*d+", but got "+c.shape[2]+"."}));var p=Yc(l,u,r,o,i,a),v=qc(p,c,1,"valid",i);return h?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),Zc=An({conv2dTranspose_:function(t,e,n,r,o,a){return Vc(n,mn(t,"x","conv2dTranspose"),mn(e,"filter","conv2dTranspose"),r,o,"NHWC",a)}}),tl=An({conv3dTranspose_:function(t,e,n,r,o){return Gc(n,mn(t,"x","conv3dTranspose"),mn(e,"filter","conv3dTranspose"),r,o)}});var el=An({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=mn(t,"a","matMul"),i=mn(e,"b","matMul");o=Nt(a,i),a=o[0],i=o[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],u=r?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?a.shape[a.rank-1]:a.shape[a.rank-2],l=r?i.shape[i.rank-2]:i.shape[i.rank-1],h=a.shape.slice(0,-2),f=i.shape.slice(0,-2),d=k(h),p=k(f);C(a.rank>=2&&i.rank>=2&&a.rank===i.rank,(function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."})),C(S(h,f),(function(){return"Error in matMul: outer dimensions ("+h+") and ("+f+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."})),C(s===u,(function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."}));var v=a.shape.slice(0,-2).concat([c,l]),m=n?a.as3D(d,s,c):a.as3D(d,c,s),g=r?i.as3D(p,l,u):i.as3D(p,u,l),y={transposeA:n,transposeB:r};return Lt.runKernelFunc((function(t,e){var o=t.batchMatMul(m,g,n,r);return e([m,g]),o}),{a:m,b:g},(function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{a:function(){return t.matMul(i,!1,!1)},b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{a:function(){return i.matMul(t,!1,!0)},b:function(){return a.matMul(t,!1,!1)}}:{a:function(){return i.matMul(t,!0,!0)},b:function(){return t.matMul(a,!0,!0)}}:{a:function(){return t.matMul(i,!1,!0)},b:function(){return a.matMul(t,!0,!1)}}}),"BatchMatMul",y).reshape(v)}}),nl=An({dot_:function(t,e){var n=mn(t,"t1","dot"),r=mn(e,"t2","dot");C(!(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 o=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return C(o===a,(function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."})),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]))}}),rl=An({outerProduct_:function(t,e){var n=mn(t,"v1","outerProduct"),r=mn(e,"v2","outerProduct");return C(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))}});var ol=An({reverse_:function(t,e){var n=mn(t,"x","reverse");if(0===n.rank)return n.clone();var r=O(e,n.shape);return Lt.runKernelFunc((function(t){return t.reverse(n,r)}),{$x:n},(function(t){return{$x:function(){return t.reverse(r)}}})).reshapeAs(n)}}),al=An({reverse1d_:function(t){var e=mn(t,"x","reverse");return C(1===e.rank,(function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."})),ol(e,0)}}),il=An({reverse2d_:function(t,e){var n=mn(t,"x","reverse");return C(2===n.rank,(function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."})),ol(n,e)}}),sl=An({reverse3d_:function(t,e){var n=mn(t,"x","reverse");return C(3===n.rank,(function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."})),ol(n,e)}}),ul=An({reverse4d_:function(t,e){var n=mn(t,"x","reverse");return C(4===n.rank,(function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."})),ol(n,e)}});function cl(t,e,n,r,o,a){var i=mn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),C(4===s.rank,(function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."})),C(Mo(n,r),(function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"})),null!=a&&C(A(o),(function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=Io(s.shape,e,n,r,o,a);if(1===c.filterWidth&&1===c.filterHeight&&S(c.inShape,c.outShape))return i.clone();var l=[s],h=Lt.runKernelFunc((function(t,e){var n=t.maxPool(s,c);return e([s,n]),n}),{x:s},(function(t,a){var i=a[0],s=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=mn(t,"dy","maxPoolBackprop"),c=mn(e,"input","maxPoolBackprop"),l=mn(n,"output","maxPoolBackprop");C(c.rank===u.rank,(function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"})),null==a&&(a=[1,1]);C(Mo(o,a),(function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),C(4===u.rank,(function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."})),C(4===c.rank,(function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."})),null!=s&&C(A(i),(function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var h=Io(c.shape,r,o,a,i,s);return Lt.runKernelFunc((function(t){return t.maxPoolBackprop(u,c,l,h)}),{$dy:u,$input:c})}(t,i,s,e,n,r,o)}}}),"MaxPool",c,l);return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function ll(t,e,n,r,o,a){var i=mn(t,"x","avgPool","float32");null==r&&(r=[1,1]),C(Mo(n,r),(function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}));var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),C(4===s.rank,(function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."})),null!=a&&C(A(o),(function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."}));var c=Io(s.shape,e,n,r,o,a);if(1===c.filterWidth&&1===c.filterHeight&&S(c.inShape,c.outShape))return i.clone();var l=Lt.runKernelFunc((function(t){return t.avgPool(s,c)}),{x:s},(function(t){return{x:function(){return function(t,e,n,r,o,a){var i=mn(t,"dy","avgPoolBackprop"),s=mn(e,"input","avgPoolBackprop");C(s.rank===i.rank,(function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"})),null==o&&(o=[1,1]);C(Mo(r,o),(function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}));var u=s,c=i,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]));C(4===c.rank,(function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."})),C(4===u.rank,(function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}));var h=Io(u.shape,n,r,o,a),f=Lt.runKernelFunc((function(t){return t.avgPoolBackprop(c,u,h)}),{dy4D:c,input4D:u});if(l)return f.as3D(f.shape[1],f.shape[2],f.shape[3]);return f}(t,s,e,n,r,o)}}}),"AvgPool",c);return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}var hl=An({maxPool_:function(t,e,n,r,o){return cl(t,e,n,1,r,o)}}),fl=An({avgPool_:function(t,e,n,r,o){return ll(t,e,n,1,r,o)}}),dl=An({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=mn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),C(Mo(a,o),(function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"}));var c,l=Io(s.shape,e,a,o,r),h=[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)})),o=n.map((function(t,e){return t-r[e]}));return n.map((function(t,e){return[r[e],o[e]]}))}([l.filterHeight,l.filterWidth],h):[[0,0],[0,0]];var f=1===h[0]&&1===h[1],d=function(t,e,n){var r=n.map((function(t){return t[0]})),o=n.map((function(t){return t[1]})),a=t.concat(r,o),i=e.map((function(t,e){return(t-a[e]%t)%t})),s=o.map((function(t,e){return t+i[e]})),u=e.map((function(t,e){return[r[e],s[e]]})),c=e.map((function(t,e){return[0,i[e]]}));return[u,c]}([l.inHeight,l.inWidth],h,c),p=d[0],v=d[1],m=f?r:"valid",g=f?s:Mr(s,h,p),y=("avg"===n?function(){return ll(g,e,a,1,m)}:function(){return cl(g,e,a,1,m)})(),x=f?y:vr(y,h,v);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),pl=An({maxPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=mn(t,"x","maxPool3d"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),C(5===u.rank,(function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."})),C("NDHWC"===a,(function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),C(Mo(n,i),(function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&C(A(r),(function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=ko(u.shape,e,n,i,r,o,a),h=Lt.runKernelFunc((function(t,e){var n=t.maxPool3d(u,l);return e([u,n]),n}),{x:u},(function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=mn(t,"dy","maxPool3dBackprop"),c=mn(e,"input","maxPool3dBackprop"),l=mn(n,"output","maxPool3dBackprop"),h=u,f=c,d=l,p=!1;4===c.rank&&(p=!0,h=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),f=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),d=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]));C(5===h.rank,(function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."})),C(5===f.rank,(function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+f.rank+"."})),C(5===d.rank,(function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."})),null==a&&(a=[1,1,1]);C(Mo(o,a),(function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"})),null!=s&&C(A(i),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."}));var v=ko(f.shape,r,o,a,i,s),m=Lt.runKernelFunc((function(t){return t.maxPool3dBackprop(h,f,d,v)}),{dy5D:h,input5D:f});if(p)return m.as4D(m.shape[1],m.shape[2],m.shape[3],m.shape[4]);return m}(t,s,u,e,n,i,r,o)}}}));return c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),vl=An({avgPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=mn(t,"x","avgPool3d","float32"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),C(5===u.rank,(function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."})),C("NDHWC"===a,(function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a})),C(Mo(n,i),(function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"})),null!=o&&C(A(r),(function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}));var l=ko(u.shape,e,n,i,r,o,a),h=Lt.runKernelFunc((function(t){return t.avgPool3d(u,l)}),{x:u},(function(t){return{x:function(){return function(t,e,n,r,o,a,i){var s=mn(t,"dy","avgPool3dBackprop"),u=mn(e,"input","avgPool3dBackprop"),c=s,l=u,h=!1;4===u.rank&&(h=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),l=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]));C(5===c.rank,(function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."})),C(5===l.rank,(function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+l.rank+"."})),null==o&&(o=[1,1,1]);C(Mo(r,o),(function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"})),null!=i&&C(A(a),(function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."}));var f=ko(l.shape,n,r,o,a,i),d=Lt.runKernelFunc((function(t){return t.avgPool3dBackprop(c,l,f)}),{dy5D:c,input5D:l});if(h)return d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]);return d}(t,u,e,n,i,r,o)}}}));return h=h.cast(u.dtype),c?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}});var ml=An({slice_:function(t,e,n){var r,o,a=mn(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length<a.rank?e.concat(new Array(a.rank-e.length).fill(0)):e.slice()).forEach((function(t){C(-1!==t,(function(){return"slice() does not support negative begin indexing."}))})),o=(o=null==n?new Array(a.rank).fill(-1):"number"==typeof n?[n].concat(new Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(new Array(a.rank-n.length).fill(-1)):n).map((function(t,e){return t>=0?t:(C(-1===t,(function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."})),a.shape[e]-r[e])})),eo(a,r,o);var i=a.shape,s={begin:r,size:o};return Lt.runKernelFunc((function(t){return t.slice(a,r,o)}),{x:a},(function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],i[n]-r[n]-o[n]]);return{x:function(){return t.pad(e)}}}),"Slice",s)}}),gl=An({slice1d_:function(t,e,n){var r=mn(t,"x","slice1d");return C(1===r.rank,(function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"})),ml(r,[e],[n])}}),yl=An({slice2d_:function(t,e,n){var r=mn(t,"x","slice2d");return C(2===r.rank,(function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"})),ml(r,e,n)}}),xl=An({slice3d_:function(t,e,n){var r=mn(t,"x","slice3d");return C(3===r.rank,(function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"})),ml(r,e,n)}}),bl=An({slice4d_:function(t,e,n){var r=mn(t,"x","slice4d");return C(4===r.rank,(function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"})),ml(r,e,n)}});function wl(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(wn(e.shape,r))),t.rank<n.rank&&(t=t.reshape(wn(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o)}}}var Cl=An({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","all","bool"),o=O(e,r.shape),a=o,i=En(a,r.rank);null!=i&&(r=r.transpose(i),a=In(a.length,r.rank));var s=Lt.runKernelFunc((function(t){return t.all(r,a)}),{$x:r});if(n){var u=wn(s.shape,o);return s.reshape(u)}return s}}),El=An({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","any","bool"),o=O(e,r.shape),a=o,i=En(a,r.rank);null!=i&&(r=r.transpose(i),a=In(a.length,r.rank));var s=Lt.runKernelFunc((function(t){return t.any(r,a)}),{$x:r});if(n){var u=wn(s.shape,o);return s.reshape(u)}return s}}),Rl=An({argMax_:function(t,e){void 0===e&&(e=0);var n=mn(t,"x","argMax");null==e&&(e=0);var r=O(e,n.shape),o=En(r,n.rank);null!=o&&(n=n.transpose(o),r=In(r.length,n.rank));var a={axis:r[0]},i=[n];return Lt.runKernelFunc((function(t,e){var o=t.argMax(n,r[0]);return e([n]),o}),{x:n},(function(t,e){var n=e[0];return{x:function(){return Xn(n)}}}),"ArgMax",a,i)}}),Il=An({argMin_:function(t,e){void 0===e&&(e=0);var n=mn(t,"x","argMin");null==e&&(e=0);var r=O(e,n.shape),o=En(r,n.rank);return null!=o&&(n=n.transpose(o),r=In(r.length,n.rank)),Lt.runKernelFunc((function(t,e){var o=t.argMin(n,r[0]);return e([n]),o}),{$x:n},(function(t,e){var n=e[0];return{$x:function(){return Xn(n)}}}))}}),kl=An({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","logSumExp"),o=O(e,r.shape),a=r.max(o,!0),i=r.sub(a).exp().sum(o).log(),s=a.reshape(i.shape).add(i);if(n){var u=wn(s.shape,o);return s.reshape(u)}return s}}),Sl=An({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","max"),o=r,a=O(e,r.shape),i=a,s=En(i,r.rank);null!=s&&(r=r.transpose(s),i=In(i.length,r.rank));var u=[r],c=Lt.runKernelFunc((function(t,e){var n=t.max(r,i);return e([o,n]),n}),{x:r},(function(t,e){return wl(t,e[1],e[0],a,s)}),"Max",{axes:i},u,[!0]);if(n){var l=wn(c.shape,a);c=c.reshape(l)}return c}}),Al=An({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","mean"),o=O(e,r.shape),a=k(bn(r.shape,o)[1]);return vo((function(t){var r=On(a);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return o.forEach((function(t){n[t]=1})),e.reshape(n).mul(zn(t.shape,"float32")).div(a)}}}))(r)}}),Dl=An({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","min"),o=r,a=O(e,r.shape),i=a,s=En(i,r.rank);null!=s&&(r=r.transpose(s),i=In(i.length,r.rank));var u=[r],c=Lt.runKernelFunc((function(t,e){var n=t.min(r,i);return e([o,n]),n}),{x:r},(function(t,e){return wl(t,e[1],e[0],a,s)}),"Min",{axes:i},u,[!0]);if(n){var l=wn(c.shape,a);c=c.reshape(l)}return c}}),Tl=An({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=O(e,(t=mn(t,"x","moments")).shape),o=t.mean(r,n),a=o.shape;n||(a=wn(o.shape,r));var i=t.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(r,n)}}}),Nl=An({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=O(e,r.shape);return vo((function(t){var e=En(o,t.rank),r=o,a=t;null!=e&&(a=t.transpose(e),r=In(r.length,t.rank));var i=function(e){var n=t.shape.slice();return o.forEach((function(t){n[t]=1})),e.reshape(n).mul(zn(t.shape,"float32"))},s={axes:r},u=Lt.runKernelFunc((function(t){return t.sum(a,r)}),{x:a},(function(t){return{x:function(){return i(t)}}}),"Sum",s);if(n){var c=wn(u.shape,o);u=u.reshape(c)}return{value:u,gradFunc:i}}))(r)}}),Fl=An({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=mn(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=O(e,r.shape),a=En(o,r.rank),i=o,s=r;null!=a&&(s=r.transpose(a),i=In(i.length,r.rank));var u=Lt.runKernelFunc((function(t){return t.prod(s,i)}),{permutedX:s});if(n){var c=wn(u.shape,o);u=u.reshape(c)}return u}});var _l=An({elu_:function(t){var e=mn(t,"x","elu");return Lt.runKernelFunc((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 Lt.runKernelFunc((function(e){return e.eluDer(t,n)}),{dy:t,y:n})}}}))}}),Ol=An({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=mn(t,"x","leakyRelu");return hc(On(e).mul(n),n)}}),Ml=An({prelu_:function(t,e){var n=mn(t,"x","prelu"),r=mn(e,"alpha","prelu");return Lt.runKernelFunc((function(t,e){var o=t.prelu(n,r);return e([n,r]),o}),{x:n,alpha:r},(function(t,e){var n=e[0],r=e[1],o=n.greater(0);return{x:function(){return ec(o,t,t.mul(r))},alpha:function(){var e=ec(o,Xn(t),t.mul(n)),a=Eo(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}}),"Prelu")}}),Bl=An({relu_:function(t){var e=mn(t,"x","relu");return"bool"===e.dtype?e.toInt():Lt.runKernelFunc((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())}}}),"Relu")}}),Pl=An({relu6_:function(t){var e=mn(t,"x","relu6");return"bool"===e.dtype?e.toInt():Lt.runKernelFunc((function(t,n){var r=t.relu6(e);return n([e]),r}),{x:e},(function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{x:function(){return t.mulStrict(r.toFloat())}}}),"Relu6")}}),Ll=An({selu_:function(t){var e=mn(t,"x","selu");return Lt.runKernelFunc((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(On(0)),r=On(bs),o=On(ws),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return ec(e,a,i)}}}))}});var Wl=An({transpose_:function(t,e){var n=mn(t,"x","transpose");if(null==e&&(e=n.shape.map((function(t,e){return e})).reverse()),C(n.rank===e.length,(function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."})),e.forEach((function(t){C(t>=0&&t<n.rank,(function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e}))})),n.rank<=1)return n.clone();var r={perm:e};return Lt.runKernelFunc((function(t){return t.transpose(n,e)}),{x:n},(function(t){var n=Rn(e);return{x:function(){return t.transpose(n)}}}),"Transpose",r)}});var Ul=An({localResponseNormalization_:function(t,e,n,r,o){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===o&&(o=.5);var a=mn(t,"x","localResponseNormalization");C(4===a.rank||3===a.rank,(function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+a.rank+"."})),C(A(e),(function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."}));var i=a,s=!1;3===a.rank&&(s=!0,i=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=Lt.runKernelFunc((function(t,a){var s=t.localResponseNormalization4D(i,e,n,r,o);return a([i,s]),s}),{x4D:i},(function(t,a){var i=a[0],s=a[1];return{x4D:function(){return Lt.runKernelFunc((function(a){return a.LRNGrad(t,i,s,e,n,r,o)}),{})}}}));return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}});var Vl=An({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var o=function t(e,n,r){void 0===r&&(r=null);if(0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(On(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=mn(t,"x","norm"),e,n),a=o.shape;if(r){var i=O(n,t.shape);a=wn(o.shape,i)}return o.reshape(a)}});var zl=An({basicLSTMCell_:function(t,e,n,r,o,a){var i=mn(t,"forgetBias","basicLSTMCell"),s=mn(e,"lstmKernel","basicLSTMCell"),u=mn(n,"lstmBias","basicLSTMCell"),c=mn(r,"data","basicLSTMCell"),l=mn(o,"c","basicLSTMCell"),h=mn(a,"h","basicLSTMCell"),f=c.concat(h,1).matMul(s).add(u),d=f.shape[0],p=f.shape[1]/4,v=[d,p],m=f.slice([0,0],v),g=f.slice([0,p],v),y=f.slice([0,2*p],v),x=f.slice([0,3*p],v),b=m.sigmoid().mulStrict(g.tanh()).addStrict(l.mulStrict(i.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w]}}),Gl=An({multiRNNCell_:function(t,e,n,r){for(var o=mn(e,"data","multiRNNCell"),a=gn(n,"c","multiRNNCell"),i=gn(r,"h","multiRNNCell"),s=o,u=[],c=0;c<t.length;c++){var l=t[c](s,a[c],i[c]);u.push(l[0]),u.push(l[1]),s=l[1]}var h=[],f=[];for(c=0;c<u.length;c+=2)h.push(u[c]),f.push(u[c+1]);return[h,f]}});var Hl=An({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var a=mn(t,"v","movingAverage"),i=mn(e,"x","movingAverage"),s=mn(n,"decay","movingAverage");Ft(a,i),C(S(a.shape,i.shape),(function(){return"Shape mismatch in v and x"}));var u=On(1),c=u.sub(s),l=i.sub(a).mul(c);if(o){C(null!=r,(function(){return"When using zeroDebias: true, step is required."}));var h=mn(r,"step","movingAverage");l=l.div(u.sub(xc(s,h)))}return a.add(l)}});var ql=An({stridedSlice_:function(t,e,n,r,o,a,i,s,u){if(void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==i)throw new Error("ellipsis mask is not yet supported");var c=mn(t,"x","stridedSlice"),l=no(s),h=c.shape.slice();l.forEach((function(t){e[t]=0,n[t]=1,h.splice(t,0,1)})),c=c.reshape(h);for(var f=0;f<c.rank;f++)e[f]=oo(o,e,r,c.shape,f),n[f]=ao(a,n,r,c.shape,f),r[f]=r[f]||1;var d=no(u);d.forEach((function(t){n[t]=e[t]+1,r[t]=1}));var p=ro(e,n,r),v=p.filter((function(t,e){return-1===d.indexOf(e)}));return r.every((function(t){return 1===t}))?ml(c,e,p).reshape(v):Lt.runKernelFunc((function(t){return t.stridedSlice(c,e,n,r)}),{$x:c}).reshape(v)}});var Kl=An({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=mn(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var o=r.shape[r.shape.length-1];if(e>o)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=Lt.runKernelFunc((function(t){return t.topk(r,e,n)}),{$x:r});return{values:a[0],indices:a[1]}}});var jl=An({scatterND_:function(t,e,n){var r=mn(t,"indices","scatterND","int32"),o=mn(e,"updates","scatterND");return Jr(o,r,n),Lt.runKernelFunc((function(t){return t.scatterND(r,o,n)}),{indices:r,updates:o},null,"ScatterNd",{shape:n})}});var Xl=An({fft_:function(t){C("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Lt.runKernelFunc((function(t){return t.fft(r)}),{input:t}).reshape(t.shape)}}),Yl=An({ifft_:function(t){C("complex64"===t.dtype,(function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."}));var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Lt.runKernelFunc((function(t){return t.ifft(r)}),{input:t}).reshape(t.shape)}}),$l=An({rfft_:function(t,e){C("float32"===t.dtype,(function(){return"The dtype for rfft() must be real value but got "+t.dtype}));var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&e<r){var a=t.shape.map((function(t){return 0})),i=t.shape.map((function(t){return t}));i[t.shape.length-1]=e,n=t.slice(a,i),r=e}else if(null!=e&&e>r){var s=t.shape.map((function(t){return t}));s[t.shape.length-1]=e-r,n=t.concat(Gn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=Dn(n,u).as2D(o,r),l=Xl(c),h=Math.floor(r/2)+1,f=Tn(l),d=Nn(l),p=f.split([h,r-h],f.shape.length-1),v=d.split([h,r-h],d.shape.length-1),m=n.shape.slice();return m[n.shape.length-1]=h,Dn(p[0],v[0]).reshape(m)}}),Ql=An({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=Yl(r);return Tn(o)}var a=[n,2*(e-1)],i=Tn(t).as2D(n,e),s=Nn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(On(-1)),l=i.concat(u,1),h=s.concat(c,1);return r=Dn(l,h).as2D(a[0],a[1]),o=Yl(r),Tn(o)}}),Jl=Object.freeze({fft:Xl,ifft:Yl,rfft:$l,irfft:Ql});var Zl=An({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=mn(t,"sparseIndices","sparseToDense","int32"),a=mn(e,"sparseValues","sparseToDense"),i=mn(r,"defaultValue","sparseToDense",a.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 o=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,n,i),Lt.runKernelFunc((function(t){return t.sparseToDense(o,a,n,i)}),{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});var th=An({gatherND_:function(t,e){var n=mn(e,"indices","gatherND","int32"),r=mn(t,"x","gatherND");return Lt.runKernelFunc((function(t){return t.gatherND(r,n)}),{x:r,indices:n},null,"GatherNd")}});var eh=An({diag_:function(t){var e=mn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Lt.runKernelFunc((function(t){return t.diag(e)}),{$x:e}).reshape(n)}});var nh=An({dropout_:function(t,e,n,r){var o=mn(t,"x","dropout");if(C("float32"===o.dtype,(function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."})),C(e>=0&&e<1,(function(){return"rate must be a float in the range [0, 1), but got "+e+"."})),0===e)return t instanceof wt?o.clone():o;var a=function(t,e){if(null==e)return t.shape.slice();if(S(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r<t.shape.length;r++)null==e[r]&&null!=t.shape[r]?n.push(t.shape[r]):n.push(e[r]);return n}return e}(o,n),i=1-e,s=_r(a,0,1,"float32",r).add(i).floor().div(i);return o.mul(s)}});function rh(t,e,n){for(var r=1-t%2,o=new Float32Array(t),a=0;a<t;++a){var i=2*Math.PI*a/(t+r-1);o[a]=e-n*Math.cos(i)}return Mn(o,"float32")}var oh=An({hannWindow_:function(t){return rh(t,.5,.5)}}),ah=An({hammingWindow_:function(t){return rh(t,.54,.46)}}),ih=An({frame_:function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=0);for(var a=0,i=[];a+e<=t.size;)i.push(ml(t,a,e)),a+=n;if(r)for(;a<t.size;){var s=a+e-t.size,u=Yn([ml(t,a,e-s),Hn([s],o)]);i.push(u),a+=n}return 0===i.length?Bn([],[0,e]):Yn(i).as2D(i.length,e)}}),sh=An({stft_:function(t,e,n,r,o){var a;void 0===o&&(o=oh),null==r&&(a=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var i=ih(t,e,n),s=gc(i,o(e)),u=[],c=0;c<i.shape[0];c++)u.push($l(s.slice([c,0],[1,e]),r));return Yn(u)}}),uh=Object.freeze({hannWindow:oh,hammingWindow:ah,frame:ih,stft:sh});var ch,lh=function(t,e,o){return void 0===o&&(o=1),n(this,void 0,void 0,(function(){var n,a,i,s,u,c,l,h,f,d,p,v,m,g;return r(this,(function(r){switch(r.label){case 0:return n=mn(t,"predictions","inTopK"),a=mn(e,"targets","inTopK"),C(n.rank>1,(function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+n.rank})),C(n.rank-1===a.rank,(function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+n.rank+" and targets rank "+a.rank})),E(n.shape.slice(0,n.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),i=n.shape[n.shape.length-1],C(o>0&&o<=i,(function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+i+"), but got "+o})),[4,n.data()];case 1:return s=r.sent(),[4,a.data()];case 2:for(u=r.sent(),c=[s.length/i,i],h=c[1],f=B("bool",l=c[0]),d=0;d<l;d++){for(p=d*h,v=s.subarray(p,p+h),m=[],g=0;g<v.length;g++)m.push({value:v[g],index:g});for(m.sort((function(t,e){return e.value-t.value})),f[d]=0,g=0;g<o;g++)if(m[g].index===u[d]){f[d]=1;break}}return t!==n&&n.dispose(),e!==a&&a.dispose(),[2,Fn(f,a.shape,"bool")]}}))}))};!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(ch||(ch={}));var hh=An({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=ch.SUM_BY_NONZERO_WEIGHTS);var o=mn(t,"labels","absoluteDifference"),a=mn(e,"predictions","absoluteDifference"),i=null;null!=n&&(i=mn(n,"weights","absoluteDifference")),E(o.shape,a.shape,"Error in absoluteDifference: ");var s=o.sub(a).abs();return fh(s,i,r)}}),fh=An({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=ch.SUM_BY_NONZERO_WEIGHTS);var r=mn(t,"losses","computeWeightedLoss"),o=null;null!=e&&(o=mn(e,"weights","computeWeightedLoss"));var a=null==o?r:r.mul(o);if(n===ch.NONE)return a;if(n===ch.SUM)return a.sum();if(n===ch.MEAN){if(null==o)return a.mean();var i=r.size/o.size,s=a.sum().div(o.sum());return i>1?s.div(On(i)):s}if(n===ch.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(On(r.size));var u=o.mul(zn(r.shape)).notEqual(On(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+n)}}),dh=An({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=ch.SUM_BY_NONZERO_WEIGHTS);var a=mn(t,"labels","cosineDistance"),i=mn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=mn(r,"weights","cosineDistance")),E(a.shape,i.shape,"Error in cosineDistance: ");var u=On(1).sub(a.mul(i).sum(n,!0));return fh(u,s,o)}}),ph=An({hingeLoss_:function(t,e,n,r){void 0===r&&(r=ch.SUM_BY_NONZERO_WEIGHTS);var o=mn(t,"labels","hingeLoss"),a=mn(e,"predictions","hingeLoss"),i=null;null!=n&&(i=mn(n,"weights","hingeLoss")),E(o.shape,a.shape,"Error in hingeLoss: ");var s=On(1);o=On(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return fh(u,i,r)}}),vh=An({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=ch.SUM_BY_NONZERO_WEIGHTS);var a=mn(t,"labels","huberLoss"),i=mn(e,"predictions","huberLoss"),s=null;null!=n&&(s=mn(n,"weights","huberLoss")),E(a.shape,i.shape,"Error in huberLoss: ");var u=On(r),c=i.sub(a).abs(),l=dc(c,u),h=c.sub(l),f=On(.5).mul(l.square()).add(u.mul(h));return fh(f,s,o)}}),mh=An({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=ch.SUM_BY_NONZERO_WEIGHTS);var a=mn(t,"labels","logLoss"),i=mn(e,"predictions","logLoss"),s=null;null!=n&&(s=mn(n,"weights","logLoss")),E(a.shape,i.shape,"Error in logLoss: ");var u=On(1),c=On(r),l=a.mul(i.add(c).log()).neg().sub(u.sub(a).mul(u.sub(i).add(c).log()));return fh(l,s,o)}}),gh=An({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=ch.SUM_BY_NONZERO_WEIGHTS);var o=mn(t,"labels","meanSquaredError"),a=mn(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=mn(n,"weights","meanSquaredError")),E(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return fh(s,i,r)}}),yh=An({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=ch.SUM_BY_NONZERO_WEIGHTS);var a=mn(t,"multiClassLabels","sigmoidCrossEntropy"),i=mn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=mn(n,"weights","sigmoidCrossEntropy")),E(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=On(r),c=On(1),l=On(.5);a=a.mul(c.sub(u)).add(l.mul(u))}var h=function(t,e){var n=mn(t,"labels","sigmoidCrossEntropyWithLogits"),r=mn(e,"logits","sigmoidCrossEntropyWithLogits");E(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i)}(a,i);return fh(h,s,o)}}),xh=An({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=ch.SUM_BY_NONZERO_WEIGHTS);var a=mn(t,"onehotLabels","softmaxCrossEntropy"),i=mn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=mn(n,"weights","softmaxCrossEntropy")),E(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=On(r),c=On(1),l=On(a.shape[1]);a=a.mul(c.sub(u)).add(u.div(l))}var h=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 vo((function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);r([t,a]);return{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=wn(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))]}}}))(t,e)}(a,i);return fh(h,s,o)}}),bh=Object.freeze({get Reduction(){return ch},absoluteDifference:hh,computeWeightedLoss:fh,cosineDistance:dh,hingeLoss:ph,huberLoss:vh,logLoss:mh,meanSquaredError:gh,sigmoidCrossEntropy:yh,softmaxCrossEntropy:xh});function wh(t,e){return void 0===e&&(e=!1),Lt.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],o=Cr(n),a=t.clone(),i=Bn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,c=function(t){var e,u=a,c=s,l=o;e=Lt.tidy((function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),c=a.slice([t,t],[1,1]),l=Bn([[-1]]).where(c.greater(0),Bn([[1]])),h=c.sub(l.mul(u)),f=e.div(h);s=1===f.shape[0]?i.clone():i.concat(f.slice([1,0],[f.shape[0]-1,f.shape[1]]),0);var d=l.matMul(h).div(u).neg(),p=a.slice([t,0],[n-t,r]),v=d.mul(s);if(0===t)a=p.sub(v.matMul(s.transpose().matMul(p)));else{var m=p.sub(v.matMul(s.transpose().matMul(p)));a=a.slice([0,0],[t,r]).concat(m,0)}var g=o.slice([0,t],[n,o.shape[1]-t]);if(0===t)o=g.sub(g.matMul(s).matMul(v.transpose()));else{var y=g.sub(g.matMul(s).matMul(v.transpose()));o=o.slice([0,0],[n,t]).concat(y,1)}return[s,a,o]})),s=e[0],a=e[1],o=e[2],tn([u,c,l])},l=0;l<u;++l)c(l);return!e&&n>r&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]}))}var Ch=An({bandPart_:function(t,e,n){if(e%1!=0)throw new Error("bandPart(): numLower must be an integer, got "+e+".");if(n%1!=0)throw new Error("bandPart(): numUpper must be an integer, got "+n+".");var r=mn(t,"a","bandPart");if(r.rank<2)throw new Error("bandPart(): Rank must be at least 2, got "+r.rank+".");var o=r.shape,a=r.shape.slice(-2),i=a[0],s=a[1];if(!(e<=i))throw new Error("bandPart(): numLower ("+e+") must not be greater than the number of rows ("+i+").");if(!(n<=s))throw new Error("bandPart(): numUpper ("+n+") must not be greater than the number of columns ("+s+").");e<0&&(e=i),n<0&&(n=s);var u=Kn(0,i,1,"int32").reshape([-1,1]),c=Kn(0,s,1,"int32"),l=Cc(u,c),h=Qu(l.lessEqual(On(+e,"int32")),l.greaterEqual(On(-n,"int32"))),f=Gn([i,s],r.dtype);return Pr(Ur(r.reshape([-1,i,s])).map((function(t){return ec(h,t,f)}))).reshape(o)}}),Eh=An({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,C(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){C(t[e].shape[0]===n,(function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"}))},o=1;o<t.length;++o)r(o)}else e=!0,t=tr(t,t.shape[0],0).map((function(t){return Br(t,[0])}));C(t.length<=t[0].shape[0],(function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."}));var a=[],i=t,s=function(t){a.push(Lt.tidy((function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=Nl(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r)}return e.div(Vl(e,"euclidean"))})))};for(o=0;o<t.length;++o)s(o);return e?Pr(a,0):a}}),Rh=An({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return wh(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce((function(t,e){return t*e})),r=Ur(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach((function(t){var n=wh(t,e),r=n[0],i=n[1];o.push(r),a.push(i)})),[Pr(o,0).reshape(t.shape),Pr(a,0).reshape(t.shape)]}}),Ih=Object.freeze({bandPart:Ch,gramSchmidt:Eh,qr:Rh});function kh(t,e,n,r,o,a){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY),null==a&&(a=0);var i=t.shape[0];return n=Math.min(n,i),C(0<=r&&r<=1,(function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"})),C(2===t.rank,(function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"})),C(4===t.shape[1],(function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]})),C(1===e.rank,(function(){return"scores must be a 1D tensor"})),C(e.shape[0]===i,(function(){return"scores has incompatible shape with boxes. Expected "+i+", but was "+e.shape[0]})),C(0<=a&&a<=1,(function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"})),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o,softNmsSigma:a}}var Sh=An({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=mn(t,"images","resizeBilinear");C(3===r.rank||4===r.rank,(function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."})),C(2===e.length,(function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."}));var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Lt.runKernelFunc((function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)}),{x:o},(function(t,e){return{x:function(){return Lt.runKernelFunc((function(r){return r.resizeBilinearBackprop(t,e[0],n)}),{})}}}),"ResizeBilinear",{alignCorners:n,newHeight:i,newWidth:s});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ah=An({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=mn(t,"images","resizeNearestNeighbor");C(3===r.rank||4===r.rank,(function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."})),C(2===e.length,(function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."})),C("float32"===r.dtype||"int32"===r.dtype,(function(){return"`images` must have `int32` or `float32` as dtype"}));var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Lt.runKernelFunc((function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)}),{batchImages:o},(function(t,e){return{batchImages:function(){return Lt.runKernelFunc((function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)}),{})}}}));return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Dh=An({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=mn(t,"boxes","nonMaxSuppression"),i=mn(e,"scores","nonMaxSuppression"),s=kh(a,i,n,r,o);n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold;var u={maxOutputSize:n,iouThreshold:r,scoreThreshold:o};return Lt.runKernelFunc((function(t){return t.nonMaxSuppression(a,i,n,r,o)}),{boxes:a,scores:i},null,"NonMaxSuppressionV3",u)}}),Th=function(t,e,o,a,i){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),n(this,void 0,void 0,(function(){var n,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return n=mn(t,"boxes","nonMaxSuppressionAsync"),s=mn(e,"scores","nonMaxSuppressionAsync"),u=kh(n,s,o,a,i),o=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,Promise.all([n.data(),s.data()])];case 1:return c=r.sent(),l=c[0],h=c[1],f=jo(l,h,o,a,i),n!==t&&n.dispose(),s!==e&&s.dispose(),[2,f]}}))}))},Nh=An({nonMaxSuppressionWithScore_:function(t,e,n,r,o,a){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),void 0===a&&(a=0);var i=mn(t,"boxes","nonMaxSuppression"),s=mn(e,"scores","nonMaxSuppression"),u=kh(i,s,n,r,o,a),c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:o=u.scoreThreshold,softNmsSigma:a=u.softNmsSigma},l=Lt.runKernel("NonMaxSuppressionV5",{boxes:i,scores:s},c);return{selectedIndices:l[0],selectedScores:l[1]}}}),Fh=function(t,e,o,a,i,s){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),void 0===s&&(s=0),n(this,void 0,void 0,(function(){var n,u,c,l,h,f,d;return r(this,(function(r){switch(r.label){case 0:return n=mn(t,"boxes","nonMaxSuppressionAsync"),u=mn(e,"scores","nonMaxSuppressionAsync"),c=kh(n,u,o,a,i,s),o=c.maxOutputSize,a=c.iouThreshold,i=c.scoreThreshold,s=c.softNmsSigma,[4,Promise.all([n.data(),u.data()])];case 1:return l=r.sent(),h=l[0],f=l[1],d=Xo(h,f,o,a,i,s),n!==t&&n.dispose(),u!==e&&u.dispose(),[2,d]}}))}))},_h=An({cropAndResize_:function(t,e,n,r,o,a){var i=mn(t,"image","cropAndResize"),s=mn(e,"boxes","cropAndResize","float32"),u=mn(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return C(4===i.rank,(function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."})),C(2===s.rank&&4===s.shape[1],(function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."})),C(1===u.rank&&u.shape[0]===c,(function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."})),C(2===r.length,(function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."})),C(r[0]>=1&&r[1]>=1,(function(){return"cropSize must be atleast [1,1], but was "+r})),C("bilinear"===o||"nearest"===o,(function(){return"method must be bilinear or nearest, but was "+o})),Lt.runKernelFunc((function(t,e){return t.cropAndResize(i,s,u,r,o,a)}),{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:r})}}),Oh=Object.freeze({resizeBilinear:Sh,resizeNearestNeighbor:Ah,nonMaxSuppression:Dh,nonMaxSuppressionAsync:Th,nonMaxSuppressionWithScore:Nh,nonMaxSuppressionWithScoreAsync:Fh,cropAndResize:_h}),Mh=function(t,e){return!(t>0)||"linear"===e},Bh=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},Ph=function(t,e){var n=e,r=Eo(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},Lh=function(t,e,n){if("linear"===e)return t;if("relu"===e)return Bl(t);if("elu"===e)return _l(t);if("relu6"===e)return Pl(t);if("prelu"===e)return Ml(t,n);throw new Error("Unknown fused activation "+e+".")};var Wh=An({fusedMatMul_:function(t){var e,n=t.a,r=t.b,o=t.transposeA,a=void 0!==o&&o,i=t.transposeB,s=void 0!==i&&i,u=t.bias,c=t.activation,l=void 0===c?"linear":c,h=t.preluActivationWeights;if(!1===Mh(Lt.state.gradientDepth,l)){var f=el(n,r,a,s);return null!=u&&(f=rc(f,u)),Lh(f,l,h)}var d=mn(n,"a","fused matMul"),p=mn(r,"b","fused matMul");e=Nt(d,p),d=e[0],p=e[1];var v=a?d.shape[d.rank-2]:d.shape[d.rank-1],m=s?p.shape[p.rank-1]:p.shape[p.rank-2],g=a?d.shape[d.rank-1]:d.shape[d.rank-2],y=s?p.shape[p.rank-2]:p.shape[p.rank-1],x=d.shape.slice(0,-2),b=p.shape.slice(0,-2),w=k(x),E=k(b);C(d.rank>=2&&p.rank>=2&&d.rank===p.rank,(function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+p.rank+"."})),C(S(x,b),(function(){return"Error in fused matMul: outer dimensions ("+x+") and ("+b+") of Tensors with shapes "+d.shape+" and "+p.shape+" must match."})),C(v===m,(function(){return"Error in fused matMul: inner shapes ("+v+") and ("+m+") of Tensors with shapes "+d.shape+" and "+p.shape+" and transposeA="+a+" and transposeB="+s+" must match."}));var R,I,A=d.shape.slice(0,-2).concat([g,y]),D=a?d.as3D(w,v,g):d.as3D(w,g,v),T=s?p.as3D(E,y,m):p.as3D(E,m,y);null!=u&&Ro(A,(R=Nt(R=mn(u,"bias","fused matMul"),d)[0]).shape),null!=h&&(I=mn(h,"prelu weights","fused matMul"));var N={a:D,b:T};null!=u&&(N.bias=R),null!=h&&(N.preluActivationWeights=I);var F=[D,T];return Lt.runKernelFunc((function(t,e){var n=t.fusedBatchMatMul({a:D,b:T,transposeA:a,transposeB:s,bias:R,activation:l,preluActivationWeights:I});return e([D,T,n]),n}),N,(function(t,e){var n=e[0],r=e[1],o=e[2],i=Bh(t,o,l),c={};return null!=u&&(c={bias:function(){return Ph(R,i)}}),a||s?!a&&s?Object.assign({a:function(){return i.matMul(r,!1,!1)},b:function(){return i.matMul(n,!0,!1)}},c):a&&!s?Object.assign({a:function(){return r.matMul(i,!1,!0)},b:function(){return n.matMul(i,!1,!1)}},c):Object.assign({a:function(){return r.matMul(i,!0,!0)},b:function(){return i.matMul(n,!0,!0)}},c):Object.assign({a:function(){return i.matMul(r,!1,!0)},b:function(){return n.matMul(i,!0,!1)}},c)}),"_FusedMatMul",{transposeA:a,transposeB:s,activation:l},F,[!0]).reshape(A)}}),Uh=An({fusedConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,h=t.activation,f=void 0===h?"linear":h,d=t.preluActivationWeights;if(f=f||"linear",!1===Mh(Lt.state.gradientDepth,f)){var p=qc(e,n,r,o,i,u,c);return null!=l&&(p=rc(p,l)),Lh(p,f,d)}var v=mn(e,"x","conv2d"),m=mn(n,"filter","conv2d"),g=v,y=!1;3===v.rank&&(y=!0,g=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),C(4===g.rank,(function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."})),C(4===m.rank,(function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."})),null!=c&&C(A(o),(function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."})),C(g.shape[3]===m.shape[2],(function(){return"Error in conv2d: depth of input ("+g.shape[3]+") must match input depth for filter "+m.shape[2]+"."})),C(Mo(r,u),(function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),C("NHWC"===i,(function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."}));var x,b,w=So(g.shape,m.shape,r,u,o,c);null!=l&&(x=Nt(x=mn(l,"bias","fused conv2d"),v)[0],Ro(w.outShape,x.shape)),null!=d&&(b=mn(d,"prelu weights","fused conv2d"));var E={x:g,filter:m};null!=l&&(E.bias=x),null!=d&&(E.preluActivationWeights=b);var R=[m,g],I=Lt.runKernelFunc((function(t,e){var n=t.fusedConv2d({input:g,filter:m,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([m,g,n]),n}),E,(function(t,e){var n=e,a=n[0],i=n[1],s=n[2],c=Bh(t,s,f);C(Oo(u),(function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"}));var h={};return null!=l&&(h={bias:function(){return Ph(x,c)}}),Object.assign({x:function(){return Xc(i.shape,c,a,r,o)},filter:function(){return jc(i,c,a.shape,r,o)}},h)}),"FusedConv2D",{convInfo:w,activation:f},R,[!0]);return y?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),Vh=An({fusedDepthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,h=t.activation,f=void 0===h?"linear":h,d=t.preluActivationWeights;if(!1===Mh(Lt.state.gradientDepth,f)){var p=Yc(e,n,r,o,i,u,c);return null!=l&&(p=rc(p,l)),Lh(p,f,d)}var v=mn(e,"x","depthwiseConv2d"),m=mn(n,"filter","depthwiseConv2d"),g=v,y=!1;3===v.rank&&(y=!0,g=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),C(4===g.rank,(function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."})),C(4===m.rank,(function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+m.rank+"."})),C(g.shape[3]===m.shape[2],(function(){return"Error in fused depthwiseConv2d: number of input channels ("+g.shape[3]+") must match the inChannels dimension in filter "+m.shape[2]+"."})),null==u&&(u=[1,1]),C(Mo(r,u),(function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"})),null!=c&&C(A(o),(function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."}));var x,b,w=So(g.shape,m.shape,r,u,o,c,!0);null!=l&&(x=Nt(x=mn(l,"bias","fused conv2d"),v)[0],Ro(w.outShape,x.shape)),null!=d&&(b=mn(d,"prelu weights","fused depthwiseConv2d"));var E={x:g,filter:m};null!=l&&(E.bias=x),null!=d&&(E.preluActivationWeights=b);var R=[m,g],I=Lt.runKernelFunc((function(t,e){var n=t.fusedDepthwiseConv2D({input:g,filter:m,convInfo:w,bias:x,activation:f,preluActivationWeights:b});return e([m,g,n]),n}),E,(function(t,e){C(Oo(u),(function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"}));var n=e[0],r=e[1],o=e[2],a=Bh(t,o,f),i={};return null!=l&&(i={bias:function(){return Ph(x,a)}}),Object.assign({x:function(){return $c(r.shape,a,n,w)},filter:function(){return Qc(r,a,n.shape,w)}},i)}),"FusedDepthwiseConv2D",{convInfo:w,activation:f},R,[!0]);return y?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),zh=Object.freeze({matMul:Wh,conv2d:Uh,depthwiseConv2d:Vh}),Gh=Object.freeze({image:Oh,linalg:Ih,losses:bh,spectral:Jl,fused:zh,signal:uh,square:tu,squaredDifference:nu,conv1d:Hc,conv2d:qc,conv3d:Kc,depthwiseConv2d:Yc,separableConv2d:Jc,conv2dTranspose:Zc,conv3dTranspose:tl,op:An,batchNormalization2d:Gu,batchNormalization3d:Hu,batchNormalization4d:qu,batchNormalization:Ku,batchNorm:ju,batchNorm2d:Xu,batchNorm3d:Yu,batchNorm4d:$u,booleanMaskAsync:Uc,complex:Dn,real:Tn,imag:Nn,concat:Yn,concat1d:$n,concat2d:Qn,concat3d:Jn,concat4d:Zn,split:tr,matMul:el,dot:nl,outerProduct:rl,reverse:ol,reverse1d:al,reverse2d:il,reverse3d:sl,reverse4d:ul,maxPool:hl,avgPool:fl,pool:dl,maxPool3d:pl,avgPool3d:vl,slice:ml,slice1d:gl,slice2d:yl,slice3d:xl,slice4d:bl,abs:ru,acos:ou,acosh:au,asin:iu,asinh:su,atan:uu,atanh:cu,ceil:lu,clipByValue:hu,cos:fu,cosh:du,erf:pu,exp:vu,expm1:mu,floor:gu,log:yu,log1p:xu,logSigmoid:bu,neg:wu,reciprocal:Cu,round:Eu,rsqrt:Ru,sigmoid:Iu,sign:ku,isNaN:Su,isInf:Au,isFinite:Du,sin:Tu,sinh:Nu,softplus:Fu,sqrt:_u,step:Ou,tan:Mu,tanh:Bu,all:Cl,any:El,argMax:Rl,argMin:Il,logSumExp:kl,max:Sl,mean:Al,min:Dl,moments:Tl,sum:Nl,prod:Fl,equal:Rc,equalStrict:Ic,greater:kc,greaterEqual:Sc,greaterEqualStrict:Ac,greaterStrict:Dc,less:Tc,lessEqual:Nc,lessEqualStrict:Fc,lessStrict:_c,notEqual:Oc,notEqualStrict:Mc,add:rc,addN:oc,addStrict:ac,atan2:ic,div:sc,divNoNan:uc,divStrict:cc,floorDiv:lc,maximum:hc,maximumStrict:fc,minimum:dc,minimumStrict:pc,mod:vc,modStrict:mc,mul:gc,mulStrict:yc,pow:xc,powStrict:bc,squaredDifferenceStrict:wc,sub:Cc,subStrict:Ec,elu:_l,leakyRelu:Ol,prelu:Ml,relu:Bl,relu6:Pl,selu:Ll,logicalAnd:Qu,logicalNot:Ju,logicalOr:Zu,logicalXor:tc,where:ec,whereAsync:nc,buffer:dr,print:pr,batchToSpaceND:vr,broadcastTo:mr,cast:gr,clone:yr,cumsum:xr,depthToSpace:br,expandDims:wr,eye:Cr,multinomial:Er,oneHot:Rr,pad:Ir,pad1d:kr,pad2d:Sr,pad3d:Ar,pad4d:Dr,rand:Tr,randomNormal:Nr,randomGamma:Fr,randomUniform:_r,reshape:Or,spaceToBatchND:Mr,squeeze:Br,stack:Pr,tile:Lr,truncatedNormal:Wr,unstack:Ur,setdiff1dAsync:Vr,fill:Hn,linspace:qn,ones:zn,range:Kn,scalar:On,tensor:Fn,tensor1d:Mn,tensor2d:Bn,tensor3d:Pn,tensor4d:Ln,tensor5d:Wn,tensor6d:Un,variable:Vn,zeros:Gn,onesLike:jn,zerosLike:Xn,transpose:Wl,softmax:go,logSoftmax:yo,localResponseNormalization:Ul,norm:Vl,gather:Lc,unsortedSegmentSum:Wc,basicLSTMCell:zl,multiRNNCell:Gl,movingAverage:Hl,stridedSlice:ql,topk:Kl,scatterND:jl,fft:Xl,ifft:Yl,rfft:$l,irfft:Ql,sparseToDense:Zl,gatherND:th,diag:eh,dropout:nh,hannWindow:oh,hammingWindow:ah,frame:ih,stft:sh,inTopKAsync:lh});function Hh(t,e){Array.isArray(t)||(t=[t]),t.forEach((function(t){null!=t&&C("complex64"!==t.dtype,(function(){return e+" does not support complex64 tensors."}))}))}function qh(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var Kh=function(t){function o(){var e=t.call(this)||this;return e.blockSize=48,e.firstUse=!0,e.data=new xo(e,Lt),e}return e(o,t),o.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,i().get("IS_NODE")&&dn("\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============================"));var r={};return this.data.set(r,{values:t,dtype:n}),r},o.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},o.prototype.numDataIds=function(){return this.data.numDataIds()},o.prototype.read=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){return[2,this.readSync(t)]}))}))},o.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?Vo(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},o.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map((function(t){return ot(t)}))}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return dr(t.shape,t.dtype,n)},o.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return Lt.makeTensorFromDataId(r,e,n,this)},o.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},o.prototype.time=function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){return e=et(),t(),[2,{kernelMs:et()-e}]}))}))},o.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},o.prototype.complex=function(t,e){var n=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:Lt.keep(t.clone()),imag:Lt.keep(e.clone())},n},o.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},o.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},o.prototype.slice=function(t,e,n){if(Hh(t,"slice"),io(t.shape,e,n)){var r=so(e,t.strides),o=k(n);return Fn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype)}for(var a=dr(n,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s).map((function(t,n){return t+e[n]}));a.values[s]=i.get.apply(i,u)}return a.toTensor()},o.prototype.stridedSlice=function(t,e,n,r){Hh(t,"stridedSlice");var o=ro(e,n,r);if(o.some((function(t){return 0===t})))return Fn([],o);for(var a=dr(o,t.dtype),i=this.bufferSync(t),s=0;s<a.size;s++){for(var u=a.indexToLoc(s),c=new Array(u.length),l=0;l<c.length;l++)c[l]=u[l]*r[l]+e[l];a.set.apply(a,[i.get.apply(i,c)].concat(u))}return a.toTensor()},o.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=dr([t.size,t.size],t.dtype),r=n.values,o=0;o<e.length;o++)r[o*t.size+o]=e[o];return n.toTensor()},o.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},o.prototype.reverse=function(t,e){Hh(t,"reverse");for(var n=dr(t.shape,t.dtype),r=this.bufferSync(t),o=function(o){var a=n.indexToLoc(o),i=a.slice();e.forEach((function(e){return i[e]=t.shape[e]-1-i[e]})),n.set.apply(n,[r.get.apply(r,i)].concat(a))},a=0;a<n.size;a++)o(a);return n.toTensor()},o.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map((function(t){return Tn(t)})),o=t.map((function(t){return Nn(t)}));return Dn(this.concat(r,e),this.concat(o,e))}var a=t.map((function(t){var n=k(t.shape.slice(e));return t.as2D(-1,n)})),i=Sn(a.map((function(t){return t.shape})),1),s=dr(i,t[0].dtype).values;if(1===a[0].shape[0]){var u=0;a.forEach((function(t){s.set(n.readSync(t.dataId),u),u+=t.size}))}else{var c=0;a.forEach((function(t){for(var e=n.readSync(t.dataId),r=0,o=0;o<t.shape[0];++o)for(var a=o*i[1]+c,u=0;u<t.shape[1];++u)s[a+u]=e[r++];c+=t.shape[1]}))}var l=Sn(t.map((function(t){return t.shape})),e);return Fn(s,l,t[0].dtype)},o.prototype.neg=function(t){return Hh(t,"neg"),this.multiply(On(-1),t)},o.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t+n,imag:e+r}})):this.broadcastedBinaryOp(t,e,Dt(t.dtype,e.dtype),(function(t,e){return t+e}))},o.prototype.addN=function(t){var e=this;Hh(t,"addN");for(var n=t.map((function(t){return e.readSync(t.dataId)})),r=dr(t[0].shape,t[0].dtype),o=r.values,a=0;a<t.length;a++)for(var i=n[a],s=0;s<o.length;s++)o[s]+=i[s];return r.toTensor()},o.prototype.softmax=function(t,e){var n=O([e],t.shape),r=this.max(t,n),o=wn(r.shape,n),a=this.subtract(t,r.reshape(o)),i=this.exp(a),s=this.sum(i,n).reshape(o);return this.realDivide(i,s)},o.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t-n,imag:e-r}})):this.broadcastedBinaryOp(t,e,Dt(t.dtype,e.dtype),(function(t,e){return t-e}))},o.prototype.pow=function(t,e){return Hh([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.pow(t,e)}))},o.prototype.batchMatMul=function(t,e,n,r){Hh([t,e],"matMul");for(var o=n?t.shape[1]:t.shape[2],a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],h=l[0],f=l[1],d=l[2],p=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=p[0],m=p[1],g=p[2],y=a*i,x=dr([s,a,i],t.dtype),b=x.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<a;E+=w)for(var R=0;R<i;R+=w)for(var I=0;I<o;I+=w)for(var k=Math.min(E+w,a),S=Math.min(R+w,i),A=Math.min(I+w,o),D=E;D<k;D++)for(var T=R;T<S;T++){for(var N=0,F=I;F<A;F++)N+=u[C*h+D*f+F*d]*c[F*v+T*m+C*g];b[C*y+(D*i+T)]+=N}return x.toTensor()},o.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,o);return a&&(u=this.add(u,a)),i&&(u=qh(this,u,i,s)),u},o.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),(function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}})):this.broadcastedBinaryOp(t,e,Dt(t.dtype,e.dtype),(function(t,e){return t*e}))},o.prototype.realDivide=function(t,e){Hh([t,e],"realDivide");return this.broadcastedBinaryOp(t,e,"float32",(function(t,e){return t/e}))},o.prototype.floorDiv=function(t,e){Hh([t,e],"floorDiv");return this.broadcastedBinaryOp(t,e,"int32",(function(t,e){return Math.floor(t/e)}))},o.prototype.sum=function(t,e){Hh(t,"sum"),Cn("sum",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,Dt(t.dtype,"int32")),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=0,f=0;f<i;++f)h+=u[l+f];s[c]=h}return a},o.prototype.prod=function(t,e){Hh(t,"sum");for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,Dt(t.dtype,"int32")),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=1,f=0;f<i;++f)h*=u[l+f];s[c]=h}return a},o.prototype.unsortedSegmentSum=function(t,e,n){Hh(t,"unsortedSegmentSum");for(var r=[],o=t.rank-e.rank,a=0;a<o;++a)e=e.expandDims(a+1);for(a=0;a<n;++a){var i=On(a,"int32"),s=Rc(i,e).asType("float32").mul(t).sum(0);r.push(s)}return Pr(r)},o.prototype.argMin=function(t,e){Hh(t,"argMin");var n=[e];Cn("argMin",n,t.rank);for(var r=bn(t.shape,n),o=r[0],a=r[1],i=Gn(o,"int32"),s=k(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,f=c[h],d=0,p=0;p<s;++p){var v=c[h+p];v<f&&(f=v,d=p)}u[l]=d}return i},o.prototype.argMax=function(t,e){Hh(t,"argMax");var n=[e];Cn("argMax",n,t.rank);for(var r=bn(t.shape,n),o=r[0],a=r[1],i=Gn(o,"int32"),s=k(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var h=l*s,f=c[h],d=0,p=0;p<s;++p){var v=c[h+p];v>f&&(f=v,d=p)}u[l]=d}return i},o.prototype.cumsum=function(t,e,n,r){if(Hh(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 o=Dt(t.dtype,"int32"),a=Gn(t.shape,o),i=this.readSync(a.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;l<s.length;l+=u)for(var h=0;h<u;h++){var f=c(l,h);if(0===h)i[f]=n?0:s[f];else{var d=c(l,h-1);i[f]=n?s[d]+i[d]:s[f]+i[d]}}return a},o.prototype.equal=function(t,e){return Hh([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t===e?1:0}))},o.prototype.notEqual=function(t,e){return Hh([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t!==e?1:0}))},o.prototype.less=function(t,e){return Hh([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<e?1:0}))},o.prototype.lessEqual=function(t,e){return Hh([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t<=e?1:0}))},o.prototype.greater=function(t,e){return Hh([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>e?1:0}))},o.prototype.greaterEqual=function(t,e){return Hh([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t>=e?1:0}))},o.prototype.logicalNot=function(t){Hh(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return this.makeOutput(n,t.shape,"bool")},o.prototype.logicalAnd=function(t,e){return Hh([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t&&e}))},o.prototype.logicalOr=function(t,e){return Hh([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",(function(t,e){return t||e}))},o.prototype.select=function(t,e,n){Hh([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=this.readSync(n.dataId),i=Gn(e.shape,Dt(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,c=0===t.rank||t.rank>1||1===e.rank?1:k(e.shape.slice(1)),l=0;l<r.length;l++)for(var h=0;h<c;h++)1===r[l]?s[u++]=o[l]:s[u++]=a[l];return i},o.prototype.where=function(t){Hh([t],"where");var e=this.readSync(t.dataId);return na(t.shape,e)},o.prototype.topk=function(t,e,n){return Hh(t,"topk"),ea(this.readSync(t.dataId),t.shape,t.dtype,e)},o.prototype.min=function(t,e){Hh(t,"min"),Cn("min",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];d<h&&(h=d)}s[c]=h}return a},o.prototype.minimum=function(t,e){return Hh([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.min(t,e)}))},o.prototype.mod=function(t,e){return Hh([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e}))},o.prototype.max=function(t,e){Hh(t,"max"),Cn("max",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];d>h&&(h=d)}s[c]=h}return a},o.prototype.maximum=function(t,e){return Hh([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.max(t,e)}))},o.prototype.all=function(t,e){Hh(t,"all"),Cn("all",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];h=h&&d}s[c]=h}return a},o.prototype.any=function(t,e){Hh(t,"any"),Cn("any",e,t.rank);for(var n=bn(t.shape,e),r=n[0],o=n[1],a=Gn(r,t.dtype),i=k(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,h=u[l],f=0;f<i;++f){var d=u[l+f];h=h||d}s[c]=h}return a},o.prototype.squaredDifference=function(t,e){return Hh([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){var n=t-e;return n*n}))},o.prototype.ceil=function(t){Hh(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.floor=function(t){Hh(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.sign=function(t){Hh(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,t.shape,"float32")},o.prototype.isNaN=function(t){Hh(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},o.prototype.isInf=function(t){Hh(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},o.prototype.isFinite=function(t){Hh(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},o.prototype.round=function(t){Hh(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=Math.floor(e[r]);e[r]-o<.5?n[r]=Math.floor(e[r]):e[r]-o>.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1}return this.makeOutput(n,t.shape,"float32")},o.prototype.exp=function(t){Hh(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.expm1=function(t){Hh(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return this.makeOutput(n,t.shape,"float32")},o.prototype.log=function(t){Hh(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.log1p=function(t){Hh(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log1p(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.sqrt=function(t){Hh(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.sqrt(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.rsqrt=function(t){Hh(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=1/Math.sqrt(o)}return this.makeOutput(n,t.shape,"float32")},o.prototype.reciprocal=function(t){Hh(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return this.makeOutput(n,t.shape,"float32")},o.prototype.linear=function(t){return t},o.prototype.relu=function(t){Hh(t,"relu");for(var e=Gn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.max(0,r[o]);return e},o.prototype.relu6=function(t){Hh(t,"relu");for(var e=Gn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.min(Math.max(0,r[o]),6);return e},o.prototype.prelu=function(t,e){return Hh([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return t<0?e*t:t}))},o.prototype.elu=function(t){Hh(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r];e[r]=o>=0?o:Math.exp(o)-1}return this.makeOutput(e,t.shape,"float32")},o.prototype.eluDer=function(t,e){Hh([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),a=0;a<r.length;++a){var i=r[a];n[a]=i>=1?o[a]:o[a]*(i+1)}return this.makeOutput(n,e.shape,"float32")},o.prototype.selu=function(t){Hh(t,"selu");for(var e=bs,n=ws,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>=0?n*i:e*(Math.exp(i)-1)}return this.makeOutput(r,t.shape,"float32")},o.prototype.clip=function(t,e,n){Hh(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>n?n:i<e?e:i}return this.makeOutput(r,t.shape,"float32")},o.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var o=n[2*r],a=n[2*r+1];e[r]=Math.hypot(o,a)}return this.makeOutput(e,t.shape,"float32")},o.prototype.int=function(t){Hh(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return this.makeOutput(e,t.shape,"int32")},o.prototype.sigmoid=function(t){Hh(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(e,t.shape,"float32")},o.prototype.softplus=function(t){Hh(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o]>-e,i=r[o]<e,s=Math.exp(r[o]),u=void 0;u=i?s:a?r[o]:Math.log(1+s),n[o]=u}return this.makeOutput(n,t.shape,"float32")},o.prototype.sin=function(t){Hh(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.cos=function(t){Hh(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.tan=function(t){Hh(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.asin=function(t){Hh(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.acos=function(t){Hh(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.atan=function(t){Hh(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.atan2=function(t,e){return Hh([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,(function(t,e){return Math.atan2(t,e)}))},o.prototype.sinh=function(t){Hh(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.cosh=function(t){Hh(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.tanh=function(t){Hh(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=D(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.asinh=function(t){Hh(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.acosh=function(t){Hh(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.atanh=function(t){Hh(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return this.makeOutput(e,t.shape,"float32")},o.prototype.erf=function(t){Hh(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=Math.sign(n[r]),a=Math.abs(n[r]),i=1/(1+.3275911*a);e[r]=o*(1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-a*a))}return this.makeOutput(e,t.shape,"float32")},o.prototype.step=function(t,e){void 0===e&&(e=0),Hh(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o];isNaN(a)?n[o]=NaN:n[o]=a>0?1:e}return this.makeOutput(n,t.shape,"float32")},o.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.conv2d(e,n,r);return o&&(s=this.add(s,o)),a&&(s=qh(this,s,a,i)),s},o.prototype.conv2d=function(t,e,n){Hh([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c="channelsLast"===n.dataFormat,l=dr(n.outShape,t.dtype),h=t.strides[0],f=c?t.strides[1]:t.strides[2],d=c?t.strides[2]:1,p=c?1:t.strides[1],v=l.strides[0],m=c?l.strides[1]:l.strides[2],g=c?l.strides[2]:1,y=c?1:l.strides[1],x=this.readSync(t.dataId),b=this.readSync(e.dataId),w=l.values,C=0;C<n.batchSize;++C)for(var E=C*h,R=C*v,I=0;I<n.outHeight;++I)for(var k=R+I*m,S=I*n.strideHeight-u,A=0;A<r;A++){var D=S+A*a;if(!(D<0||D>=n.inHeight))for(var T=A*e.strides[0],N=E+D*f,F=0;F<n.outWidth;++F)for(var _=k+F*g,O=F*n.strideWidth-s,M=0;M<o;M++){var B=O+M*i;if(!(B<0||B>=n.inWidth))for(var P=N+B*d,L=T+M*e.strides[1],W=0;W<n.inChannels;++W){for(var U=x[P+W*p],V=0;V<n.outChannels;++V)w[_+V*y]+=U*b[L+V];L+=n.outChannels}}}return l.toTensor()},o.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,o=n.filterHeight,a=n.filterWidth,i=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,c=n.padInfo.front,l=n.padInfo.left,h=n.padInfo.top,f=dr(n.outShape,t.dtype),d=this.readSync(t.dataId),p=this.readSync(e.dataId),v=f.values,m=0;m<n.batchSize;++m)for(var g=m*t.strides[0],y=m*f.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*f.strides[1],w=x*n.strideDepth-c,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var R=C*e.strides[0],I=g+E*t.strides[1],k=0;k<n.outHeight;++k)for(var S=b+k*f.strides[2],A=k*n.strideHeight-h,D=0;D<o;D++){var T=A+D*s;if(!(T<0||T>=n.inHeight))for(var N=R+D*e.strides[1],F=I+T*t.strides[2],_=0;_<n.outWidth;++_)for(var O=S+_*n.outChannels,M=_*n.strideWidth-l,B=0;B<a;B++){var P=M+B*u;if(!(P<0||P>=n.inWidth))for(var L=N+B*e.strides[2],W=F+P*n.inChannels,U=L,V=0;V<n.inChannels;++V){for(var z=d[W+V],G=0;G<n.outChannels;++G)v[O+G]+=z*p[U+G];U+=n.outChannels}}}}return f.toTensor()},o.prototype.conv2dDerInput=function(t,e,n){Hh([t,e],"conv2dDerInput");for(var r=dr(n.inShape,"float32"),o=r.values,a=this.readSync(t.dataId),i=this.readSync(e.dataId),s=e.strides,u=s[0],c=s[1],l=s[2],h=n.batchSize,f=n.filterHeight,d=n.filterWidth,p=n.inChannels,v=n.inHeight,m=n.inWidth,g=n.outChannels,y=n.outHeight,x=n.outWidth,b=n.strideHeight,w=n.strideWidth,C=n.dataFormat,E=f-1-n.padInfo.top,R=d-1-n.padInfo.left,I="channelsLast"===C,k=r.strides[0],S=I?r.strides[1]:r.strides[2],A=I?r.strides[2]:1,D=I?1:r.strides[1],T=t.strides[0],N=I?t.strides[1]:t.strides[2],F=I?t.strides[2]:1,_=I?1:t.strides[1],O=0;O<h;++O)for(var M=0;M<p;++M)for(var B=0;B<v;++B)for(var P=B-E,L=Math.max(0,Math.ceil(P/b)),W=Math.min(y,(f+P)/b),U=0;U<m;++U){for(var V=U-R,z=Math.max(0,Math.ceil(V/w)),G=Math.min(x,(d+V)/w),H=0,q=L;q<W;++q)for(var K=q*b-P,j=z;j<G;++j)for(var X=T*O+N*q+F*j,Y=u*(f-1-K)+c*(d-1-(j*w-V))+l*M,$=0;$<g;++$){H+=a[X+_*$]*i[Y+$]}o[k*O+S*B+A*U+D*M]=H}return r.toTensor()},o.prototype.conv3dDerInput=function(t,e,n){for(var r=dr(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=a[3],l=this.readSync(t.dataId),h=t.strides,f=h[0],d=h[1],p=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=n.batchSize,E=n.filterDepth,R=n.filterHeight,I=n.filterWidth,k=n.inChannels,S=n.inDepth,A=n.inHeight,D=n.inWidth,T=n.outChannels,N=n.outDepth,F=n.outHeight,_=n.outWidth,O=n.strideDepth,M=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=R-1-n.padInfo.top,W=I-1-n.padInfo.left,U=0;U<C;++U)for(var V=0;V<k;++V)for(var z=0;z<S;++z)for(var G=z-P,H=Math.max(0,Math.ceil(G/O)),q=Math.min(N,(E+G)/O),K=0;K<A;++K)for(var j=K-L,X=Math.max(0,Math.ceil(j/M)),Y=Math.min(F,(R+j)/M),$=0;$<D;++$){for(var Q=$-W,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(_,(I+Q)/B),tt=0,et=H;et<q;++et)for(var nt=et*O-G,rt=X;rt<Y;++rt)for(var ot=rt*M-j,at=J;at<Z;++at)for(var it=f*U+d*et+p*rt+v*at,st=y*(E-1-nt)+x*(R-1-ot)+b*(I-1-(at*B-Q))+w*V,ut=0;ut<T;++ut){tt+=l[it+ut]*m[st+ut]}o[i*U+s*z+u*K+c*$+V]=tt}return r.toTensor()},o.prototype.conv2dDerFilter=function(t,e,n){Hh([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s="channelsLast"===n.dataFormat,u=dr(n.filterShape,"float32"),c=n.padInfo.left,l=n.padInfo.top,h=this.bufferSync(t),f=this.bufferSync(e),d=0;d<a;++d)for(var p=Math.max(0,Math.ceil((l-d)/r)),v=Math.min(n.outHeight,(n.inHeight+l-d)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((c-m)/o)),y=Math.min(n.outWidth,(n.inWidth+c-m)/o),x=0;x<n.inChannels;++x)for(var b=0;b<n.outChannels;++b){for(var w=0,C=0;C<n.batchSize;++C)for(var E=p;E<v;++E)for(var R=d+E*r-l,I=g;I<y;++I){var k=m+I*o-c;w+=s?h.get(C,R,k,x)*f.get(C,E,I,b):h.get(C,x,R,k)*f.get(C,b,E,I)}u.set(w,d,m,x,b)}return u.toTensor()},o.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=dr(n.filterShape,"float32"),l=c.values,h=c.strides,f=h[0],d=h[1],p=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=this.readSync(t.dataId),E=t.strides,R=E[0],I=E[1],k=E[2],S=E[3],A=n.padInfo.front,D=n.padInfo.left,T=n.padInfo.top,N=0;N<i;++N)for(var F=Math.max(0,Math.ceil((A-N)/r)),_=Math.min(n.outDepth,(n.inDepth+A-N)/r),O=N*f,M=0;M<s;++M)for(var B=Math.max(0,Math.ceil((T-M)/o)),P=Math.min(n.outHeight,(n.inHeight+T-M)/o),L=M*d+O,W=0;W<u;++W)for(var U=Math.max(0,Math.ceil((D-W)/a)),V=Math.min(n.outWidth,(n.inWidth+D-W)/a),z=W*p+L,G=0;G<n.inChannels;++G)for(var H=G*v+z,q=0;q<n.outChannels;++q){for(var K=0,j=0;j<n.batchSize;++j)for(var X=j*R,Y=j*y,$=F;$<_;++$)for(var Q=(N+$*r-A)*I+X,J=$*x+Y,Z=B;Z<P;++Z)for(var tt=(M+Z*o-T)*k+Q,et=Z*b+J,nt=U;nt<V;++nt){var rt=nt*w+et;K+=C[(W+nt*a-D)*S+tt+G]*m[rt+q]}l[H+q]=K}return c.toTensor()},o.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return o&&(s=this.add(s,o)),a&&(s=qh(this,s,a,i)),s},o.prototype.depthwiseConv2D=function(t,e,n){Hh([t,e],"depthwiseConv2D");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=n.outChannels/n.inChannels,l=dr(n.outShape,t.dtype),h=this.readSync(t.dataId),f=this.readSync(e.dataId),d=l.values,p=0;p<n.batchSize;++p)for(var v=p*t.strides[0],m=p*l.strides[0],g=0;g<n.outHeight;++g)for(var y=m+g*l.strides[1],x=g*n.strideHeight-s,b=0;b<r;++b){var w=x+b*a;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],R=0;R<n.outWidth;++R)for(var I=y+R*l.strides[2],k=R*n.strideWidth-u,S=0;S<o;++S){var A=k+S*i;if(!(A<0||A>=n.inWidth))for(var D=C+S*e.strides[1],T=E+A*n.inChannels,N=I,F=D,_=0;_<n.inChannels;++_){for(var O=h[T+_],M=0;M<c;++M)d[N+M]+=O*f[F+M];N+=c,F+=c}}}return l.toTensor()},o.prototype.depthwiseConv2DDerInput=function(t,e,n){Hh([t,e],"depthwiseConv2DDerInput");for(var r=dr(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=this.readSync(t.dataId),l=t.strides,h=l[0],f=l[1],d=l[2],p=this.readSync(e.dataId),v=e.strides,m=v[0],g=v[1],y=v[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,R=n.inWidth,I=n.outChannels,k=n.outHeight,S=n.outWidth,A=n.strideHeight,D=n.strideWidth,T=b-1-n.padInfo.top,N=w-1-n.padInfo.left,F=I/C,_=0;_<x;++_)for(var O=0;O<C;++O)for(var M=0;M<E;++M)for(var B=M-T,P=Math.max(0,Math.ceil(B/A)),L=Math.min(k,(b+B)/A),W=0;W<R;++W){for(var U=W-N,V=Math.max(0,Math.ceil(U/D)),z=Math.min(S,(w+U)/D),G=0,H=P;H<L;++H)for(var q=H*A-B,K=V;K<z;++K)for(var j=h*_+f*H+d*K,X=m*(b-1-q)+g*(w-1-(K*D-U))+y*O,Y=0;Y<F;++Y){G+=c[j+(O*F+Y)]*p[X+Y]}o[i*_+s*M+u*W+O]=G}return r.toTensor()},o.prototype.depthwiseConv2DDerFilter=function(t,e,n){Hh([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=dr(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,h=this.bufferSync(t),f=this.bufferSync(e),d=0;d<a;++d)for(var p=Math.max(0,Math.ceil((c-d)/r)),v=Math.min(n.outHeight,(n.inHeight+c-d)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((u-m)/o)),y=Math.min(n.outWidth,(n.inWidth+u-m)/o),x=0;x<n.outChannels;++x){for(var b=Math.trunc(x/l),w=x%l,C=0,E=0;E<n.batchSize;++E)for(var R=p;R<v;++R)for(var I=d+R*r-c,k=g;k<y;++k){var S=m+k*o-u;C+=h.get(E,I,S,b)*f.get(E,R,k,x)}s.set(C,d,m,b,w)}return s.toTensor()},o.prototype.tile=function(t,e){return Hh(t,"tile"),ta(this.bufferSync(t),e)},o.prototype.pad=function(t,e,n){Hh(t,"pad");var r=e.map((function(e,n){return e[0]+t.shape[n]+e[1]})),o=e.map((function(t){return t[0]})),a=this.bufferSync(t),i=dr(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),c=u.map((function(t,e){return t+o[e]}));i.set.apply(i,[a.get.apply(a,u)].concat(c))}return i.toTensor()},o.prototype.transpose=function(t,e){Hh(t,"transpose");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[e[r]];var o=this.readSync(t.dataId),a=dr(n,t.dtype),i=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=i.indexToLoc(r),u=new Array(s.length),c=0;c<u.length;c++)u[c]=s[e[c]];var l=a.locToIndex(u);a.values[l]=o[r]}return a.toTensor()},o.prototype.gather=function(t,e,n){Hh([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var a=dr(r,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),c=u.slice();c[n]=o[u[n]];var l=i.locToIndex(c);a.values[s]=i.values[l]}return a.toTensor()},o.prototype.batchToSpaceND=function(t,e,n){Hh([t],"batchToSpaceND");var r=e.reduce((function(t,e){return t*e})),o=zr(t.shape,e,r),a=Gr(o.length,e.length),i=Hr(t.shape,e,r),s=qr(n,e.length),u=Kr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},o.prototype.spaceToBatchND=function(t,e,n){Hh([t],"spaceToBatchND");var r=e.reduce((function(t,e){return t*e})),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=zr(i.shape,e,r,!1),u=Gr(s.length,e.length,!1),c=Hr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},o.prototype.pool=function(t,e,n){Hh(t,"pool");for(var r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,h="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=this.readSync(t.dataId),d=dr(e.outShape,t.dtype),p=d.values,v=e.outShape[1]*e.outShape[2]*e.outShape[3],m=e.outShape[2]*e.outShape[3],g=e.outShape[3],y=0;y<e.batchSize;++y)for(var x=y*v,b=y*t.strides[0],w=0;w<e.inChannels;++w)for(var C=0;C<e.outHeight;++C)for(var E=C*r-c,R=Math.max(0,E),I=Math.min(e.inHeight,s+E),k=x+C*m,S=0;S<e.outWidth;++S){for(var A=S*o-l,D=Math.max(0,A),T=Math.min(e.inWidth,u+A),N=h,F=0,_=0,O=R;O<I;O+=a){for(var M=b+O*t.strides[1],B=D;B<T;B+=i){var P=f[M+B*t.strides[2]+w];"max"===n&&P>N?N=P:"avg"===n&&(F+=P,_++)}if(isNaN(N))break}p[k+S*g+w]="avg"===n?F/_:N}return d.toTensor()},o.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},o.prototype.maxPoolPositions=function(t,e){for(var n=dr(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,h=this.bufferSync(t),f=0;f<e.batchSize;++f)for(var d=0;d<e.inChannels;++d)for(var p=0;p<e.outHeight;++p){for(var v=p*r-c,m=v;m<0;)m+=a;for(var g=Math.min(e.inHeight,s+v),y=0;y<e.outWidth;++y){for(var x=y*o-l,b=x;b<0;)b+=i;for(var w=Math.min(e.inWidth,u+x),C=Number.NEGATIVE_INFINITY,E=-1,R=m;R<g;R+=a)for(var I=R-v,k=b;k<w;k+=i){var S=k-x,A=h.get(f,R,k,d);A>C&&(C=A,E=I*u+S)}n.set(E,f,p,y,d)}}return n.toTensor()},o.prototype.maxPoolBackprop=function(t,e,n,r){Hh([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,h=l-1-r.padInfo.left,f=c-1-r.padInfo.top,d=dr(e.shape,"float32"),p=this.bufferSync(o),v=this.bufferSync(t),m=0;m<r.batchSize;++m)for(var g=0;g<r.inChannels;++g)for(var y=0;y<r.inHeight;++y)for(var x=0;x<r.inWidth;++x){for(var b=y-f,w=x-h,C=0,E=0;E<c;E+=s){var R=(b+E)/a;if(!(R<0||R>=r.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/i;if(!(k<0||k>=r.outWidth||Math.floor(k)!==k)){var S=c*l-1-p.get(m,R,k,g)===E*l+I?1:0;if(0!==S)C+=v.get(m,R,k,g)*S}}}d.set(C,m,y,x,g)}return d.toTensor()},o.prototype.avgPoolBackprop=function(t,e,n){Hh([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=l-1-n.padInfo.left,f=c-1-n.padInfo.top,d=dr(e.shape,"float32"),p=1/(a*i),v=this.bufferSync(t),m=0;m<n.batchSize;++m)for(var g=0;g<n.inChannels;++g)for(var y=0;y<n.inHeight;++y)for(var x=0;x<n.inWidth;++x){for(var b=y-f,w=x-h,C=0,E=0;E<c;E+=s){var R=(b+E)/r;if(!(R<0||R>=n.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/o;if(!(k<0||k>=n.outWidth||Math.floor(k)!==k))C+=v.get(m,R,k,g)}}d.set(C*p,m,y,x,g)}return d.toTensor()},o.prototype.pool3d=function(t,e,n){Hh(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,f=e.padInfo.front,d=e.padInfo.top,p=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),g=dr(e.outShape,t.dtype),y=g.values,x=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],E=0;E<e.batchSize;++E)for(var R=E*x,I=E*t.strides[0],k=0;k<e.inChannels;++k)for(var S=0;S<e.outDepth;++S){for(var A=S*r-f,D=A;D<0;)D+=i;for(var T=Math.min(e.inDepth,c+A),N=R+S*b,F=0;F<e.outHeight;++F){for(var _=F*o-d,O=_;O<0;)O+=s;for(var M=Math.min(e.inHeight,l+_),B=N+F*w,P=0;P<e.outWidth;++P){for(var L=P*a-p,W=L;W<0;)W+=u;for(var U=Math.min(e.inWidth,h+L),V=B+P*C,z=v,G=0,H=0,q=D;q<T;q+=i){for(var K=I+q*t.strides[1],j=O;j<M;j+=s){for(var X=K+j*t.strides[2],Y=W;Y<U;Y+=u){var $=m[X+Y*t.strides[3]+k];if("max"===n&&$>z?z=$:"avg"===n&&(G+=$,H++),isNaN(z))break}if(isNaN(z))break}if(isNaN(z))break}y[V+k]="avg"===n?G/H:z}}}return g.toTensor()},o.prototype.avgPool3d=function(t,e){return Hh(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},o.prototype.avgPool3dBackprop=function(t,e,n){Hh([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=n.dilationDepth,l=n.dilationHeight,h=n.dilationWidth,f=n.effectiveFilterDepth,d=n.effectiveFilterHeight,p=n.effectiveFilterWidth,v=f-1-n.padInfo.front,m=p-1-n.padInfo.left,g=d-1-n.padInfo.top,y=dr(e.shape,"float32"),x=1/(i*s*u),b=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var E=0;E<n.inDepth;++E)for(var R=0;R<n.inHeight;++R)for(var I=0;I<n.inWidth;++I){for(var k=E-v,S=R-g,A=I-m,D=0,T=0;T<f;T+=c){var N=(k+T)/r;if(!(N<0||N>=n.outDepth||Math.floor(N)!==N))for(var F=0;F<d;F+=l){var _=(S+F)/o;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var O=0;O<p;O+=h){var M=(A+O)/a;if(!(M<0||M>=n.outWidth||Math.floor(M)!==M))D+=b.get(w,N,_,M,C)}}}y.set(D*x,w,E,R,I,C)}return y.toTensor()},o.prototype.maxPool3d=function(t,e){return Hh(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},o.prototype.maxPool3dPositions=function(t,e){for(var n=dr(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,h=e.effectiveFilterWidth,f=e.padInfo.front,d=e.padInfo.top,p=e.padInfo.left,v=this.bufferSync(t),m=0;m<e.batchSize;++m)for(var g=0;g<e.inChannels;++g)for(var y=0;y<e.outDepth;++y){for(var x=y*r-f,b=x;b<0;)b+=i;for(var w=Math.min(e.inDepth,c+x),C=0;C<e.outHeight;++C){for(var E=C*o-d,R=E;R<0;)R+=s;for(var I=Math.min(e.inHeight,l+E),k=0;k<e.outWidth;++k){for(var S=k*a-p,A=S;A<0;)A+=u;for(var D=Math.min(e.inWidth,h+S),T=Number.NEGATIVE_INFINITY,N=-1,F=b;F<w;F+=i)for(var _=F-x,O=R;O<I;O+=s)for(var M=O-E,B=A;B<D;B+=u){var P=B-S,L=v.get(m,F,O,B,g);L>=T&&(T=L,N=_*l*h+M*l+P)}n.set(N,m,y,C,k,g)}}}return n.toTensor()},o.prototype.maxPool3dBackprop=function(t,e,n,r){Hh([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),a=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,h=r.effectiveFilterDepth,f=r.effectiveFilterHeight,d=r.effectiveFilterWidth,p=h-1-r.padInfo.front,v=d-1-r.padInfo.left,m=f-1-r.padInfo.top,g=dr(e.shape,"float32"),y=this.bufferSync(o),x=this.bufferSync(t),b=0;b<r.batchSize;++b)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var E=0;E<r.inHeight;++E)for(var R=0;R<r.inWidth;++R){for(var I=C-p,k=E-m,S=R-v,A=0,D=0;D<h;D+=u){var T=(I+D)/a;if(!(T<0||T>=r.outDepth||Math.floor(T)!==T))for(var N=0;N<f;N+=c){var F=(k+N)/i;if(!(F<0||F>=r.outHeight||Math.floor(F)!==F))for(var _=0;_<d;_+=l){var O=(S+_)/s;if(!(O<0||O>=r.outWidth||Math.floor(O)!==O)){var M=h*f*d-1-y.get(b,T,F,O,w)===D*f*d+N*d+_?1:0;if(0!==M)A+=x.get(b,T,F,O,w)*M}}}}g.set(A,b,C,E,R,w)}return g.toTensor()},o.prototype.cast=function(t,e){return Po(t,e,this)},o.prototype.reshape=function(t,e){return Lo(t,e)},o.prototype.avgPool=function(t,e){return Hh(t,"avgPool"),this.pool(t,e,"avg").toFloat()},o.prototype.resizeBilinear=function(t,e,n,r){Hh(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(k([a,e,n,u])),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=0,p=h[0]/f[0],v=h[1]/f[1],m=0;m<a;m++)for(var g=0;g<e;g++)for(var y=p*g,x=Math.floor(y),b=y-x,w=Math.min(i-1,Math.ceil(y)),C=m*t.strides[0]+x*t.strides[1],E=m*t.strides[0]+w*t.strides[1],R=0;R<n;R++)for(var I=v*R,S=Math.floor(I),A=I-S,D=Math.min(s-1,Math.ceil(I)),T=C+S*t.strides[2],N=E+S*t.strides[2],F=C+D*t.strides[2],_=E+D*t.strides[2],O=0;O<u;O++){var M=c[T+O],B=c[N+O],P=M+(c[F+O]-M)*A,L=P+(B+(c[_+O]-B)*A-P)*b;l[d++]=L}return Fn(l,[a,e,n,u])},o.prototype.resizeBilinearBackprop=function(t,e,n){Hh([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*a*i*s),f=[n&&c>1?a-1:a,n&&l>1?i-1:i],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],p=f[0]/d[0],v=f[1]/d[1],m=this.readSync(t.dataId),g=0,y=0;y<o;y++)for(var x=y*e.strides[0],b=0;b<c;b++)for(var w=b*p,C=Math.floor(w),E=Math.min(Math.ceil(w),a-1),R=x+C*e.strides[1],I=x+E*e.strides[1],k=w-C,S=1-k,A=0;A<l;A++)for(var D=A*v,T=Math.floor(D),N=Math.min(Math.ceil(D),i-1),F=D-T,_=1-F,O=R+T*e.strides[2],M=R+N*e.strides[2],B=I+T*e.strides[2],P=I+N*e.strides[2],L=S*_,W=S*F,U=k*_,V=k*F,z=0;z<s;z++){var G=m[g++];h[O+z]+=G*L,h[M+z]+=G*W,h[B+z]+=G*U,h[P+z]+=G*V}return Ln(h,[o,i,a,s],e.dtype)},o.prototype.resizeNearestNeighbor=function(t,e,n,r){Hh(t,"resizeNearestNeighbor");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(a*e*n*u),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],f=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=h[0]/f[0],p=h[1]/f[1],v=0,m=0;m<a;m++)for(var g=m*t.strides[0],y=0;y<e;y++)for(var x=d*y,b=g+Math.min(i-1,r?Math.round(x):Math.floor(x))*t.strides[1],w=0;w<n;w++)for(var C=p*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],R=0;R<u;R++){var I=c[E+R];l[v++]=I}return Fn(l,[a,e,n,u],t.dtype)},o.prototype.resizeNearestNeighborBackprop=function(t,e,n){Hh([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],h=new Float32Array(o*a*i*s),f=this.readSync(t.dataId),d=[n&&c>1?a-1:a,n&&l>1?i-1:i],p=[n&&c>1?c-1:c,n&&l>1?l-1:l],v=d[0]/p[0],m=d[1]/p[1],g=1/v,y=1/m,x=2*Math.ceil(g)+2,b=2*Math.ceil(y)+2,w=0;w<o;w++)for(var C=w*e.strides[0],E=0;E<a;E++)for(var R=C+E*e.strides[1],I=Math.floor(E*g),k=Math.floor(I-x/2),S=0;S<i;S++)for(var A=R+S*e.strides[2],D=Math.floor(S*y),T=Math.floor(D-b/2),N=0;N<s;N++){for(var F=0,_=0;_<x;_++){var O=_+k;if(!(O<0||O>=c)){var M=C+O*t.strides[1],B=O*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P<b;P++){var L=P+T;if(!(L<0||L>=l)){var W=M+L*t.strides[2],U=L*m;S===Math.min(i-1,n?Math.round(U):Math.floor(U))&&(F+=f[W+N])}}}}h[A+N]=F}return Ln(h,e.shape,e.dtype)},o.prototype.batchNormalization=function(t,e,n,r,o,a){Hh([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),l=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),f=l.length,d=c.length,p=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b<i.length;++b)h[b]=l[m++]+(i[b]-s[g++])*c[y++]/Math.sqrt(u[x++]+r),m>=f&&(m=0),g>=v&&(g=0),y>=d&&(y=0),x>=p&&(x=0);return Ln(h,t.shape)},o.prototype.localResponseNormalization4D=function(t,e,n,r,o){Hh(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var c=s[r];u+=c*c}return u}for(var h=0;h<u;h++){var f=l(h),d=s[h]*Math.pow(n+r*f,-o);c[h]=d}return Ln(c,t.shape)},o.prototype.LRNGrad=function(t,e,n,r,o,a,i){Hh(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=this.readSync(n.dataId),h=new Float32Array(t.size),f=t.size,d=0;d<f;d++){for(var p=d%s,v=d-p+Math.max(0,p-r),m=d-p+Math.min(s,p+r+1),g=0,y=v;y<m;y++)g+=Math.pow(c[y],2);g=a*g+o;for(y=v;y<m;y++){var x=-2*a*i*c[y]*l[d]/g;d===y&&(x+=Math.pow(g,-i)),x*=u[d],h[y]+=x}}return Ln(h,t.shape)},o.prototype.multinomial=function(t,e,n,r){Hh(t,"multinomial");for(var o=e?t:go(t),a=o.shape[0],i=o.shape[1],s=Gn([a,n],"int32"),u=this.readSync(s.dataId),c=this.readSync(o.dataId),l=0;l<a;++l){var h=l*i,f=new Float32Array(i-1);f[0]=c[h];for(var d=1;d<f.length;++d)f[d]=f[d-1]+c[h+d];for(var p=cr(r.toString()),v=l*n,m=0;m<n;++m){var g=p();u[v+m]=f.length;for(var y=0;y<f.length;y++)if(g<f[y]){u[v+m]=y;break}}}return s},o.prototype.oneHot=function(t,e,n,r){Hh(t,"oneHot");var o=new Float32Array(t.size*e);o.fill(r);for(var a=this.readSync(t.dataId),i=0;i<t.size;++i)a[i]>=0&&a[i]<e&&(o[i*e+a[i]]=n);return Bn(o,[t.size,e],"int32")},o.prototype.nonMaxSuppression=function(t,e,n,r,o){return Hh(t,"nonMaxSuppression"),jo(this.readSync(t.dataId),this.readSync(e.dataId),n,r,o)},o.prototype.fft=function(t){return this.fftBatch(t,!1)},o.prototype.ifft=function(t){return this.fftBatch(t,!0)},o.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],o=dr(t.shape,"float32"),a=dr(t.shape,"float32"),i=Tn(t).as2D(n,r),s=Nn(t).as2D(n,r),u=0;u<n;u++)for(var c=i.slice([u,0],[1,r]),l=s.slice([u,0],[1,r]),h=Dn(c,l),f=this.readSync(this.fftImpl(h,e).dataId),d=0;d<r;d++){var p=zo(f,d);o.values[u*r+d]=p.real,a.values[u*r+d]=p.imag}return Dn(o.toTensor(),a.toTensor()).as2D(n,r)},o.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var o=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(o=Dn(Tn(o).div(On(r)),Nn(o).div(On(r)))),o}var a=this.readSync(t.dataId),i=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(a,r,e));return Dn(i.real,i.imag).as2D(t.shape[0],t.shape[1])},o.prototype.isExponentOf2=function(t){return 0==(t&t-1)},o.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),o=e/2,a=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=0;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),i=Dn(a.real,a.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=2;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),u=Dn(s.real,s.imag).as1D();i=this.fftRadix2(i,o,n),u=this.fftRadix2(u,o,n);var c=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),o=0;o<Math.ceil(t/2);o++){var a=(e?2:-2)*Math.PI*(o/t);n[o]=Math.cos(a),r[o]=Math.sin(a)}return{real:n,imag:r}}(e,n),l=Dn(c.real,c.imag).mul(u),h=i.add(l),f=i.sub(l),d=Tn(h).concat(Tn(f)),p=Nn(h).concat(Nn(f));return Dn(d,p).as1D()},o.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),o=0;o<e;o++){for(var a=0,i=0,s=0;s<e;s++){var u=Ho(o*s,e,n),c=zo(t,s);a+=c.real*u.real-c.imag*u.imag,i+=c.real*u.imag+c.imag*u.real}n&&(a/=e,i/=e),Go(r,a,i,o)}return r},o.prototype.depthToSpace=function(t,e,n){C("NHWC"===n,(function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n})),C(e>1,(function(){return"blockSize should be > 1 for depthToSpace, but was: "+e}));for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,c=i/(e*e),l=this.readSync(t.dataId),h=new Float32Array(r*s*u*c),f=0,d=0;d<r;++d)for(var p=0;p<s;++p)for(var v=Math.floor(p/e),m=p%e,g=0;g<u;++g)for(var y=Math.floor(g/e),x=(m*e+g%e)*c,b=0;b<c;++b){var w=b+x+i*(y+a*(v+o*d));h[f++]=l[w]}return Ln(h,[r,s,u,c])},o.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=Ro(t.shape,e.shape),a=dr(o,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Co(t.shape,o),c=Co(e.shape,o),l=a.values;if(u.length+c.length===0)for(var h=0;h<l.length;++h)l[h]=r(i[h%i.length],s[h%s.length]);else{var f=this.bufferSync(t),d=this.bufferSync(e),p=function(n){var o=a.indexToLoc(n),h=o.slice(-t.rank);u.forEach((function(t){return h[t]=0}));var p=f.locToIndex(h),v=o.slice(-e.rank);c.forEach((function(t){return v[t]=0}));var m=d.locToIndex(v);l[n]=r(i[p],s[m])};for(h=0;h<l.length;++h)p(h)}return a.toTensor()},o.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=Ro(t.shape,e.shape),o=dr(r,"float32"),a=dr(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Co(t.shape,r),c=Co(e.shape,r),l=o.values,h=a.values;if(u.length+c.length===0)for(var f=0;f<l.length;f++){var d=f%i.length,p=f%s.length,v=n(i[2*d],i[2*d+1],s[2*p],s[2*p+1]);l[f]=v.real,h[f]=v.imag}else{var m=this.bufferSync(this.data.get(t.dataId).complexTensors.real),g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var a=o.indexToLoc(r),f=a.slice(-t.rank);u.forEach((function(t){return f[t]=0}));var d=m.locToIndex(f),p=a.slice(-e.rank);c.forEach((function(t){return p[t]=0}));var v=g.locToIndex(p),y=n(i[2*d],i[2*d+1],s[2*v],s[2*v+1]);l[r]=y.real,h[r]=y.imag};for(f=0;f<l.length;f++)y(f)}return this.complex(o.toTensor(),a.toTensor())},o.prototype.split=function(t,e,n){return Zo(t,e,n)},o.prototype.dispose=function(){},o.prototype.floatPrecision=function(){return 32},o.prototype.epsilon=function(){return 1e-7},o.prototype.cropAndResize=function(t,e,n,r,o,a){for(var i=t.shape,s=i[0],u=i[1],c=i[2],l=i[3],h=e.shape[0],f=r[0],d=r[1],p=dr([h,f,d,l],"float32"),v=this.readSync(e.dataId),m=this.readSync(n.dataId),g=this.readSync(t.dataId),y=t.strides,x=p.strides,b=0;b<h;b++){var w=4*b,C=v[w],E=v[w+1],R=v[w+2],I=v[w+3],k=m[b];if(!(k>=s))for(var S=f>1?(R-C)*(u-1)/(f-1):0,A=d>1?(I-E)*(c-1)/(d-1):0,D=0;D<f;D++){var T=f>1?C*(u-1)+D*S:.5*(C+R)*(u-1);if(T<0||T>u-1)for(var N=0;N<d;N++)for(var F=0;F<l;F++){var _=F+N*x[2]+D*x[1]+b*x[0];p.values[_]=a}else if("bilinear"===o){var O=Math.floor(T),M=Math.ceil(T),B=T-O;for(N=0;N<d;N++){if((q=d>1?E*(c-1)+N*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++){_=F+N*x[2]+D*x[1]+b*x[0];p.values[_]=a}else{var P=Math.floor(q),L=Math.ceil(q),W=q-P;for(F=0;F<l;F++){var U=g[_=F+P*y[2]+O*y[1]+k*y[0]],V=g[_=F+L*y[2]+O*y[1]+k*y[0]],z=g[_=F+P*y[2]+M*y[1]+k*y[0]],G=U+(V-U)*W,H=z+(g[_=F+L*y[2]+M*y[1]+k*y[0]]-z)*W;_=F+N*x[2]+D*x[1]+b*x[0],p.values[_]=G+(H-G)*B}}}}else for(N=0;N<d;++N){var q;if((q=d>1?E*(c-1)+N*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++){_=F+N*x[2]+D*x[1]+b*x[0];p.values[_]=a}else{var K=Math.round(q),j=Math.round(T);for(F=0;F<l;F++){var X=F+K*y[2]+j*y[1]+k*y[0],Y=F+N*x[2]+D*x[1]+b*x[0];p.values[Y]=g[X]}}}}}return p.toTensor()},o.prototype.sparseToDense=function(t,e,n,r){var o=Zr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.sliceSize,u=o.strides,c=o.outputSize;return this.scatter(t,e,n,c,s,i,a,u,r,!1)},o.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=jr(t,e),a=o[0],i=o[1],s=o[2],u=o[3];if(0===i)return Fn([],a,t.dtype);for(var c=new gt([i,s],t.dtype),l=this.readSync(e.dataId),h=this.readSync(t.dataId),f=0;f<i;f++){for(var d=[],p=0,v=0;v<r;v++){var m=l[f*r+v];p+=m*u[v],d.push(m)}if(p<0||p>=t.size/s)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var g=0;g<s;g++)c.values[f*s+g]=h[p*s+g]}return c.toTensor().reshape(a)},o.prototype.scatterND=function(t,e,n){var r=Zr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=On(0);return this.scatter(t,e,n,u,i,a,o,s,c,!0)},o.prototype.fill=function(t,e,n){var r=P(n=n||j(e),k(t));return r.fill(e),Lt.makeTensor(r,t,n,this)},o.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},o.prototype.zerosLike=function(t){var e=P(t.dtype,k(t.shape));return this.makeOutput(e,t.shape,t.dtype)},o.prototype.linspace=function(t,e,n){return Wo(t,e,n)},o.prototype.scatter=function(t,e,n,r,o,a,i,s,u,c){var l=[r/o,o],h=this.readSync(t.dataId),f=this.readSync(e.dataId);if(0===r)return Fn([],n,e.dtype);var d=new gt(l,e.dtype);d.values.fill(this.readSync(u.dataId)[0]);for(var p=0;p<a;p++){for(var v=[],m=0,g=0;g<i;g++){var y=h[p*i+g];v.push(y),m+=y*s[g]}if(m<0||m>=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var x=0;x<o;x++)c?d.values[m*o+x]+=f[p*o+x]:d.values[m*o+x]=0===e.rank?f[0]:f[p*o+x]}return d.toTensor().reshape(n)},o}(bo);Lt.registerBackend("cpu",(function(){return new Kh}),1);for(var jh=0,Xh=[{kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e,a=o.boxes,i=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=n;Hh(a,"NonMaxSuppressionWithScore");var d=Xo(f.data.get(a.dataId).values,f.data.get(i.dataId).values,u,c,l,h);return[d.selectedIndices,d.selectedScores]}},{kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n;Hh(r,"square");for(var a=o.data.get(r.dataId).values,i=new Float32Array(a.length),s=0;s<a.length;++s){var u=a[s];i[s]=u*u}return{dataId:o.write(i,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},{kernelName:eu,backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,a=r.b,i=n;Hh([o,a],eu);var s=i.data.get(o.dataId).values,u=i.data.get(a.dataId).values,c=function(t,e,n,r,o,a){var i=Ro(t,e),s=i.length,u=$(i),c=B(o,k(i)),l=t.length,h=e.length,f=$(t),d=$(e),p=Co(t,i),v=Co(e,i);if(p.length+v.length===0)for(var m=0;m<c.length;++m)c[m]=a(n[m%n.length],r[m%r.length]);else{var g=function(t){var e=it(t,s,u),o=e.slice(-l);p.forEach((function(t){return o[t]=0}));var i=at(o,l,f),m=e.slice(-h);v.forEach((function(t){return m[t]=0}));var g=at(m,h,d);c[t]=a(n[i],r[g])};for(m=0;m<c.length;++m)g(m)}return[c,i]}(o.shape,a.shape,s,u,o.dtype,(function(t,e){var n=t-e;return n*n})),l=c[0],h=c[1];return{dataId:i.write(l,h,o.dtype),shape:h,dtype:o.dtype}}}];jh<Xh.length;jh++){d(Xh[jh])}var Yh,$h=function(t){this.variableNames=["A"];var e=ua(),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 "},Qh=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=ua(),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) /\n 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 "};for(var Jh=0,Zh=[{kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs,o=e.pixels,a=r.numChannels,s="undefined"!=typeof HTMLVideoElement&&o instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&o instanceof HTMLImageElement,c=s?[o.videoWidth,o.videoHeight]:[o.width,o.height],l=c[0],h=c[1],f=[h,l],d=[h,l,a];(u||s)&&(null==Yh&&(Yh=document.createElement("canvas").getContext("2d")),Yh.canvas.width=l,Yh.canvas.height=h,Yh.drawImage(o,0,0,l,h),o=Yh.canvas);var p=n.makeTensorInfo(f,"int32");n.texData.get(p.dataId).usage=zt.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),o);var v=i().getBool("WEBGL_PACK")?new Qh(d):new $h(d),m=n.runWebGLProgram(v,[p],"int32");return n.disposeData(p.dataId),m}},{kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=t.attrs;dn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");var o=e,a=o.boxes,i=o.scores,s=r,u=s.maxOutputSize,c=s.iouThreshold,l=s.scoreThreshold,h=s.softNmsSigma,f=n,d=Xo(f.readSync(a.dataId),f.readSync(i.dataId),u,c,l,h);return[d.selectedIndices,d.selectedScores]}},{kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n,a=new Cs(r.shape,"return x * x;");return o.runWebGLProgram(a,[r],r.dtype)}},{kernelName:eu,backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e,o=r.a,a=r.b,s=n,u=i().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new La("return (a - b) * (a - b);",o.shape,a.shape):new Ba("return (a - b) * (a - b);",o.shape,a.shape);return s.compileAndRun(u,[o,a])}}];Jh<Zh.length;Jh++){d(Zh[Jh])}for(var tf=0,ef=[{kernelName:"Square",gradFunc:function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().mul(2))}}}},{kernelName:eu,gradFunc:function(t,e){var n=e[0],r=e[1],o=On(2);return{a:function(){return gc(t,gc(o,Cc(n,r)))},b:function(){return gc(t,gc(o,Cc(r,n)))}}}}];tf<ef.length;tf++){p(ef[tf])}var nf=function(){function t(){}return t.prototype.fetch=function(t,e){return fetch(t,e)},t.prototype.now=function(){return performance.now()},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();i().get("IS_BROWSER")&&i().setPlatform("browser",new nf);var rf,of=function(){return __webpack_require__(302)},af=function(){function t(){this.util=__webpack_require__(301),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=i().global.fetch?i().global.fetch(t,e):(null==rf&&(rf=of()),rf(t,e))},t.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t)},t}();i().get("IS_NODE")&&i().setPlatform("node",new af);var sf={float32:4,int32:4,uint16:2,uint8:1,bool:1},uf=4;function cf(t,e){for(var n={},r=0,o=function(e){var o=e.name,a=e.dtype,i=e.shape,s=k(i),u=void 0;if("quantization"in e){var c=e.quantization;if("uint8"!==c.dtype&&"uint16"!==c.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+c.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=sf[c.dtype],h=t.slice(r,r+s*l),f="uint8"===c.dtype?new Uint8Array(h):new Uint16Array(h);if("float32"===a)u=Float32Array.from(f,(function(t){return t*c.scale+c.min}));else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=Int32Array.from(f,(function(t){return Math.round(t*c.scale+c.min)}))}r+=s*l}else if("string"===a){var d=k(e.shape);u=[];for(var p=0;p<d;p++){var v=new Uint32Array(t.slice(r,r+uf))[0];r+=uf;var m=new Uint8Array(t.slice(r,r+v));u.push(m),r+=v}}else{var g=sf[a];h=t.slice(r,r+s*g);if("float32"===a)u=new Float32Array(h);else if("int32"===a)u=new Int32Array(h);else{if("bool"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=new Uint8Array(h)}r+=s*g}n[o]=Fn(u,i,a)},a=0,i=e;a<i.length;a++){o(i[a])}return n}function lf(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach((function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)}));var r=new Uint8Array(e),o=0;return n.forEach((function(t){r.set(new Uint8Array(t.buffer),o),o+=t.byteLength})),r.buffer}var hf="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function ff(t){return hf?Buffer.byteLength(t):new Blob([t]).size}function df(t){var e=0;t.forEach((function(t){e+=t.byteLength}));var n=new Uint8Array(e),r=0;return t.forEach((function(t){n.set(new Uint8Array(t),r),r+=t.byteLength})),n.buffer}function pf(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function vf(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:ff(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:ff(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var mf=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var o=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach((function(t){var n=t(e,r);null!==n&&o.push(n)})),o},t}(),gf="://",yf=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){C(null!=e,(function(){return"scheme must not be undefined or null."})),e.endsWith(gf)&&(e=e.slice(0,e.indexOf(gf))),C(e.length>0,(function(){return"scheme must not be an empty string."}));var r=t.getInstance();C(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 xf(t){if(-1===t.indexOf(gf))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+yf.getSchemes().join(","));return{scheme:t.split(gf)[0],path:t.split(gf)[1]}}function bf(t,e,o){return void 0===o&&(o=!1),n(this,void 0,void 0,(function(){var n,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return C(t!==e,(function(){return"Old path and new path are the same: '"+t+"'"})),C((n=mf.getLoadHandlers(t)).length>0,(function(){return"Copying failed because no load handler is found for source URL "+t+"."})),C(n.length<2,(function(){return"Copying failed because more than one ("+n.length+") load handlers for source URL "+t+"."})),a=n[0],C((i=mf.getSaveHandlers(e)).length>0,(function(){return"Copying failed because no save handler is found for destination URL "+e+"."})),C(i.length<2,(function(){return"Copying failed because more than one ("+n.length+") save handlers for destination URL "+e+"."})),s=i[0],u=xf(t).scheme,c=xf(t).path,l=u===xf(t).scheme,[4,a.load()];case 1:return h=r.sent(),o&&l?[4,yf.getManager(u).removeModel(c)]:[3,3];case 2:r.sent(),r.label=3;case 3:return[4,s.save(h)];case 4:return f=r.sent(),!o||l?[3,6]:[4,yf.getManager(u).removeModel(c)];case 5:r.sent(),r.label=6;case 6:return[2,f.modelArtifactsInfo]}}))}))}var wf="models_store",Cf="model_info_store";function Ef(){if(!i().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window||self,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 Rf(t){var e=t.result;e.createObjectStore(wf,{keyPath:"modelPath"}),e.createObjectStore(Cf,{keyPath:"modelPath"})}var If=function(){function t(t){if(this.indexedDB=Ef(),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 n(this,void 0,void 0,(function(){return r(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 n(this,void 0,void 0,(function(){return r(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 o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Rf(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(wf,"readonly"),s=i.objectStore(wf).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},i.oncomplete=function(){return a.close()}}else{var u,c=vf(e),l=a.transaction(Cf,"readwrite"),h=l.objectStore(Cf),f=h.put({modelPath:n.modelPath,modelArtifactsInfo:c});f.onsuccess=function(){var o=(u=a.transaction(wf,"readwrite")).objectStore(wf).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});o.onsuccess=function(){return t({modelArtifactsInfo:c})},o.onerror=function(t){var e=(h=l.objectStore(Cf)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)}}},f.onerror=function(t){return a.close(),r(f.error)},l.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},o.onerror=function(t){return r(o.error)}}))},t.URL_SCHEME="indexeddb://",t}(),kf=function(t){return i().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(If.URL_SCHEME)?(e=t.slice(If.URL_SCHEME.length),new If(e)):null;var e};mf.registerSaveRouter(kf),mf.registerLoadRouter(kf);var Sf=function(){function t(){this.indexedDB=Ef()}return t.prototype.listModels=function(){return n(this,void 0,void 0,(function(){var t=this;return r(this,(function(e){return[2,new Promise((function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Rf(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(Cf,"readonly"),a=o.objectStore(Cf).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n<r.length;n++){var o=r[n];t[o.modelPath]=o.modelArtifactsInfo}e(t)},a.onerror=function(e){return t.close(),n(a.error)},o.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}}))]}))}))},t.prototype.removeModel=function(t){return n(this,void 0,void 0,(function(){var e=this;return r(this,(function(n){var r;return t=(r=t).startsWith(If.URL_SCHEME)?r.slice(If.URL_SCHEME.length):r,[2,new Promise((function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Rf(o)},o.onsuccess=function(){var e,a=o.result,i=a.transaction(Cf,"readwrite"),s=i.objectStore(Cf),u=s.get(t);u.onsuccess=function(){if(null==u.result)return a.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var o=s.delete(t),i=function(){var o=(e=a.transaction(wf,"readwrite")).objectStore(wf).delete(t);o.onsuccess=function(){return n(u.result.modelArtifactsInfo)},o.onerror=function(t){return r(u.error)}};o.onsuccess=i,o.onerror=function(t){return i(),a.close(),r(u.error)}},u.onerror=function(t){return a.close(),r(u.error)},i.oncomplete=function(){null==e?a.close():e.oncomplete=function(){return a.close()}}},o.onerror=function(t){return r(o.error)}}))]}))}))},t}();if(i().getBool("IS_BROWSER"))try{yf.registerManager(If.URL_SCHEME,new Sf)}catch(t){}var Af="/",Df="tensorflowjs_models",Tf="info",Nf="model_topology",Ff="weight_specs",_f="weight_data",Of="model_metadata";function Mf(t){return{info:[Df,t,Tf].join(Af),topology:[Df,t,Nf].join(Af),weightSpecs:[Df,t,Ff].join(Af),weightData:[Df,t,_f].join(Af),modelMetadata:[Df,t,Of].join(Af)}}function Bf(t){var e=t.split(Af);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(Af)}var Pf=function(){function t(t){if(!i().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=Mf(this.modelPath)}return t.prototype.save=function(t){return n(this,void 0,void 0,(function(){var e,n,o;return r(this,(function(r){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),o=vf(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(t){if(hf)return Buffer.from(t).toString("base64");for(var e=new Uint8Array(t),n="",r=0,o=e.length;r<o;r++)n+=String.fromCharCode(e[r]);return btoa(n)}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata})),[2,{modelArtifactsInfo:o}]}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+o.modelTopologyBytes+", weightSpecsBytes="+o.weightSpecsBytes+", weightDataBytes="+o.weightDataBytes+".")}return[2]}))}))},t.prototype.load=function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i,s;return r(this,(function(r){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(o=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=o,null!=(a=this.LS.getItem(this.keys.modelMetadata))&&(i=JSON.parse(a),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy,e.userDefinedMetadata=i.userDefinedMetadata),null==(s=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(hf){var e=Buffer.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var n=atob(t),r=new Uint8Array(n.length),o=0;o<n.length;++o)r.set([n.charCodeAt(o)],o);return r.buffer}(s),[2,e]}))}))},t.URL_SCHEME="localstorage://",t}(),Lf=function(t){return i().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Pf.URL_SCHEME)?(e=t.slice(Pf.URL_SCHEME.length),new Pf(e)):null;var e};mf.registerSaveRouter(Lf),mf.registerLoadRouter(Lf);var Wf=function(){function t(){C(i().getBool("IS_BROWSER"),(function(){return"Current environment is not a web browser"})),C("undefined"==typeof window||void 0!==window.localStorage,(function(){return"Current browser does not appear to support localStorage"})),this.LS=window.localStorage}return t.prototype.listModels=function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i;return r(this,(function(r){for(t={},e=Df+Af,n=Af+Tf,o=0;o<this.LS.length;++o)(a=this.LS.key(o)).startsWith(e)&&a.endsWith(n)&&(i=Bf(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t]}))}))},t.prototype.removeModel=function(t){return n(this,void 0,void 0,(function(){var e,n;return r(this,(function(r){var o;if(t=(o=t).startsWith(Pf.URL_SCHEME)?o.slice(Pf.URL_SCHEME.length):o,e=Mf(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n]}))}))},t}();if(i().getBool("IS_BROWSER"))try{yf.registerManager(Pf.URL_SCHEME,new Wf)}catch(t){}var Uf="model",Vf=".json",zf=".weights.bin";function Gf(t){return new Promise((function(t){return setTimeout(t)})).then(t)}var Hf=function(){function t(e){if(!i().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e=Uf),this.modelTopologyFileName=e+Vf,this.weightDataFileName=e+zf}return t.prototype.save=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,i,s;return r(this,(function(r){switch(r.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),(i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,Gf((function(){return i.dispatchEvent(new MouseEvent("click"))}))];case 2:return r.sent(),null==t.weightData?[3,4]:((s=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,Gf((function(){return s.dispatchEvent(new MouseEvent("click"))}))]);case 3:r.sent(),r.label=4;case 4:return[2,{modelArtifactsInfo:vf(t)}]}}))}))},t.URL_SCHEME="downloads://",t}(),qf=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return n(this,void 0,void 0,(function(){var t,e,n=this;return r(this,(function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise((function(r,o){var a=new FileReader;a.onload=function(a){var i=JSON.parse(a.target.result),s=i.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=i.weightsManifest;if(null!=u){var c;try{c=n.checkManifestAndWeightFiles(u,e)}catch(t){return void o(t)}var l=[],h=[],f=[];u.forEach((function(t){t.paths.forEach((function(t){h.push(t),f.push(null)})),l.push.apply(l,t.weights)})),u.forEach((function(t){t.paths.forEach((function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,o=h.indexOf(t);f[o]=n,-1===f.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:df(f),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy,userDefinedMetadata:i.userDefinedMetadata})},e.onerror=function(e){return o("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(c[t])}))}))}else o(new Error("weightManifest field is missing from file "+t.name))}else o(new Error("modelTopology field is missing from file "+t.name))},a.onerror=function(e){return o("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},a.readAsText(t)}))]}))}))},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map((function(t){return pf(t.name)})),o={},a=0,i=t;a<i.length;a++){i[a].paths.forEach((function(t){var a=pf(t);if(-1!==n.indexOf(a))throw new Error("Duplicate file basename found in weights manifest: '"+a+"'");if(n.push(a),-1===r.indexOf(a))throw new Error("Weight file with basename '"+a+"' is not provided.");o[t]=e[r.indexOf(a)]}))}if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return o},t}();function Kf(t,e,n,r){!function(t){C(null!=t&&Array.isArray(t)&&t.length>0,(function(){return"promises must be a none empty array"}))}(t),function(t,e){C(t>=0&&t<=1,(function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t})),C(e>=0&&e<=1,(function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e})),C(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 o=0;return Promise.all(t.map((function(a){return a.then((function(a){var i=n+ ++o/t.length*(r-n);return e(i),a})),a})))}function jf(t,e){return n(this,void 0,void 0,(function(){var n,o,a,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?i().platform.fetch:e.fetchFunc,o=t.map((function(t){return n(t,e.requestInit,{isBinary:!0})})),a=0,s=.5,null!=e.onProgress?[3,2]:[4,Promise.all(o)];case 1:return u=r.sent(),[3,4];case 2:return[4,Kf(o,e.onProgress,a,s)];case 3:u=r.sent(),r.label=4;case 4:return c=u.map((function(t){return t.arrayBuffer()})),l=.5,h=1,null!=e.onProgress?[3,6]:[4,Promise.all(c)];case 5:return f=r.sent(),[3,8];case 6:return[4,Kf(c,e.onProgress,l,h)];case 7:f=r.sent(),r.label=8;case 8:return[2,f]}}))}))}function Xf(t){var e=this;return function(o,a,i){return void 0===a&&(a=""),n(e,void 0,void 0,(function(){var e,n,s,u,c,l,h,f,d,p;return r(this,(function(r){switch(r.label){case 0:if(e=o.map((function(){return!1})),n={},s=null!=i?i.map((function(){return!1})):[],u=[],o.forEach((function(t,r){var o=0;t.weights.forEach((function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,c=sf[a]*k(t.shape),l=function(){e[r]=!0,null==n[r]&&(n[r]=[]),n[r].push({manifestEntry:t,groupOffset:o,sizeBytes:c})};null!=i?i.forEach((function(e,n){e===t.name&&(l(),s[n]=!0)})):l(),u.push(t.name),o+=c}))})),!s.every((function(t){return t})))throw c=i.filter((function(t,e){return!s[e]})),new Error("Could not find weights in manifest with names: "+c.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return l=e.reduce((function(t,e,n){return e&&t.push(n),t}),[]),h=[],l.forEach((function(t){o[t].paths.forEach((function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e)}))})),[4,t(h)];case 1:return f=r.sent(),d={},p=0,l.forEach((function(t){for(var e=o[t].paths.length,r=0,a=0;a<e;a++)r+=f[p+a].byteLength;for(var i=new ArrayBuffer(r),s=new Uint8Array(i),u=0,c=0;c<e;c++){var l=new Uint8Array(f[p+c]);s.set(l,u),u+=l.byteLength}n[t].forEach((function(t){var e=cf(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)d[n]=e[n]})),p+=e})),[2,d]}}))}))}}mf.registerSaveRouter((function(t){return i().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Hf.URL_SCHEME)?function(t){void 0===t&&(t="model");return new Hf(t)}(t.slice(Hf.URL_SCHEME.length)):null}));var Yf=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(C("function"==typeof e.fetchFunc,(function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"})),this.fetch=e.fetchFunc):this.fetch=i().platform.fetch,C(null!=t&&t.length>0,(function(){return"URL path for http must not be null, undefined or empty."})),Array.isArray(t)&&C(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 n(this,void 0,void 0,(function(){var e,n,o,a;return r(this,(function(r){switch(r.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}],o={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(o)],{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((a=r.sent()).ok)return[2,{modelArtifactsInfo:vf(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}}))}))},t.prototype.load=function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=r.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.");r.label=2;case 2:return r.trys.push([2,4,,5]),[4,t.json()];case 3:return e=r.sent(),[3,5];case 4:throw r.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(o=e.modelTopology,a=e.weightsManifest,i=e.generatedBy,s=e.convertedBy,u=e.format,c=e.userDefinedMetadata,null==o&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:f=r.sent(),l=f[0],h=f[1],r.label=7;case 7:return[2,{modelTopology:o,weightSpecs:l,weightData:h,userDefinedMetadata:c,generatedBy:i,convertedBy:s,format:u}]}}))}))},t.prototype.loadWeights=function(t){return n(this,void 0,void 0,(function(){var e,n,o,a,i,s,u,c,l,h,f;return r(this,(function(r){switch(r.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return[r+"/",o]}(e),o=n[0],a=n[1],i=this.weightPathPrefix||o,s=[],u=0,c=t;u<c.length;u++)l=c[u],s.push.apply(s,l.weights);return h=[],t.forEach((function(t){t.paths.forEach((function(t){h.push(i+t+a)}))})),[4,jf(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return f=r.sent(),[2,[s,df(f)]]}}))}))},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function $f(t){return null!=t.match(Yf.URL_SCHEME_REGEX)}var Qf=function(t,e){if("undefined"==typeof fetch)return null;return(Array.isArray(t)?t.every((function(t){return $f(t)})):$f(t))?Jf(t,{onProgress:e}):null};function Jf(t,e){return new Yf(t,e)}mf.registerSaveRouter(Qf),mf.registerLoadRouter(Qf);var Zf=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){return[2,this.modelArtifacts]}))}))},t}(),td=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){return[2,this.saveHandler(t)]}))}))},t}();var ed=Object.freeze({browserFiles:function(t){return new qf(t)},browserHTTPRequest:function(t,e){return Jf(t,e)},concatenateArrayBuffers:df,decodeWeights:cf,encodeWeights:function(t,e){return n(this,void 0,void 0,(function(){var o,a,i,s,u,c=this;return r(this,(function(l){switch(l.label){case 0:for(o=[],a=[],i=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t),s=function(s){var u=i[s],l=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+l.dtype);var h={name:u,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var f=new Promise((function(t){return n(c,void 0,void 0,(function(){var e,n,o,a,i,s,u;return r(this,(function(r){switch(r.label){case 0:return[4,l.bytes()];case 1:for(e=r.sent(),n=e.reduce((function(t,e){return t+e.length}),0)+uf*e.length,o=new Uint8Array(n),a=0,i=0;i<e.length;i++)s=e[i],u=new Uint8Array(new Uint32Array([s.length]).buffer),o.set(u,a),a+=uf,o.set(s,a),a+=s.length;return t(o),[2]}}))}))}));a.push(f)}else a.push(l.data());null!=e&&(h.group=e),o.push(h)},u=0;u<i.length;++u)s(u);return[4,Promise.all(a)];case 1:return[2,{data:lf(l.sent()),specs:o}]}}))}))},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Zf(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Zf({modelTopology:t})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Zf({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return mf.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:vf,getSaveHandlers:function(t){return mf.getSaveHandlers(t)},http:Jf,isHTTPScheme:$f,loadWeights:function(t,e,o,a){return void 0===e&&(e=""),n(this,void 0,void 0,(function(){return r(this,(function(n){return[2,Xf((function(t){return jf(t,{requestInit:a})}))(t,e,o)]}))}))},registerLoadRouter:function(t){return mf.registerLoadRouter(t)},registerSaveRouter:function(t){return mf.registerSaveRouter(t)},weightsLoaderFactory:Xf,withSaveHandler:function(t){return new td(t)},copyModel:function(t,e){return n(this,void 0,void 0,(function(){return r(this,(function(n){return!1,[2,bf(t,e,!1)]}))}))},listModels:function(){return n(this,void 0,void 0,(function(){var t,e,n,o,a,i,s;return r(this,(function(r){switch(r.label){case 0:t=yf.getSchemes(),e={},n=0,o=t,r.label=1;case 1:return n<o.length?(a=o[n],[4,yf.getManager(a).listModels()]):[3,4];case 2:for(s in i=r.sent())e[a+gf+s]=i[s];r.label=3;case 3:return n++,[3,1];case 4:return[2,e]}}))}))},moveModel:function(t,e){return n(this,void 0,void 0,(function(){return r(this,(function(n){return!0,[2,bf(t,e,!0)]}))}))},removeModel:function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){return e=xf(t),[2,yf.getManager(e.scheme).removeModel(e.path)]}))}))}});var nd,rd=An({confusionMatrix_:function(t,e,n){var r=mn(t,"labels","confusionMatrix"),o=mn(e,"predictions","confusionMatrix");C(null==n||n>0&&Number.isInteger(n),(function(){return"If provided, numClasses must be a positive integer, but got "+n})),C(1===r.rank,(function(){return"Expected the rank of labels to be 1, but got "+r.rank})),C(1===o.rank,(function(){return"Expected the rank of predictions to be 1, but got "+o.rank})),C(r.shape[0]===o.shape[0],(function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."})),C(n>0&&Number.isInteger(n),(function(){return"numClasses is required to be a positive integer, but got "+n}));var a=Rr(r.asType("int32"),n),i=Rr(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),od=Object.freeze({confusionMatrix:rd});var ad=An({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.");if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=!1,r=!1,o=!1,a=!1,i=!1;if(t.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&t instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement)o=!0;else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement)a=!0;else{if(null==t.getContext)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);i=!0}if(o){if(o&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(null!=l("FromPixels",Lt.backendName))return Lt.runKernel("FromPixels",{pixels:t},{numChannels:e});var s,u,c=o?[t.videoWidth,t.videoHeight]:[t.width,t.height],h=c[0],f=c[1];if(i?s=t.getContext("2d").getImageData(0,0,h,f).data:r||n?s=t.data:(a||o)&&(null==nd&&(nd=document.createElement("canvas").getContext("2d")),nd.canvas.width=h,nd.canvas.height=f,nd.drawImage(t,0,0,h,f),s=nd.getImageData(0,0,h,f).data),4===e)u=new Int32Array(s);else{var d=h*f;u=new Int32Array(d*e);for(var p=0;p<d;p++)for(var v=0;v<e;++v)u[p*e+v]=s[4*p+v]}return Pn(u,[f,h,e],"int32")}}),id=Object.freeze({toPixels:function(t,e){return n(this,void 0,void 0,(function(){var n,o,a,i,s,u,c,l,h,f,d,p,v,m,g,y,x,b,w,C,E,R,I;return r(this,(function(r){switch(r.label){case 0:if(n=mn(t,"img","toPixels"),t instanceof wt||(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(o=n.shape.slice(0,2),a=o[0],i=o[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return[4,n.data()];case 1:return u=r.sent(),c=n.min(),l=n.max(),[4,Promise.all([c.data(),l.data()])];case 2:if(h=r.sent(),f=h[0],d=h[1],p=f[0],v=d[0],c.dispose(),l.dispose(),"float32"===n.dtype){if(p<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+p+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(p<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+p+" - "+v+"].")}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(i*a*4),y=0;y<a*i;++y)x=void 0,b=void 0,w=void 0,C=void 0,1===s?(x=u[y]*m,b=u[y]*m,w=u[y]*m,C=255):3===s?(x=u[3*y]*m,b=u[3*y+1]*m,w=u[3*y+2]*m,C=255):4===s&&(x=u[4*y]*m,b=u[4*y+1]*m,w=u[4*y+2]*m,C=u[4*y+3]*m),g[(E=4*y)+0]=Math.round(x),g[E+1]=Math.round(b),g[E+2]=Math.round(w),g[E+3]=Math.round(C);return null!=e&&(e.width=i,e.height=a,R=e.getContext("2d"),I=new ImageData(g,i,a),R.putImageData(I,0,0)),n!==t&&n.dispose(),[2,g]}}))}))},fromPixels:ad}),sd=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),ud=function(){function t(){this.classNameMap={}}return t.getMap=function(){return null==t.instance&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function cd(t){C(null!=t.className,(function(){return"Class being registered does not have the static className property defined."})),C("string"==typeof t.className,(function(){return"className is required to be a string, but got type "+typeof t.className})),C(t.className.length>0,(function(){return"Class being registered has an empty-string as its className, which is disallowed."})),ud.register(t)}var ld=Object.freeze({Serializable:sd,SerializationMap:ud,registerClass:cd}),hd=.001,fd=.1;function dd(){return 32===Lt.backend.floatPrecision()?hd:fd}function pd(t,e,n){var r=!0;if((V(t)||V(e))&&(r=!1),V(t)&&V(e)&&(r=!0),r){var o=t.constructor.name,a=e.constructor.name;if(o!==a)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+a)}if(Array.isArray(t)&&Array.isArray(e)){var i=pn(t),s=pn(e);if(!S(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=V(t)?t:I(t),c=V(e)?e:I(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;l<c.length;++l){var h=u[l],f=c[l];if(!n(h,f))throw new Error("Arrays differ: actual["+l+"] = "+h+", expected["+l+"] = "+f+".\nActual: "+u+".\nExpected: "+c+".")}}function vd(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var md=Object.freeze({TEST_EPSILON_FLOAT16:fd,expectArraysClose:function(t,e,n){return null==n&&(n=dd()),pd(t,e,(function(t,e){return vd(t,e,n)}))},testEpsilon:dd,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 H(t)||H(t[0])||H(e)||H(e[0])?pd(t,n,(function(t,e){return t==e})):pd(t,e,(function(t,e){return vd(t,e,0)}))},expectNumbersClose:function(t,e,n){if(null==n&&(n=dd()),!vd(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;r<t.length;r++)if(t[r]<e||t[r]>n)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))}}),gd="1.7.0";var yd=Object.freeze({gpgpu_util:Mi,webgl_util:Ge,forceHalfFloat:function(){i().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Zs,setWebGLContext:Kt,GPGPUContext:Bi}),xd=function(t){function o(){return null!==t&&t.apply(this,arguments)||this}return e(o,t),o.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,a=r.grads;if(null!=n){var i=n.map((function(t){return{name:t.name,tensor:a[t.name]}}));this.applyGradients(i)}else this.applyGradients(a);return tn(a),e?o:(o.dispose(),null)},Object.defineProperty(o.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),o.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},o.prototype.computeGradients=function(t,e){return po(t,e)},o.prototype.dispose=function(){null!=this.iterations_&&tn(this.iterations_)},o.prototype.saveIterations=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:On(this.iterations_,"int32")}]}))}))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}))}))},o.prototype.extractIterations=function(t){return n(this,void 0,void 0,(function(){var e;return r(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)]}}))}))},o}(sd);Object.defineProperty(xd,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var bd=function(t){function o(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=Lt.backend.epsilon()),o}return e(o,t),o.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 o=Lt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Ze((function(){return Xn(o).variable(!1)}))}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Ze((function(){return Xn(o).variable(!1)}))});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Ze((function(){var t=i.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u)}))}})),this.incrementIterations()},o.prototype.dispose=function(){null!=this.accumulatedUpdates&&(tn(this.accumulatedGrads.map((function(t){return t.variable}))),tn(this.accumulatedUpdates.map((function(t){return t.variable}))))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){var t;return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){var e;return r(this,(function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,!1,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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},o.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},o.className="Adadelta",o}(xd);cd(bd);var wd=function(t){function o(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return e(o,t),o.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 o=Lt.registeredVariables[n];if(null==e.accumulatedGrads[r]){e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Ze((function(){return Hn(o.shape,e.initialAccumulatorValue).variable(!1)}))}}var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable;Ze((function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(Lt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)}))}})),this.incrementIterations()},o.prototype.dispose=function(){null!=this.accumulatedGrads&&tn(this.accumulatedGrads.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),!1,this.accumulatedGrads=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},o.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},o.className="Adagrad",o}(xd);cd(wd);var Cd=function(t){function o(e,n,r,o){void 0===o&&(o=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],Ze((function(){a.accBeta1=On(n).variable(),a.accBeta2=On(r).variable()})),null==o&&(a.epsilon=Lt.backend.epsilon()),a}return e(o,t),o.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Ze((function(){var r=Cc(1,e.accBeta1),o=Cc(1,e.accBeta2);n.forEach((function(n,a){var i=Lt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Ze((function(){return Xn(i).variable(!1)}))}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:Ze((function(){return Xn(i).variable(!1)}))});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedSecondMoment[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),f=l.div(r),d=h.div(o);u.assign(l),c.assign(h);var p=f.div(d.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(p)}})),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))})),this.incrementIterations()},o.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&tn(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedSecondMoment&&tn(this.accumulatedSecondMoment.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){var t;return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){var e,n=this;return r(this,(function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Ze((function(){n.accBeta1.assign(xc(n.beta1,n.iterations_+1)),n.accBeta2.assign(xc(n.beta2,n.iterations_+1))})),e=t.length/2,!1,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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},o.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},o.className="Adam",o}(xd);cd(Cd);var Ed=function(t){function o(e,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.decay=a,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Ze((function(){i.iteration=On(0).variable(),i.accBeta1=On(n).variable()})),null==o&&(i.epsilon=Lt.backend.epsilon()),i}return e(o,t),o.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map((function(t){return t.name})):Object.keys(t);Ze((function(){var r=Cc(1,e.accBeta1),o=sc(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach((function(n,a){var i=Lt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Xn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:Xn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedWeightedInfNorm[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=c.mul(e.beta2),f=s.abs(),d=h.maximum(f);u.assign(l),c.assign(d);var p=o.div(r).mul(l.div(d.add(e.epsilon))).add(i);i.assign(p)}})),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))})),this.incrementIterations()},o.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&tn(this.accumulatedFirstMoment.map((function(t){return t.variable}))),null!=this.accumulatedWeightedInfNorm&&tn(this.accumulatedWeightedInfNorm.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("getWeights() is not implemented for Adamax yet.")}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(t){throw new Error("setWeights() is not implemented for Adamax yet.")}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},o.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},o.className="Adamax",o}(xd);cd(Ed);var Rd=function(t){function o(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return e(o,t),o.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 o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=Lt.registeredVariables[n];Ze((function(){var t=e.c.mul(o).add(a);a.assign(t)}))}})),this.incrementIterations()},o.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=en(On(-t))},o.prototype.dispose=function(){this.c.dispose()},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate}},o.fromConfig=function(t,e){return new t(e.learningRate)},o.className="SGD",o}(xd);cd(Rd);var Id=function(t){function o(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=On(o.momentum),o}return e(o,t),o.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 o=Lt.registeredVariables[n];if(null==e.accumulations[r]){e.accumulations[r]={originalName:n+"/momentum",variable:Ze((function(){return Xn(o).variable(!1)}))}}var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Ze((function(){var t,n=e.m.mul(a).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),a.assign(n),o.assign(t)}))})),this.incrementIterations()},o.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&tn(this.accumulations.map((function(t){return t.variable})))},o.prototype.setMomentum=function(t){this.momentum=t},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){return r(this,(function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),!1,this.accumulations=t.map((function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},o.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},o.className="Momentum",o}(Rd);cd(Id);var kd=function(t){function o(e,n,r,o,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===a&&(a=!1);var i=t.call(this)||this;if(i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=o,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=a,null==o&&(i.epsilon=Lt.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.");return i}return e(o,t),o.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 o=Lt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Ze((function(){return Xn(o).variable(!1)}))}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Ze((function(){return Xn(o).variable(!1)}))}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Ze((function(){return Xn(o).variable(!1)}))});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Ze((function(){var t=i.mul(e.decay).add(a.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(a.mul(1-e.decay)),c=s.mul(e.momentum).add(a.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(c);var l=o.sub(c);o.assign(l)}else{var h=i.mul(e.decay).add(a.square().mul(1-e.decay));c=s.mul(e.momentum).add(a.mul(e.learningRate).div(h.add(e.epsilon).sqrt()));i.assign(h),s.assign(c);l=o.sub(c);o.assign(l)}}))}})),this.incrementIterations()},o.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&tn(this.accumulatedMeanSquares.map((function(t){return t.variable}))),null!=this.accumulatedMeanGrads&&this.centered&&tn(this.accumulatedMeanGrads.map((function(t){return t.variable}))),null!=this.accumulatedMoments&&tn(this.accumulatedMoments.map((function(t){return t.variable})))},o.prototype.getWeights=function(){return n(this,void 0,void 0,(function(){var t;return r(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}})))]}}))}))},o.prototype.setWeights=function(t){return n(this,void 0,void 0,(function(){var e;return r(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,!1,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]}}))}))},o.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},o.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},o.className="RMSProp",o}(xd);cd(kd);var Sd=function(){function t(){}return t.sgd=function(t){return new Rd(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Id(t,e,n)},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new kd(t,e,n,r,o)},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 Cd(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 bd(t,e,n)},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new Ed(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new wd(t,e)},t}(),Ad={sgd:Sd.sgd,momentum:Sd.momentum,adadelta:Sd.adadelta,adagrad:Sd.adagrad,rmsprop:Sd.rmsprop,adamax:Sd.adamax,adam:Sd.adam},Dd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function Td(){return new Promise((function(t){return Dd((function(){return t()}))}))}wt.prototype.squaredDifference=function(t){return nu(this,t)},xt=Gh;
//# sourceMappingURL=tf-core.esm.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53), __webpack_require__(87), __webpack_require__(86).Buffer, __webpack_require__(244).setImmediate))
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __assign; });
/* unused harmony export __rest */
/* unused harmony export __decorate */
/* unused harmony export __param */
/* unused harmony export __metadata */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return __generator; });
/* unused harmony export __exportStar */
/* unused harmony export __values */
/* unused harmony export __read */
/* unused harmony export __spread */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return __spreadArrays; });
/* unused harmony export __await */
/* unused harmony export __asyncGenerator */
/* unused harmony export __asyncDelegator */
/* unused harmony export __asyncValues */
/* unused harmony export __makeTemplateObject */
/* unused harmony export __importStar */
/* unused harmony export __importDefault */
/* unused harmony export __classPrivateFieldGet */
/* unused harmony export __classPrivateFieldSet */
/*! *****************************************************************************
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.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-core/dist/tf-core.esm.js
var tf_core_esm = __webpack_require__(0);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs-layers/dist/tf-layers.esm.js
/**
* @license
* Copyright 2020 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 tf_layers_esm_extendStatics=function(e,t){return(tf_layers_esm_extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function tf_layers_esm_extends(e,t){function n(){this.constructor=e}tf_layers_esm_extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var tf_layers_esm_epsilon,tf_layers_esm_assign=function(){return(tf_layers_esm_assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function tf_layers_esm_awaiter(e,t,n,r){return new(n||(n=Promise))(function(i,a){function o(e){try{l(r.next(e))}catch(e){a(e)}}function s(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(o,s)}l((r=r.apply(e,t||[])).next())})}function tf_layers_esm_generator(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}function dist_tf_layers_esm_epsilon(){return null==tf_layers_esm_epsilon&&(tf_layers_esm_epsilon=Object(tf_core_esm["backend"])().epsilon()),tf_layers_esm_epsilon}function tf_layers_esm_imageDataFormat(){return"channelsLast"}var tf_layers_esm_AttributeError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return tf_layers_esm_extends(t,e),t}(Error),tf_layers_esm_RuntimeError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return tf_layers_esm_extends(t,e),t}(Error),tf_layers_esm_ValueError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return tf_layers_esm_extends(t,e),t}(Error),tf_layers_esm_NotImplementedError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return tf_layers_esm_extends(t,e),t}(Error),tf_layers_esm_AssertionError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return tf_layers_esm_extends(t,e),t}(Error),tf_layers_esm_IndexError=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r}return tf_layers_esm_extends(t,e),t}(Error);function tf_layers_esm_pyListRepeat(e,t){if(Array.isArray(e)){for(var n=[],r=0;r<t;r++)n=n.concat(e);return n}return(n=new Array(t)).fill(e),n}function tf_layers_esm_assert(e,t){if(!e)throw new tf_layers_esm_AssertionError(t)}function tf_layers_esm_count(e,t){for(var n=0,r=0,i=e;r<i.length;r++){i[r]===t&&n++}return n}function tf_layers_esm_singletonOrArray(e){return 1===e.length?e[0]:e}function tf_layers_esm_toList(e){return Array.isArray(e)?e:[e]}function tf_layers_esm_toSnakeCase(e){var t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function tf_layers_esm_toCamelCase(e){return e.length<=1?e:-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,function(e,t){return t.toUpperCase()})}var tf_layers_esm_GLOBAL_CUSTOM_OBJECTS={};function tf_layers_esm_serializeKerasObject(e){if(null===e||void 0===e)return null;var t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function tf_layers_esm_convertNDArrayScalarsInConfig(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach(function(e){return tf_layers_esm_convertNDArrayScalarsInConfig(e)});else for(var t=0,n=Object.keys(e);t<n.length;t++){var r=n[t],i=e[r];null!=i&&"object"==typeof i&&(Array.isArray(i)||"ndarray"!==i.type||"number"!=typeof i.value?tf_layers_esm_convertNDArrayScalarsInConfig(i):e[r]=i.value)}}function tf_layers_esm_deserializeKerasObject(e,t,n,r,i){var a,o,s;if(void 0===t&&(t={}),void 0===n&&(n={}),void 0===r&&(r="object"),void 0===i&&(i=!1),"string"==typeof e){var l=e,u=void 0;if(l in n)u=n[l];else if(l in tf_layers_esm_GLOBAL_CUSTOM_OBJECTS)u=tf_layers_esm_GLOBAL_CUSTOM_OBJECTS[l];else if(null==(u=t[l]))throw new tf_layers_esm_ValueError("Unknown "+r+": "+e+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return u}var c=e;if(null==c.className||null==c.config)throw new tf_layers_esm_ValueError(r+": Improper config format: "+JSON.stringify(c)+".\n'className' and 'config' must set.");var p=c.className,h=void 0,d=void 0;if(p in n?(h=(a=n[p])[0],d=a[1]):p in tf_layers_esm_GLOBAL_CUSTOM_OBJECTS?(h=(o=tf_layers_esm_GLOBAL_CUSTOM_OBJECTS.className)[0],d=o[1]):p in t&&(h=(s=t[p])[0],d=s[1]),null==h)throw new tf_layers_esm_ValueError("Unknown "+r+": "+p+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if(null!=d){for(var f={},g=0,m=Object.keys(tf_layers_esm_GLOBAL_CUSTOM_OBJECTS);g<m.length;g++){f[S=m[g]]=tf_layers_esm_GLOBAL_CUSTOM_OBJECTS[S]}for(var y=0,v=Object.keys(n);y<v.length;y++){f[S=v[y]]=n[S]}c.config.customObjects=f;for(var b=tf_layers_esm_assign({},tf_layers_esm_GLOBAL_CUSTOM_OBJECTS),w=0,z=Object.keys(n);w<z.length;w++){var S=z[w];tf_layers_esm_GLOBAL_CUSTOM_OBJECTS[S]=n[S]}tf_layers_esm_convertNDArrayScalarsInConfig(c.config);var A=d(h,c.config,n,i);return tf_layers_esm_GLOBAL_CUSTOM_OBJECTS=tf_layers_esm_assign({},b),A}b=tf_layers_esm_assign({},tf_layers_esm_GLOBAL_CUSTOM_OBJECTS);for(var _=0,I=Object.keys(n);_<I.length;_++){S=I[_];tf_layers_esm_GLOBAL_CUSTOM_OBJECTS[S]=n[S]}A=new h(c.config);return tf_layers_esm_GLOBAL_CUSTOM_OBJECTS=tf_layers_esm_assign({},b),A}function tf_layers_esm_numberCompare(e,t){return e<t?-1:e>t?1:0}function tf_layers_esm_reverseNumberCompare(e,t){return-1*tf_layers_esm_numberCompare(e,t)}function tf_layers_esm_unique(e){if(null==e)return e;for(var t=[],n=0,r=e;n<r.length;n++){var i=r[n];-1===t.indexOf(i)&&t.push(i)}return t}function tf_layers_esm_isObjectEmpty(e){if(null==e)throw new tf_layers_esm_ValueError("Invalid value in obj: "+JSON.stringify(e));for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}function tf_layers_esm_checkStringTypeUnionValue(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new tf_layers_esm_ValueError(n+" is not a valid "+t+". Valid values are "+e+" or null/undefined.")}function tf_layers_esm_checkArrayTypeAndLength(e,t,n,r){return void 0===n&&(n=0),void 0===r&&(r=1/0),tf_layers_esm_assert(n>=0),tf_layers_esm_assert(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(function(e){return typeof e===t})}function tf_layers_esm_assertPositiveInteger(e,t){Array.isArray(e)?(tf_core_esm["util"].assert(e.length>0,function(){return t+" is unexpectedly an empty array."}),e.forEach(function(e,n){return tf_layers_esm_assertPositiveInteger(e,"element "+(n+1)+" of "+t)})):tf_core_esm["util"].assert(Number.isInteger(e)&&e>0,function(){return"Expected "+t+" to be a positive integer, but got "+tf_layers_esm_formatAsFriendlyString(e)+"."})}function tf_layers_esm_formatAsFriendlyString(e){return null===e?"null":Array.isArray(e)?"["+e.map(function(e){return tf_layers_esm_formatAsFriendlyString(e)}).join(",")+"]":"string"==typeof e?'"'+e+'"':""+e}function tf_layers_esm_debounce(e,t){var n,r=tf_core_esm["util"].now();return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var o=tf_core_esm["util"].now();return o-r<t?n:(r=o,n=e.apply(void 0,i))}}function tf_layers_esm_mapActivationToFusedKernel(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}function tf_layers_esm_calcL2Norms(e,t){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["sqrt"])(Object(tf_core_esm["sum"])(Object(tf_core_esm["mulStrict"])(e,e),t,!0))})}var tf_layers_esm_Constraint=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.getConfig=function(){return{}},t}(tf_core_esm["serialization"].Serializable),tf_layers_esm_MaxNorm=function(e){function t(t){var n=e.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){var t=this;return Object(tf_core_esm["tidy"])(function(){var n=tf_layers_esm_calcL2Norms(e,t.axis),r=Object(tf_core_esm["clipByValue"])(n,0,t.maxValue);return Object(tf_core_esm["mul"])(e,Object(tf_core_esm["div"])(r,Object(tf_core_esm["add"])(dist_tf_layers_esm_epsilon(),n)))})},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},t.className="MaxNorm",t}(tf_layers_esm_Constraint);tf_core_esm["serialization"].registerClass(tf_layers_esm_MaxNorm);var tf_layers_esm_UnitNorm=function(e){function t(t){var n=e.call(this)||this;return n.defaultAxis=0,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){var t=this;return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["div"])(e,Object(tf_core_esm["add"])(dist_tf_layers_esm_epsilon(),tf_layers_esm_calcL2Norms(e,t.axis)))})},t.prototype.getConfig=function(){return{axis:this.axis}},t.className="UnitNorm",t}(tf_layers_esm_Constraint);tf_core_esm["serialization"].registerClass(tf_layers_esm_UnitNorm);var tf_layers_esm_NonNeg=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["relu"])(e)},t.className="NonNeg",t}(tf_layers_esm_Constraint);tf_core_esm["serialization"].registerClass(tf_layers_esm_NonNeg);var tf_layers_esm_MinMaxNorm=function(e){function t(t){var n=e.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=t.minValue?t.minValue:n.defaultMinValue,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.rate=null!=t.rate?t.rate:n.defaultRate,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){var t=this;return Object(tf_core_esm["tidy"])(function(){var n=tf_layers_esm_calcL2Norms(e,t.axis),r=Object(tf_core_esm["add"])(Object(tf_core_esm["mul"])(t.rate,Object(tf_core_esm["clipByValue"])(n,t.minValue,t.maxValue)),Object(tf_core_esm["mul"])(1-t.rate,n));return Object(tf_core_esm["mul"])(e,Object(tf_core_esm["div"])(r,Object(tf_core_esm["add"])(dist_tf_layers_esm_epsilon(),n)))})},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},t.className="MinMaxNorm",t}(tf_layers_esm_Constraint);tf_core_esm["serialization"].registerClass(tf_layers_esm_MinMaxNorm);var tf_layers_esm_CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function tf_layers_esm_serializeConstraint(e){return tf_layers_esm_serializeKerasObject(e)}function tf_layers_esm_deserializeConstraint(e,t){return void 0===t&&(t={}),tf_layers_esm_deserializeKerasObject(e,tf_core_esm["serialization"].SerializationMap.getMap().classNameMap,t,"constraint")}function tf_layers_esm_getConstraint(e){return null==e?null:"string"==typeof e?tf_layers_esm_deserializeConstraint({className:e in tf_layers_esm_CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP?tf_layers_esm_CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e,config:{}}):e instanceof tf_layers_esm_Constraint?e:tf_layers_esm_deserializeConstraint(e)}function tf_layers_esm_maxNorm(e){return new tf_layers_esm_MaxNorm(e)}function tf_layers_esm_unitNorm(e){return new tf_layers_esm_UnitNorm(e)}function tf_layers_esm_nonNeg(){return new tf_layers_esm_NonNeg}function tf_layers_esm_minMaxNorm(e){return new tf_layers_esm_MinMaxNorm(e)}var tf_layers_esm_exports_constraints=Object.freeze({maxNorm:tf_layers_esm_maxNorm,unitNorm:tf_layers_esm_unitNorm,nonNeg:tf_layers_esm_nonNeg,minMaxNorm:tf_layers_esm_minMaxNorm}),tf_layers_esm_VALID_DATA_FORMAT_VALUES=["channelsFirst","channelsLast"],tf_layers_esm_VALID_PADDING_MODE_VALUES=["valid","same","causal"],tf_layers_esm_VALID_POOL_MODE_VALUES=["max","avg"],tf_layers_esm_VALID_BIDIRECTIONAL_MERGE_MODES=["sum","mul","concat","ave"],tf_layers_esm_nameMap=new Map;function tf_layers_esm_checkDataFormat(e){tf_layers_esm_checkStringTypeUnionValue(tf_layers_esm_VALID_DATA_FORMAT_VALUES,"DataFormat",e)}function tf_layers_esm_checkPaddingMode(e){tf_layers_esm_checkStringTypeUnionValue(tf_layers_esm_VALID_PADDING_MODE_VALUES,"PaddingMode",e)}function tf_layers_esm_checkPoolMode(e){tf_layers_esm_checkStringTypeUnionValue(tf_layers_esm_VALID_POOL_MODE_VALUES,"PoolMode",e)}var tf_layers_esm_nameScopeStack=[],tf_layers_esm_nameScopeDivider="/";function tf_layers_esm_nameScope(e,t){tf_layers_esm_nameScopeStack.push(e);try{var n=t();return tf_layers_esm_nameScopeStack.pop(),n}catch(e){throw tf_layers_esm_nameScopeStack.pop(),e}}function tf_layers_esm_currentNameScopePrefix(){return 0===tf_layers_esm_nameScopeStack.length?"":tf_layers_esm_nameScopeStack.join(tf_layers_esm_nameScopeDivider)+tf_layers_esm_nameScopeDivider}function tf_layers_esm_getScopedTensorName(e){if(!tf_layers_esm_isValidTensorName(e))throw new Error("Not a valid tensor name: '"+e+"'");return tf_layers_esm_currentNameScopePrefix()+e}function tf_layers_esm_getUniqueTensorName(e){if(!tf_layers_esm_isValidTensorName(e))throw new Error("Not a valid tensor name: '"+e+"'");tf_layers_esm_nameMap.has(e)||tf_layers_esm_nameMap.set(e,0);var t=tf_layers_esm_nameMap.get(e);if(tf_layers_esm_nameMap.set(e,tf_layers_esm_nameMap.get(e)+1),t>0){var n=e+"_"+t;return tf_layers_esm_nameMap.set(n,1),n}return e}var tf_layers_esm_tensorNameRegex=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function tf_layers_esm_isValidTensorName(e){return!!e.match(tf_layers_esm_tensorNameRegex)}function tf_layers_esm_isInteger(e){return e===parseInt(e.toString(),10)}function tf_layers_esm_arrayProd(e,t,n){null==t&&(t=0),null==n&&(n=e.length);for(var r=1,i=t;i<n;++i)r*=e[i];return r}function tf_layers_esm_toArray1D(e){return e=Array.isArray(e)?new Float32Array(e):e,Object(tf_core_esm["tensor1d"])(e)}function tf_layers_esm_min$1(e){return Object(tf_core_esm["min"])(tf_layers_esm_toArray1D(e)).dataSync()[0]}function tf_layers_esm_max$1(e){return Object(tf_core_esm["max"])(tf_layers_esm_toArray1D(e)).dataSync()[0]}function tf_layers_esm_range(e,t){if(t<e)throw new tf_layers_esm_ValueError("end ("+t+") < begin ("+e+") is forbidden.");for(var n=[],r=e;r<t;++r)n.push(r);return n}function tf_layers_esm_cast$1(e,t){return e.asType(t)}function tf_layers_esm_expandDims$1(e,t){void 0===t&&(t=-1);var n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),e.reshape(n)}function tf_layers_esm_repeat(e,t){return Object(tf_core_esm["tidy"])(function(){if(2!==e.shape.length)throw new tf_layers_esm_ValueError("repeat() expects a rank-2 tensor, but received a rank-"+e.shape.length+" tensor.");return tf_layers_esm_tile$1(tf_layers_esm_expandDims$1(e,1),[1,t,1])})}function tf_layers_esm_flatten(e){var t=[tf_layers_esm_arrayProd(e.shape)];return e.reshape(t)}function tf_layers_esm_batchFlatten(e){if(e.rank<=1)throw new tf_layers_esm_ValueError("batchFlatten requires a minimum rank of 2. Got rank: "+e.rank+".");var t=[e.shape[0],tf_layers_esm_arrayProd(e.shape,1)];return e.reshape(t)}function tf_layers_esm_sliceAlongFirstAxis(e,t,n){return Object(tf_core_esm["tidy"])(function(){switch(e.rank){case 1:return Object(tf_core_esm["slice1d"])(e,t,n);case 2:return Object(tf_core_esm["slice2d"])(e,[t,0],[n,e.shape[1]]);case 3:return Object(tf_core_esm["slice3d"])(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Object(tf_core_esm["slice4d"])(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Object(tf_core_esm["slice"])(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Object(tf_core_esm["slice"])(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new tf_layers_esm_ValueError("sliceAlongFirstAxis() received an unsupported tensor rank: "+e.rank)}})}function tf_layers_esm_sliceAlongLastAxis(e,t,n){return Object(tf_core_esm["tidy"])(function(){switch(e.rank){case 1:return Object(tf_core_esm["slice1d"])(e,t,n);case 2:return Object(tf_core_esm["slice2d"])(e,[0,t],[e.shape[0],n]);case 3:return Object(tf_core_esm["slice3d"])(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Object(tf_core_esm["slice4d"])(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new tf_layers_esm_ValueError("sliceAlongLastAxis() received an unsupported tensor rank: "+e.rank)}})}function tf_layers_esm_sliceAlongAxis(e,t,n,r){return Object(tf_core_esm["tidy"])(function(){switch(e.rank){case 1:return Object(tf_core_esm["slice1d"])(e,t,n);case 2:switch(r){case 1:return tf_layers_esm_sliceAlongFirstAxis(e,t,n);case 2:return tf_layers_esm_sliceAlongLastAxis(e,t,n);default:throw new tf_layers_esm_ValueError("The axis is not within the rank of the tensor "+r)}case 3:switch(r){case 1:return tf_layers_esm_sliceAlongFirstAxis(e,t,n);case 2:return Object(tf_core_esm["slice3d"])(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return tf_layers_esm_sliceAlongLastAxis(e,t,n);default:throw new tf_layers_esm_ValueError("The axis is not within the rank of the tensor "+r)}case 4:switch(r){case 1:return tf_layers_esm_sliceAlongFirstAxis(e,t,n);case 2:return Object(tf_core_esm["slice4d"])(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Object(tf_core_esm["slice4d"])(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return tf_layers_esm_sliceAlongLastAxis(e,t,n);default:throw new tf_layers_esm_ValueError("The axis is not within the rank of the tensor "+r)}default:throw new tf_layers_esm_ValueError("sliceAlongLastAxis() received an unsupported tensor rank: "+e.rank)}})}function tf_layers_esm_concatenate(e,t){var n;return void 0===t&&(t=-1),t<0&&(t=0!==(n=e[0].rank)?n:0),t===e[0].rank&&(t=-1),Object(tf_core_esm["concat"])(e,t)}function tf_layers_esm_concatAlongFirstAxis(e,t){switch(e.rank){case 1:return Object(tf_core_esm["concat1d"])([e,t]);case 2:return Object(tf_core_esm["concat2d"])([e,t],0);case 3:return Object(tf_core_esm["concat3d"])([e,t],0);case 4:return Object(tf_core_esm["concat4d"])([e,t],0);default:throw new tf_layers_esm_ValueError("concatAlongFirstAxis() received an unsupported tensor rank: "+e.rank)}}function tf_layers_esm_tile$1(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new tf_layers_esm_ValueError("The length of input n ("+t.length+") does not match the number of dimensions in input x ("+e.rank+")");return Object(tf_core_esm["tile"])(e,t)}function tf_layers_esm_randomNormal$1(e,t,n,r,i){return void 0===t&&(t=0),void 0===n&&(n=1),Object(tf_core_esm["randomNormal"])(e,t,n,r,i)}function tf_layers_esm_dot(e,t,n,r){if(e.rank<2||t.rank<2)throw new tf_layers_esm_NotImplementedError("dot requires both inputs to be rank >= 2 but got x shape = "+e.shape+" and y shape = "+t.shape);if(t.rank>=3&&e.shape.slice(-1)[0]!==(c=t.shape.slice(-2)[0]))throw new tf_layers_esm_NotImplementedError("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+e.shape+" and y shape = "+t.shape);if(2===e.rank&&2===t.rank){var i=!1,a=!1;return tf_core_esm["fused"].matMul({a:e,b:t,transposeA:i,transposeB:a,bias:r?tf_layers_esm_reshapeBias(e.rank,r,tf_layers_esm_imageDataFormat()):null,activation:n})}var o=e.shape.slice(),s=o.pop();e=e.reshape([-1,s]);var l=t.shape.slice(),u=l.pop(),c=l.pop(),p=l.concat([u]),h=Array.from({length:t.rank},function(e,n){return 0===n?t.rank-2:n<=t.rank-2?n-1:n});t=t.transpose(h).reshape([c,-1]);var d=o.concat(p);i=!1,a=!1;return tf_core_esm["fused"].matMul({a:e,b:t,transposeA:i,transposeB:a,bias:r?tf_layers_esm_reshapeBias(e.rank,r,tf_layers_esm_imageDataFormat()):null,activation:n}).reshape(d)}function tf_layers_esm_gather$1(e,t,n){return Object(tf_core_esm["tidy"])(function(){return t=Array.isArray(t)?Object(tf_core_esm["tensor1d"])(t,"int32"):t.toInt(),Object(tf_core_esm["gather"])(e,t,n)})}function tf_layers_esm_square(e){return Object(tf_core_esm["mulStrict"])(e,e)}function tf_layers_esm_reshapeBias(e,t,n){var r=t.shape;if(1!==t.rank&&t.rank!==e)throw new tf_layers_esm_ValueError("Unexpected bias dimensions: "+t.rank+"; expected it to be 1 or "+e);if(5===e){if("channelsFirst"===n)return 1===r.length?t.reshape([1,r[0],1,1,1]):t.reshape([1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?t.reshape([1,1,1,1,r[0]]):t.reshape([1].concat(r))}else if(4===e){if("channelsFirst"===n)return 1===r.length?t.reshape([1,r[0],1,1]):t.reshape([1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?t.reshape([1,1,1,r[0]]):t.reshape([1].concat(r))}else if(3===e){if("channelsFirst"===n)return 1===r.length?t.reshape([1,r[0],1]):t.reshape([1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?t.reshape([1,1,r[0]]):t.reshape([1].concat(r))}else if(e<3)return t;throw new tf_layers_esm_ValueError("Unsupported input rank by biasAdd: "+t.rank)}function tf_layers_esm_biasAdd(e,t,n){return Object(tf_core_esm["tidy"])(function(){return null==n&&(n=tf_layers_esm_imageDataFormat()),tf_layers_esm_checkDataFormat(n),e.add(tf_layers_esm_reshapeBias(e.rank,t,n))})}function tf_layers_esm_elu$1(e,t){if(void 0===t&&(t=1),1!==t)throw new tf_layers_esm_NotImplementedError("Support for alpha values other than 1 ("+t+") is not implemented yet.");return Object(tf_core_esm["elu"])(e)}function tf_layers_esm_softsign(e){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["div"])(e,Object(tf_core_esm["abs"])(e).add(1))})}function tf_layers_esm_dropout$1(e,t,n,r){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["dropout"])(e,t,n,r)})}function tf_layers_esm_hardSigmoid(e){return Object(tf_core_esm["tidy"])(function(){var t=Object(tf_core_esm["add"])(.5,Object(tf_core_esm["mul"])(.2,e));return Object(tf_core_esm["clipByValue"])(t,0,1)})}function tf_layers_esm_inTrainPhase(e,t,n){return void 0===n&&(n=!1),n?e():t()}var tf_layers_esm_VALID_FAN_MODE_VALUES=["fanIn","fanOut","fanAvg"],tf_layers_esm_VALID_DISTRIBUTION_VALUES=["normal","uniform","truncatedNormal"];function tf_layers_esm_checkFanMode(e){tf_layers_esm_checkStringTypeUnionValue(tf_layers_esm_VALID_FAN_MODE_VALUES,"FanMode",e)}function tf_layers_esm_checkDistribution(e){tf_layers_esm_checkStringTypeUnionValue(tf_layers_esm_VALID_DISTRIBUTION_VALUES,"Distribution",e)}var tf_layers_esm_Initializer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(tf_core_esm["serialization"].Serializable),tf_layers_esm_Zeros=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){return Object(tf_core_esm["zeros"])(e,t)},t.className="Zeros",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Zeros);var tf_layers_esm_Ones=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){return Object(tf_core_esm["ones"])(e,t)},t.className="Ones",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Ones);var tf_layers_esm_Constant=function(e){function t(t){var n=e.call(this)||this;if("object"!=typeof t)throw new tf_layers_esm_ValueError("Expected argument of type ConstantConfig but got "+t);if(void 0===t.value)throw new tf_layers_esm_ValueError("config must have value set but got "+t);return n.value=t.value,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["mul"])(Object(tf_core_esm["scalar"])(n.value),Object(tf_core_esm["ones"])(e,t))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Constant);var tf_layers_esm_RandomUniform=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=t.minval||n.DEFAULT_MINVAL,n.maxval=t.maxval||n.DEFAULT_MAXVAL,n.seed=t.seed,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){return Object(tf_core_esm["randomUniform"])(e,this.minval,this.maxval,t)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_RandomUniform);var tf_layers_esm_RandomNormal=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new tf_layers_esm_NotImplementedError("randomNormal does not support dType "+t+".");return tf_layers_esm_randomNormal$1(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_RandomNormal);var tf_layers_esm_TruncatedNormal=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new tf_layers_esm_NotImplementedError("truncatedNormal does not support dType "+t+".");return Object(tf_core_esm["truncatedNormal"])(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_TruncatedNormal);var tf_layers_esm_Identity=function(e){function t(t){var n=e.call(this)||this;return n.gain=null!=t.gain?t.gain:1,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){if(2!==e.length||e[0]!==e[1])throw new tf_layers_esm_ValueError("Identity matrix initializer can only be used for 2D square matrices.");return Object(tf_core_esm["mul"])(n.gain,Object(tf_core_esm["eye"])(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain}},t.className="Identity",t}(tf_layers_esm_Initializer);function tf_layers_esm_computeFans(e,t){var n,r;if(void 0===t&&(t="channelsLast"),tf_layers_esm_checkDataFormat(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){var i=tf_layers_esm_arrayProd(e,2);n=e[1]*i,r=e[0]*i}else if("channelsLast"===t){i=tf_layers_esm_arrayProd(e,0,e.length-2);n=e[e.length-2]*i,r=e[e.length-1]*i}}else{var a=tf_layers_esm_arrayProd(e);n=Math.sqrt(a),r=Math.sqrt(a)}return[n,r]}tf_core_esm["serialization"].registerClass(tf_layers_esm_Identity);var tf_layers_esm_VarianceScaling=function(e){function t(t){var n=e.call(this)||this;if(t.scale<0)throw new tf_layers_esm_ValueError("scale must be a positive float. Got: "+t.scale);return n.scale=null==t.scale?1:t.scale,n.mode=null==t.mode?"fanIn":t.mode,tf_layers_esm_checkFanMode(n.mode),n.distribution=null==t.distribution?"normal":t.distribution,tf_layers_esm_checkDistribution(n.distribution),n.seed=t.seed,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){var n=tf_layers_esm_computeFans(e),r=n[0],i=n[1],a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,r):"fanOut"===this.mode?a/=Math.max(1,i):a/=Math.max(1,(r+i)/2),"normal"===this.distribution){var o=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new tf_layers_esm_NotImplementedError(this.getClassName()+" does not support dType "+t+".");return Object(tf_core_esm["truncatedNormal"])(e,0,o,t,this.seed)}var s=Math.sqrt(3*a);return Object(tf_core_esm["randomUniform"])(e,-s,s,t)},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_VarianceScaling);var tf_layers_esm_GlorotUniform=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this}return tf_layers_esm_extends(t,e),t.prototype.getClassName=function(){return tf_layers_esm_VarianceScaling.className},t.className="GlorotUniform",t}(tf_layers_esm_VarianceScaling);tf_core_esm["serialization"].registerClass(tf_layers_esm_GlorotUniform);var tf_layers_esm_GlorotNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this}return tf_layers_esm_extends(t,e),t.prototype.getClassName=function(){return tf_layers_esm_VarianceScaling.className},t.className="GlorotNormal",t}(tf_layers_esm_VarianceScaling);tf_core_esm["serialization"].registerClass(tf_layers_esm_GlorotNormal);var tf_layers_esm_HeNormal=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return tf_layers_esm_extends(t,e),t.prototype.getClassName=function(){return tf_layers_esm_VarianceScaling.className},t.className="HeNormal",t}(tf_layers_esm_VarianceScaling);tf_core_esm["serialization"].registerClass(tf_layers_esm_HeNormal);var tf_layers_esm_HeUniform=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==t?null:t.seed})||this}return tf_layers_esm_extends(t,e),t.prototype.getClassName=function(){return tf_layers_esm_VarianceScaling.className},t.className="HeUniform",t}(tf_layers_esm_VarianceScaling);tf_core_esm["serialization"].registerClass(tf_layers_esm_HeUniform);var tf_layers_esm_LeCunNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return tf_layers_esm_extends(t,e),t.prototype.getClassName=function(){return tf_layers_esm_VarianceScaling.className},t.className="LeCunNormal",t}(tf_layers_esm_VarianceScaling);tf_core_esm["serialization"].registerClass(tf_layers_esm_LeCunNormal);var tf_layers_esm_LeCunUniform=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==t?null:t.seed})||this}return tf_layers_esm_extends(t,e),t.prototype.getClassName=function(){return tf_layers_esm_VarianceScaling.className},t.className="LeCunNormal",t}(tf_layers_esm_VarianceScaling);tf_core_esm["serialization"].registerClass(tf_layers_esm_LeCunUniform);var tf_layers_esm_Orthogonal=function(e){function t(t){var n=e.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==t.gain?n.DEFAULT_GAIN:t.gain,n.seed=t.seed,null!=n.seed)throw new tf_layers_esm_NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.");return n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){if(2!==e.length)throw new tf_layers_esm_NotImplementedError("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=tf_layers_esm_randomNormal$1(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),r=tf_core_esm["linalg"].gramSchmidt(t);return e[0]>e[1]&&(r=r.transpose()),Object(tf_core_esm["mul"])(n.gain,r)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(tf_layers_esm_Initializer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Orthogonal);var tf_layers_esm_INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={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 tf_layers_esm_deserializeInitializer(e,t){return void 0===t&&(t={}),tf_layers_esm_deserializeKerasObject(e,tf_core_esm["serialization"].SerializationMap.getMap().classNameMap,t,"initializer")}function tf_layers_esm_serializeInitializer(e){return tf_layers_esm_serializeKerasObject(e)}function tf_layers_esm_getInitializer(e){if("string"==typeof e){var t=e in tf_layers_esm_INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?tf_layers_esm_INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e;if("GlorotNormal"===t)return new tf_layers_esm_GlorotNormal;if("GlorotUniform"===t)return new tf_layers_esm_GlorotUniform;if("HeNormal"===t)return new tf_layers_esm_HeNormal;if("HeUniform"===t)return new tf_layers_esm_HeUniform;if("LeCunNormal"===t)return new tf_layers_esm_LeCunNormal;if("LeCunUniform"===t)return new tf_layers_esm_LeCunUniform;var n={};return n.className=t,n.config={},tf_layers_esm_deserializeInitializer(n)}return e instanceof tf_layers_esm_Initializer?e:tf_layers_esm_deserializeInitializer(e)}function tf_layers_esm_zeros$1(){return new tf_layers_esm_Zeros}function tf_layers_esm_ones$1(){return new tf_layers_esm_Ones}function tf_layers_esm_constant(e){return new tf_layers_esm_Constant(e)}function tf_layers_esm_randomUniform$1(e){return new tf_layers_esm_RandomUniform(e)}function tf_layers_esm_randomNormal$2(e){return new tf_layers_esm_RandomNormal(e)}function tf_layers_esm_truncatedNormal$1(e){return new tf_layers_esm_TruncatedNormal(e)}function tf_layers_esm_identity(e){return new tf_layers_esm_Identity(e)}function tf_layers_esm_varianceScaling(e){return new tf_layers_esm_VarianceScaling(e)}function tf_layers_esm_glorotUniform(e){return new tf_layers_esm_GlorotUniform(e)}function tf_layers_esm_glorotNormal(e){return new tf_layers_esm_GlorotNormal(e)}function tf_layers_esm_heNormal(e){return new tf_layers_esm_HeNormal(e)}function tf_layers_esm_heUniform(e){return new tf_layers_esm_HeUniform(e)}function tf_layers_esm_leCunNormal(e){return new tf_layers_esm_LeCunNormal(e)}function tf_layers_esm_leCunUniform(e){return new tf_layers_esm_LeCunUniform(e)}function tf_layers_esm_orthogonal(e){return new tf_layers_esm_Orthogonal(e)}var tf_layers_esm_exports_initializers=Object.freeze({zeros:tf_layers_esm_zeros$1,ones:tf_layers_esm_ones$1,constant:tf_layers_esm_constant,randomUniform:tf_layers_esm_randomUniform$1,randomNormal:tf_layers_esm_randomNormal$2,truncatedNormal:tf_layers_esm_truncatedNormal$1,identity:tf_layers_esm_identity,varianceScaling:tf_layers_esm_varianceScaling,glorotUniform:tf_layers_esm_glorotUniform,glorotNormal:tf_layers_esm_glorotNormal,heNormal:tf_layers_esm_heNormal,heUniform:tf_layers_esm_heUniform,leCunNormal:tf_layers_esm_leCunNormal,leCunUniform:tf_layers_esm_leCunUniform,orthogonal:tf_layers_esm_orthogonal}),tf_layers_esm_nextUniqueTensorId=0;function tf_layers_esm_getNextUniqueTensorId(){return tf_layers_esm_nextUniqueTensorId++}var tf_layers_esm_uidPrefixes={};function tf_layers_esm_getUid(e){return void 0===e&&(e=""),e in tf_layers_esm_uidPrefixes||(tf_layers_esm_uidPrefixes[e]=0),tf_layers_esm_uidPrefixes[e]+=1,e+tf_layers_esm_uidPrefixes[e].toString()}function tf_layers_esm_isArrayOfShapes(e){return Array.isArray(e)&&Array.isArray(e[0])}function tf_layers_esm_normalizeShapeList(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function tf_layers_esm_getExactlyOneTensor(e){var t;if(Array.isArray(e)){if(1!==e.length)throw new tf_layers_esm_ValueError("Expected Tensor length to be 1; got "+e.length);t=e[0]}else t=e;return t}function tf_layers_esm_getExactlyOneShape(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new tf_layers_esm_ValueError("Expected exactly 1 Shape; got "+e.length)}return e}function tf_layers_esm_countParamsInWeights(e){for(var t=0,n=0,r=e;n<r.length;n++){var i=r[n];0===i.shape.length?t+=1:t+=i.shape.reduce(function(e,t){return e*t})}return t}var tf_layers_esm_DEFAULT_VARIABLE_NAME_PREFIX="Variable",tf_layers_esm_LayerVariable=function(){function e(e,t,n,r,i){void 0===t&&(t="float32"),void 0===n&&(n=tf_layers_esm_DEFAULT_VARIABLE_NAME_PREFIX),void 0===r&&(r=!0),void 0===i&&(i=null),this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=tf_layers_esm_getNextUniqueTensorId(),n=null==n?tf_layers_esm_DEFAULT_VARIABLE_NAME_PREFIX:n,this.originalName=tf_layers_esm_getScopedTensorName(n),this.name=tf_layers_esm_getUniqueTensorName(this.originalName),this.trainable_=r,this.constraint=i,this.val=Object(tf_core_esm["variable"])(e,this.trainable_,this.name,this.dtype)}return e.prototype.read=function(){return this.assertNotDisposed(),this.val},e.prototype.write=function(e){return this.assertNotDisposed(),tf_layers_esm_checkShapesMatch(this.val,e),this.val.id!==e.id&&(this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this},e.prototype.dispose=function(){this.assertNotDisposed(),this.val.dispose()},e.prototype.assertNotDisposed=function(){if(this.val.isDisposed)throw new Error("LayersVariable "+this.name+" is already disposed.")},Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this.trainable_=e,this.val.trainable=e},enumerable:!0,configurable:!0}),e}();function tf_layers_esm_checkShapesMatch(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function tf_layers_esm_batchGetValue(e){return e.map(function(e){return e.read()})}function tf_layers_esm_batchSetValue(e){e.forEach(function(e){e[0].write(e[1])})}var tf_layers_esm_InputSpec=function(){return function(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}(),tf_layers_esm_SymbolicTensor=function(){return function(e,t,n,r,i,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=i,this.outputTensorIndex=o,this.id=tf_layers_esm_getNextUniqueTensorId(),null!=a&&(this.originalName=tf_layers_esm_getScopedTensorName(a),this.name=tf_layers_esm_getUniqueTensorName(this.originalName)),this.rank=t.length}}(),tf_layers_esm_nextNodeID=0,tf_layers_esm_Node=function(){function e(e,t){this.callArgs=t,this.id=tf_layers_esm_nextNodeID++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(var n=0,r=e.inboundLayers;n<r.length;n++){var i=r[n];null!=i&&i.outboundNodes.push(this)}e.outboundLayer.inboundNodes.push(this)}return e.prototype.getConfig=function(){for(var e=[],t=0,n=this.inboundLayers;t<n.length;t++){var r=n[t];null!=r?e.push(r.name):e.push(null)}return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}},e}(),tf_layers_esm_nextLayerID=0,tf_layers_esm_Layer=function(e){function t(t){var n=e.call(this)||this;n._callHook=null,n._addedWeightNames=[],n._stateful=!1,n.id=tf_layers_esm_nextLayerID++,n.activityRegularizer=null,n.inputSpec=null,n.supportsMasking=!1,n._trainableWeights=[],n._nonTrainableWeights=[],n._losses=[],n._updates=[],n._built=!1,n.inboundNodes=[],n.outboundNodes=[];var r=t.name;if(!r){var i=n.getClassName();r=tf_layers_esm_toSnakeCase(i)+"_"+tf_layers_esm_getUid(i)}if(n.name=r,n.trainable_=null==t.trainable||t.trainable,null!=t.inputShape||null!=t.batchInputShape){var a=void 0;if(null!=t.batchInputShape)a=t.batchInputShape;else if(null!=t.inputShape){var o=null;null!=t.batchSize&&(o=t.batchSize),a=[o].concat(t.inputShape)}n.batchInputShape=a;var s=t.dtype;null==s&&(s=t.inputDType),null==s&&(s="float32"),n.dtype=s}return null!=t.weights?n.initialWeights=t.weights:n.initialWeights=null,n._refCount=null,n.fastWeightInitDuringBuild=!1,n}return tf_layers_esm_extends(t,e),t.nodeKey=function(e,t){return e.name+"_ib-"+t.toString()},t.prototype.getNodeAtIndex=function(e,t){if(0===this.inboundNodes.length)throw new tf_layers_esm_RuntimeError("The layer has never been called and thus has no defined "+t+".");if(this.inboundNodes.length<=e)throw new tf_layers_esm_ValueError("Asked to get "+t+" at node "+e+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[e]},t.prototype.getInputAt=function(e){return tf_layers_esm_singletonOrArray(this.getNodeAtIndex(e,"input").inputTensors)},t.prototype.getOutputAt=function(e){return tf_layers_esm_singletonOrArray(this.getNodeAtIndex(e,"output").outputTensors)},Object.defineProperty(t.prototype,"input",{get:function(){if(this.inboundNodes.length>1)throw new tf_layers_esm_AttributeError("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 tf_layers_esm_AttributeError("Layer "+this.name+" is not connected, no input to return.");return tf_layers_esm_singletonOrArray(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new tf_layers_esm_AttributeError("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new tf_layers_esm_AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return tf_layers_esm_singletonOrArray(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this._trainableWeights.forEach(function(t){return t.trainable=e}),this.trainable_=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(e){return e.trainable}):[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(e){return!e.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=tf_layers_esm_toList(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=tf_layers_esm_toList(this.inputSpec);if(e.length!==t.length)throw new tf_layers_esm_ValueError("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var n=0;n<e.length;n++){var r=e[n],i=t[n];if(null!=i){var a=r.rank;if(null!=i.ndim&&a!==i.ndim)throw new tf_layers_esm_ValueError("Input "+n+" is incompatible with layer "+this.name+": expected ndim="+i.ndim+", found ndim="+a);if(null!=i.maxNDim&&a>i.maxNDim)throw new tf_layers_esm_ValueError("Input "+n+" is incompatible with layer "+this.name+": expected max_ndim="+i.maxNDim+", found ndim="+a);if(null!=i.minNDim&&a<i.minNDim)throw new tf_layers_esm_ValueError("Input "+n+" is incompatible with layer "+this.name+": expected min_ndim="+i.minNDim+", found ndim="+a+".");if(null!=i.dtype&&r.dtype!==i.dtype)throw new tf_layers_esm_ValueError("Input "+n+" is incompatible with layer "+this.name+" : expected dtype="+i.dtype+", found dtype="+r.dtype+".");if(i.axes){var o=r.shape;for(var s in i.axes){var l=Number(s),u=i.axes[s],c=l>=0?o[l]:o[o.length+l];if(null!=u&&-1===[u,null].indexOf(c))throw new tf_layers_esm_ValueError("Input "+n+" is incompatible with layer "+this.name+": expected axis "+l+" of input shape to have value "+u+" but got shape "+o+".")}}if(null!=i.shape)for(var p=0;p<i.shape.length;++p){var h=i.shape[p],d=r.shape[p];if(null!=h&&null!=d&&h!==d)throw new tf_layers_esm_ValueError("Input "+n+" is incompatible with layer "+this.name+": expected shape="+i.shape+", found shape="+r.shape+".")}}}}},t.prototype.call=function(e,t){return e},t.prototype.invokeCallHook=function(e,t){null!=this._callHook&&this._callHook(e,t)},t.prototype.setCallHook=function(e){this._callHook=e},t.prototype.clearCallHook=function(){this._callHook=null},t.prototype.apply=function(e,t){var n=this;t=t||{},this.assertNotDisposed();for(var r=tf_layers_esm_toList(e),i=!0,a=0,o=r;a<o.length;a++){if(!(o[a]instanceof tf_layers_esm_SymbolicTensor)){i=!1;break}}for(var s=!0,l=0,u=r;l<u.length;l++){if(u[l]instanceof tf_layers_esm_SymbolicTensor){s=!1;break}}if(i===s)throw new tf_layers_esm_ValueError("Arguments to apply() must be all SymbolicTensors or all Tensors");return tf_layers_esm_nameScope(this.name,function(){if(!n.built){n.assertInputCompatibility(e);for(var i=[],a=0,o=tf_layers_esm_toList(e);a<o.length;a++){var l=o[a];i.push(l.shape)}n.build(tf_layers_esm_singletonOrArray(i)),n.built=!0,n.initialWeights&&n.setWeights(n.initialWeights),null===n._refCount&&s&&(n._refCount=1)}if(n.assertInputCompatibility(e),s){for(var u=[],c=0,p=tf_layers_esm_toList(g=n.call(e,t));c<p.length;c++){var h=p[c];-1!==r.indexOf(h)&&(h=h.clone()),u.push(h)}if(g=tf_layers_esm_singletonOrArray(u),null!=n.activityRegularizer)throw new tf_layers_esm_NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return g}var d=tf_layers_esm_collectInputShape(e),f=n.computeOutputShape(d),g=void 0,m=tf_layers_esm_guessOutputDType(e);if(n.warnOnIncompatibleInputShape(Array.isArray(e)?d[0]:d),g=null!=f&&f.length>0&&Array.isArray(f[0])?f.map(function(r,i){return new tf_layers_esm_SymbolicTensor(m,r,n,tf_layers_esm_toList(e),t,n.name,i)}):new tf_layers_esm_SymbolicTensor(m,f,n,tf_layers_esm_toList(e),t,n.name),n.addInboundNode(e,g,null,null,d,f,t),n._refCount++,null!=n.activityRegularizer)throw new tf_layers_esm_NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return g})},t.prototype.warnOnIncompatibleInputShape=function(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(e)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var t=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=e[r]&&e[r]!==n&&(t=!0)}),t&&console.warn("The shape of the input tensor ("+JSON.stringify(e)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new tf_layers_esm_AttributeError("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],t=0,n=this.inboundNodes;t<n.length;t++){var r=n[t],i=JSON.stringify(r.outputShapes);-1===e.indexOf(i)&&e.push(i)}if(1===e.length){var a=this.inboundNodes[0].outputShapes;return Array.isArray(a)&&Array.isArray(a[0])&&1===a.length?a[0]:a}throw new tf_layers_esm_AttributeError("The layer "+this.name+' has multiple inbound nodes with different output shapes. Hence the notion of "outut shape" is ill-defined for the layer.')},enumerable:!0,configurable:!0}),t.prototype.countParams=function(){if(!this.built)throw new tf_layers_esm_RuntimeError("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).");return tf_layers_esm_countParamsInWeights(this.weights)},t.prototype.build=function(e){this.built=!0},t.prototype.getWeights=function(e){return void 0===e&&(e=!1),tf_layers_esm_batchGetValue(e?this.trainableWeights:this.weights)},t.prototype.setWeights=function(e){var t=this;Object(tf_core_esm["tidy"])(function(){var n=t.weights;if(n.length!==e.length)throw new tf_layers_esm_ValueError('You called setWeights(weights) on layer "'+t.name+'" with a weight list of length '+e.length+", but the layer was expecting "+n.length+" weights. Provided weights: "+e+"...");if(0!==n.length){for(var r=[],i=tf_layers_esm_batchGetValue(n),a=0;a<i.length;++a){var o=i[a],s=n[a],l=e[a];if(!tf_core_esm["util"].arraysEqual(o.shape,l.shape))throw new tf_layers_esm_ValueError("Layer weight shape "+o.shape+" not compatible with provided weight shape "+l.shape);r.push([s,l])}tf_layers_esm_batchSetValue(r)}})},t.prototype.addWeight=function(e,t,n,r,i,a,o){if(-1!==this._addedWeightNames.indexOf(e))throw new tf_layers_esm_ValueError("Duplicate weight name "+e+" for layer "+this.name);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=tf_layers_esm_getInitializer("zeros"));var s=r.apply(t,n),l=new tf_layers_esm_LayerVariable(s,n,e,a,o);return s.dispose(),null!=i&&this.addLoss(function(){return i.apply(l.read())}),null==a&&(a=!0),a?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l},t.prototype.setFastWeightInitDuringBuild=function(e){this.fastWeightInitDuringBuild=e},t.prototype.addLoss=function(e){var t;null==e||Array.isArray(e)&&0===e.length||(e=tf_layers_esm_toList(e),void 0!==this._losses&&null!==this._losses&&(t=this.losses).push.apply(t,e))},t.prototype.computeOutputShape=function(e){return e},t.prototype.computeMask=function(e,t){var n=this;if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError("Layer "+this.name+" does not support masking, but was passed an inputMask.");t.forEach(function(e){if(null!=e)throw new TypeError("Layer "+n.name+" does not support masking, but was passed an inputMask.")})}return null}return t},t.prototype.addInboundNode=function(e,t,n,r,i,a,o){void 0===o&&(o=null);var s=tf_layers_esm_toList(e);t=tf_layers_esm_toList(t),n=tf_layers_esm_toList(n),r=tf_layers_esm_toList(r),i=tf_layers_esm_normalizeShapeList(i),a=tf_layers_esm_normalizeShapeList(a);for(var l=[],u=[],c=[],p=0,h=s;p<h.length;p++){var d=h[p];l.push(d.sourceLayer),u.push(d.nodeIndex),c.push(d.tensorIndex)}new tf_layers_esm_Node({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:s,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:i,outputShapes:a},o);for(var f=0;f<t.length;f++)t[f].sourceLayer=this,t[f].nodeIndex=this.inboundNodes.length-1,t[f].tensorIndex=f},t.prototype.getConfig=function(){var e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e},t.prototype.disposeWeights=function(){return this.weights.forEach(function(e){return e.dispose()}),this.weights.length},t.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Layer '"+this.name+"' is already disposed.")},t.prototype.dispose=function(){if(!this.built)throw new Error("Cannot dispose Layer "+this.name+" because it has not been built yet.");if(null===this._refCount)throw new Error("Cannot dispose Layer "+this.name+" because it has not been used yet.");this.assertNotDisposed();var e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}},t}(tf_core_esm["serialization"].Serializable);function tf_layers_esm_collectInputShape(e){for(var t=[],n=0,r=e=tf_layers_esm_toList(e);n<r.length;n++){var i=r[n];t.push(i.shape)}return tf_layers_esm_singletonOrArray(t)}function tf_layers_esm_guessOutputDType(e){return"float32"}function tf_layers_esm_getSourceInputs(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];var r=t.inboundNodes[n];if(0===r.inboundLayers.length)return r.inputTensors;for(var i=[],a=0;a<r.inboundLayers.length;a++)for(var o=0,s=tf_layers_esm_getSourceInputs(r.inputTensors[a],r.inboundLayers[a],r.nodeIndices[a]);o<s.length;o++){var l=s[o];-1===i.indexOf(l)&&i.push(l)}return i}var tf_layers_esm_ModelLoggingVerbosity,tf_layers_esm_InputLayer=function(e){function t(t){var n=e.call(this,{dtype:t.dtype,name:null!=t.name?t.name:tf_layers_esm_getUid("input").toString()})||this;if(null==t.batchSize&&(t.batchSize=null),null==t.sparse&&(t.sparse=!1),n.trainable=!1,n.built=!0,n.sparse=t.sparse,null!=t.inputShape&&null!=t.batchInputShape)throw new tf_layers_esm_ValueError("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var r=t.batchInputShape;if(null==r){if(null==t.inputShape)throw new tf_layers_esm_ValueError("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r=[t.batchSize].concat(t.inputShape)}else if(null!=t.batchSize)throw new tf_layers_esm_ValueError("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");var i=t.dtype||"float32";n.batchInputShape=r,n.dtype=i,n.inputSpec=[{shape:r}];var a=new tf_layers_esm_SymbolicTensor(n.dtype,n.batchInputShape,n,[],{},n.name);return a.nodeIndex=0,a.tensorIndex=0,new tf_layers_esm_Node({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[r],outputShapes:[r]}),n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){throw new tf_layers_esm_ValueError("Cannot pass any input to an InputLayer's apply() method. InputLayer name: "+this.name)},t.prototype.dispose=function(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}},t.prototype.getConfig=function(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}},t.className="InputLayer",t}(tf_layers_esm_Layer);function tf_layers_esm_Input(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new tf_layers_esm_ValueError("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));var n=e.dtype;return null==n&&(n="float32"),new tf_layers_esm_InputLayer({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function tf_layers_esm_resolveScalarsInLogs(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var t,n,r,i,a,o,s,l;return tf_layers_esm_generator(this,function(u){switch(u.label){case 0:if(null==e)return[2];for(i in t=[],n=[],r=[],e)"number"!=typeof(a=e[i])&&(o=a,t.push(o.data()),n.push(i),r.push(o));return t.length>0?[4,Promise.all(t)]:[3,2];case 1:for(s=u.sent(),l=0;l<s.length;++l)e[n[l]]=s[l][0];Object(tf_core_esm["dispose"])(r),u.label=2;case 2:return[2]}})})}function tf_layers_esm_disposeTensorsInLogs(e){if(null!=e)for(var t in e){var n=e[t];"number"!=typeof n&&n.dispose()}}tf_core_esm["serialization"].registerClass(tf_layers_esm_InputLayer),function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(tf_layers_esm_ModelLoggingVerbosity||(tf_layers_esm_ModelLoggingVerbosity={}));var tf_layers_esm_DEFAULT_YIELD_EVERY_MS=125,tf_layers_esm_BaseCallback=function(){function e(){this.validationData=null}return e.prototype.setParams=function(e){this.params=e},e.prototype.onEpochBegin=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return[2]})})},e.prototype.onEpochEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return[2]})})},e.prototype.onBatchBegin=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return[2]})})},e.prototype.onBatchEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return[2]})})},e.prototype.onTrainBegin=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return[2]})})},e.prototype.onTrainEnd=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return[2]})})},e.prototype.setModel=function(e){},e}(),tf_layers_esm_CallbackList=function(){function e(e,t){void 0===t&&(t=10),null==e&&(e=[]),this.callbacks=e,this.queueLength=t}return e.prototype.append=function(e){this.callbacks.push(e)},e.prototype.setParams=function(e){for(var t=0,n=this.callbacks;t<n.length;t++){n[t].setParams(e)}},e.prototype.setModel=function(e){for(var t=0,n=this.callbacks;t<n.length;t++){n[t].setModel(e)}},e.prototype.onEpochBegin=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r;return tf_layers_esm_generator(this,function(i){switch(i.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onEpochBegin(e,t)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},e.prototype.onEpochEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r;return tf_layers_esm_generator(this,function(i){switch(i.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onEpochEnd(e,t)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},e.prototype.onBatchBegin=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r;return tf_layers_esm_generator(this,function(i){switch(i.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onBatchBegin(e,t)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},e.prototype.onBatchEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r;return tf_layers_esm_generator(this,function(i){switch(i.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onBatchEnd(e,t)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},e.prototype.onTrainBegin=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var t,n;return tf_layers_esm_generator(this,function(r){switch(r.label){case 0:null==e&&(e={}),t=0,n=this.callbacks,r.label=1;case 1:return t<n.length?[4,n[t].onTrainBegin(e)]:[3,4];case 2:r.sent(),r.label=3;case 3:return t++,[3,1];case 4:return[2]}})})},e.prototype.onTrainEnd=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var t,n;return tf_layers_esm_generator(this,function(r){switch(r.label){case 0:null==e&&(e={}),t=0,n=this.callbacks,r.label=1;case 1:return t<n.length?[4,n[t].onTrainEnd(e)]:[3,4];case 2:r.sent(),r.label=3;case 3:return t++,[3,1];case 4:return[2]}})})},e}(),tf_layers_esm_BaseLogger=function(e){function t(){return e.call(this)||this}return tf_layers_esm_extends(t,e),t.prototype.onEpochBegin=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return this.seen=0,this.totals={},[2]})})},t.prototype.onBatchEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var e,n,r,i,a=this;return tf_layers_esm_generator(this,function(o){for(i in null==t&&(t={}),e=null==t.size?0:t.size,this.seen+=e,n=function(n){var i=t[n];if("number"==typeof i)r.totals.hasOwnProperty(n)||(r.totals[n]=0),r.totals[n]=r.totals[n]+i*e;else{var o=void 0;n in r.totals?o=r.totals[n]:r.totals[n]=0;var s=Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["add"])(a.totals[n],Object(tf_core_esm["mul"])(i,e))});r.totals[n]=s,null!=o&&o.dispose()}},r=this,t)n(i);return[2]})})},t.prototype.onEpochEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var e,n,r,i,a,o=this;return tf_layers_esm_generator(this,function(s){if(null!=t)for(e=function(e){if(null==n.totals[e])return"continue";"number"==typeof n.totals[e]?t[e]=n.totals[e]/n.seen:Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["mul"])(Object(tf_core_esm["div"])(1,o.seen),o.totals[e]);t[e]=n,o.totals[e].dispose(),Object(tf_core_esm["keep"])(t[e])})},n=this,r=0,i=this.params.metrics;r<i.length;r++)a=i[r],e(a);return[2]})})},t}(tf_layers_esm_BaseCallback),tf_layers_esm_History=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.onTrainBegin=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return this.epoch=[],this.history={},[2]})})},t.prototype.onEpochEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n;return tf_layers_esm_generator(this,function(r){for(n in null==t&&(t={}),this.epoch.push(e),t)null==this.history[n]&&(this.history[n]=[]),this.history[n].push(t[n]);return[2]})})},t.prototype.syncData=function(){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var e,t,n,r,i,a,o,s,l;return tf_layers_esm_generator(this,function(u){switch(u.label){case 0:for(r in e=[],t=[],n=[],this.history)for(i=this.history[r],a=0;a<i.length;++a)"number"!=typeof i[a]&&(o=i[a],e.push(o.data()),t.push(r),n.push(a));return[4,Promise.all(e)];case 1:for(s=u.sent(),l=0;l<s.length;++l)this.history[t[l]][n[l]].dispose(),this.history[t[l]][n[l]]=s[l][0];return[2]}})})},t}(tf_layers_esm_BaseCallback),tf_layers_esm_CustomCallback=function(e){function t(t,n){var r=e.call(this)||this;if(r.currentEpoch=0,r.yieldEvery=n||"auto","auto"===r.yieldEvery&&(r.yieldEvery=tf_layers_esm_DEFAULT_YIELD_EVERY_MS),"never"===r.yieldEvery&&null!=t.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");return tf_core_esm["util"].isNumber(r.yieldEvery)&&(r.maybeWait=tf_layers_esm_debounce(r.maybeWait.bind(r),r.yieldEvery)),r.trainBegin=t.onTrainBegin,r.trainEnd=t.onTrainEnd,r.epochBegin=t.onEpochBegin,r.epochEnd=t.onEpochEnd,r.batchBegin=t.onBatchBegin,r.batchEnd=t.onBatchEnd,r.yield=t.onYield,r}return tf_layers_esm_extends(t,e),t.prototype.maybeWait=function(e,t,n){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var r;return tf_layers_esm_generator(this,function(i){switch(i.label){case 0:return r=[],null==this.yield?[3,2]:[4,tf_layers_esm_resolveScalarsInLogs(n)];case 1:i.sent(),r.push(this.yield(e,t,n)),i.label=2;case 2:return r.push(Object(tf_core_esm["nextFrame"])()),[4,Promise.all(r)];case 3:return i.sent(),[2]}})})},t.prototype.onEpochBegin=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){switch(n.label){case 0:return this.currentEpoch=e,null==this.epochBegin?[3,3]:[4,tf_layers_esm_resolveScalarsInLogs(t)];case 1:return n.sent(),[4,this.epochBegin(e,t)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},t.prototype.onEpochEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n;return tf_layers_esm_generator(this,function(r){switch(r.label){case 0:return n=[],null==this.epochEnd?[3,2]:[4,tf_layers_esm_resolveScalarsInLogs(t)];case 1:r.sent(),n.push(this.epochEnd(e,t)),r.label=2;case 2:return"epoch"===this.yieldEvery&&n.push(Object(tf_core_esm["nextFrame"])()),[4,Promise.all(n)];case 3:return r.sent(),[2]}})})},t.prototype.onBatchBegin=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){switch(n.label){case 0:return null==this.batchBegin?[3,3]:[4,tf_layers_esm_resolveScalarsInLogs(t)];case 1:return n.sent(),[4,this.batchBegin(e,t)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},t.prototype.onBatchEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n;return tf_layers_esm_generator(this,function(r){switch(r.label){case 0:return n=[],null==this.batchEnd?[3,2]:[4,tf_layers_esm_resolveScalarsInLogs(t)];case 1:r.sent(),n.push(this.batchEnd(e,t)),r.label=2;case 2:return"batch"===this.yieldEvery?n.push(Object(tf_core_esm["nextFrame"])()):tf_core_esm["util"].isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),[4,Promise.all(n)];case 3:return r.sent(),[2]}})})},t.prototype.onTrainBegin=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(t){switch(t.label){case 0:return null==this.trainBegin?[3,3]:[4,tf_layers_esm_resolveScalarsInLogs(e)];case 1:return t.sent(),[4,this.trainBegin(e)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},t.prototype.onTrainEnd=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(t){switch(t.label){case 0:return null==this.trainEnd?[3,3]:[4,tf_layers_esm_resolveScalarsInLogs(e)];case 1:return t.sent(),[4,this.trainEnd(e)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},t}(tf_layers_esm_BaseCallback);function tf_layers_esm_standardizeCallbacks(e,t){return null==e&&(e={}),e instanceof tf_layers_esm_BaseCallback?[e]:Array.isArray(e)&&e[0]instanceof tf_layers_esm_BaseCallback?e:tf_layers_esm_toList(e).map(function(e){return new tf_layers_esm_CustomCallback(e,t)})}var tf_layers_esm_CallbackConstructorRegistry=function(){function e(){}return e.registerCallbackConstructor=function(t,n){tf_core_esm["util"].assert(t>=0&&Number.isInteger(t),function(){return"Verbosity level is expected to be an integer >= 0, but got "+t}),e.checkForDuplicate(n),null==e.constructors[t]&&(e.constructors[t]=[]),e.constructors[t].push(n)},e.checkForDuplicate=function(t){for(var n in e.constructors){e.constructors[+n].forEach(function(e){if(e===t)throw new tf_layers_esm_ValueError("Duplicate callback constructor.")})}},e.clear=function(){e.constructors={}},e.createCallbacks=function(t){var n=[];for(var r in e.constructors){var i=+r;t>=i&&n.push.apply(n,e.constructors[i])}return n.map(function(e){return new e})},e.constructors={},e}();function tf_layers_esm_configureCallbacks(e,t,n,r,i,a,o,s,l){var u=new tf_layers_esm_History,c=[new tf_layers_esm_BaseLogger].concat(tf_layers_esm_CallbackConstructorRegistry.createCallbacks(t));null!=e&&c.push.apply(c,e),c.push(u);var p=new tf_layers_esm_CallbackList(c);return p.setParams({epochs:n,initialEpoch:r,samples:i,steps:a,batchSize:o,verbose:t,doValidation:s,metrics:l}),{callbackList:p,history:u}}function tf_layers_esm_deserialize(e,t,n){return void 0===t&&(t={}),void 0===n&&(n=!1),tf_layers_esm_deserializeKerasObject(e,tf_core_esm["serialization"].SerializationMap.getMap().classNameMap,t,"layer",n)}function tf_layers_esm_l2Normalize(e,t){return Object(tf_core_esm["tidy"])(function(){"float32"!==e.dtype&&(e=e.asType("float32"));var n=Object(tf_core_esm["sum"])(tf_layers_esm_square(e),t,!0),r=Object(tf_core_esm["fill"])(n.shape,dist_tf_layers_esm_epsilon()),i=Object(tf_core_esm["sqrt"])(Object(tf_core_esm["maximum"])(n,r));return Object(tf_core_esm["div"])(e,i)})}function tf_layers_esm_meanSquaredError(e,t){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["mean"])(tf_layers_esm_square(Object(tf_core_esm["sub"])(t,e)),-1)})}function tf_layers_esm_meanAbsoluteError(e,t){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["mean"])(Object(tf_core_esm["abs"])(Object(tf_core_esm["sub"])(t,e)),-1)})}function tf_layers_esm_meanAbsolutePercentageError(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["sub"])(e,t),r=Object(tf_core_esm["clipByValue"])(Object(tf_core_esm["abs"])(e),dist_tf_layers_esm_epsilon(),Number.MAX_VALUE),i=Object(tf_core_esm["abs"])(Object(tf_core_esm["div"])(n,r));return Object(tf_core_esm["mul"])(100,Object(tf_core_esm["mean"])(i,-1))})}function tf_layers_esm_meanSquaredLogarithmicError(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["clipByValue"])(t,dist_tf_layers_esm_epsilon(),Number.MAX_VALUE),r=Object(tf_core_esm["log"])(Object(tf_core_esm["add"])(1,n)),i=Object(tf_core_esm["clipByValue"])(e,dist_tf_layers_esm_epsilon(),Number.MAX_VALUE),a=Object(tf_core_esm["log"])(Object(tf_core_esm["add"])(1,i));return Object(tf_core_esm["mean"])(tf_layers_esm_square(Object(tf_core_esm["sub"])(r,a)),-1)})}function tf_layers_esm_squaredHinge(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["maximum"])(0,Object(tf_core_esm["sub"])(1,Object(tf_core_esm["mul"])(e,t)));return Object(tf_core_esm["mean"])(tf_layers_esm_square(n),-1)})}function tf_layers_esm_hinge(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["maximum"])(0,Object(tf_core_esm["sub"])(1,Object(tf_core_esm["mul"])(e,t)));return Object(tf_core_esm["mean"])(n,-1)})}function tf_layers_esm_categoricalHinge(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["sum"])(Object(tf_core_esm["mul"])(e,t),-1),r=Object(tf_core_esm["max"])(Object(tf_core_esm["mul"])(Object(tf_core_esm["sub"])(1,e),t),-1);return Object(tf_core_esm["maximum"])(0,Object(tf_core_esm["add"])(1,Object(tf_core_esm["sub"])(r,n)))})}function tf_layers_esm_logcosh(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Math.log(2),r=Object(tf_core_esm["sub"])(t,e),i=Object(tf_core_esm["sub"])(Object(tf_core_esm["add"])(r,Object(tf_core_esm["softplus"])(Object(tf_core_esm["mul"])(-2,r))),n);return Object(tf_core_esm["mean"])(i,-1)})}function tf_layers_esm_categoricalCrossentropy(e,t,n){return void 0===n&&(n=!1),Object(tf_core_esm["tidy"])(function(){if(n)t=Object(tf_core_esm["softmax"])(t);else{var r=Object(tf_core_esm["sum"])(t,t.shape.length-1,!0);t=Object(tf_core_esm["div"])(t,r)}return t=Object(tf_core_esm["clipByValue"])(t,dist_tf_layers_esm_epsilon(),1-dist_tf_layers_esm_epsilon()),Object(tf_core_esm["neg"])(Object(tf_core_esm["sum"])(Object(tf_core_esm["mul"])(e.toFloat(),Object(tf_core_esm["log"])(t)),t.shape.length-1))})}function tf_layers_esm_sparseCategoricalCrossentropy(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["floor"])(tf_layers_esm_flatten(e)).toInt(),r=(t=Object(tf_core_esm["clipByValue"])(t,dist_tf_layers_esm_epsilon(),1-dist_tf_layers_esm_epsilon())).shape;return tf_layers_esm_categoricalCrossentropy(Object(tf_core_esm["oneHot"])(n,r[r.length-1]).reshape(r),t,!1)})}function tf_layers_esm_sigmoidCrossEntropyWithLogits(e,t){if(!tf_core_esm["util"].arraysEqual(e.shape,t.shape))throw new tf_layers_esm_ValueError("logits and labels must have the same shape, but got shapes "+JSON.stringify(e.shape)+" and "+JSON.stringify(t.shape));return Object(tf_core_esm["tidy"])(function(){var n=t.relu(),r=t.abs().neg();return n.sub(t.mul(e)).add(r.exp().log1p())})}function tf_layers_esm_binaryCrossentropy(e,t){return Object(tf_core_esm["tidy"])(function(){var n;return n=Object(tf_core_esm["clipByValue"])(t,dist_tf_layers_esm_epsilon(),1-dist_tf_layers_esm_epsilon()),n=Object(tf_core_esm["log"])(Object(tf_core_esm["div"])(n,Object(tf_core_esm["sub"])(1,n))),Object(tf_core_esm["mean"])(tf_layers_esm_sigmoidCrossEntropyWithLogits(e,n),-1)})}function tf_layers_esm_kullbackLeiblerDivergence(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["clipByValue"])(e,dist_tf_layers_esm_epsilon(),1),r=Object(tf_core_esm["clipByValue"])(t,dist_tf_layers_esm_epsilon(),1);return Object(tf_core_esm["sum"])(Object(tf_core_esm["mul"])(e,Object(tf_core_esm["log"])(Object(tf_core_esm["div"])(n,r))),-1)})}function tf_layers_esm_poisson(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["log"])(Object(tf_core_esm["add"])(dist_tf_layers_esm_epsilon(),t));return Object(tf_core_esm["mean"])(Object(tf_core_esm["sub"])(t,Object(tf_core_esm["mul"])(e,n)),-1)})}function tf_layers_esm_cosineProximity(e,t){return Object(tf_core_esm["tidy"])(function(){var n=tf_layers_esm_l2Normalize(e,-1),r=tf_layers_esm_l2Normalize(t,-1),i=Object(tf_core_esm["mul"])(n,r);return Object(tf_core_esm["neg"])(Object(tf_core_esm["sum"])(i,-1))})}var tf_layers_esm_lossesMap={meanSquaredError:tf_layers_esm_meanSquaredError,meanAbsoluteError:tf_layers_esm_meanAbsoluteError,meanAbsolutePercentageError:tf_layers_esm_meanAbsolutePercentageError,meanSquaredLogarithmicError:tf_layers_esm_meanSquaredLogarithmicError,squaredHinge:tf_layers_esm_squaredHinge,hinge:tf_layers_esm_hinge,categoricalHinge:tf_layers_esm_categoricalHinge,logcosh:tf_layers_esm_logcosh,categoricalCrossentropy:tf_layers_esm_categoricalCrossentropy,sparseCategoricalCrossentropy:tf_layers_esm_sparseCategoricalCrossentropy,binaryCrossentropy:tf_layers_esm_binaryCrossentropy,kullbackLeiblerDivergence:tf_layers_esm_kullbackLeiblerDivergence,poisson:tf_layers_esm_poisson,cosineProximity:tf_layers_esm_cosineProximity};function tf_layers_esm_get(e){if("string"==typeof e){if(e in tf_layers_esm_lossesMap)return tf_layers_esm_lossesMap[e];var t="Unknown loss "+e;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t="Unknown loss "+e+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new tf_layers_esm_ValueError(t)}return e}function tf_layers_esm_binaryAccuracy(e,t){return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["mul"])(.5,Object(tf_core_esm["onesLike"])(t)),r=tf_layers_esm_cast$1(Object(tf_core_esm["greater"])(t,n),e.dtype);return Object(tf_core_esm["mean"])(Object(tf_core_esm["equal"])(e,r),-1)})}function tf_layers_esm_categoricalAccuracy(e,t){return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_cast$1(Object(tf_core_esm["equal"])(Object(tf_core_esm["argMax"])(e,-1),Object(tf_core_esm["argMax"])(t,-1)),"float32")})}function tf_layers_esm_truePositives(e,t){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["logicalAnd"])(e.equal(1),t.equal(1)).sum().cast("float32")})}function tf_layers_esm_falseNegatives(e,t){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["logicalAnd"])(e.equal(1),t.equal(0)).sum().cast("float32")})}function tf_layers_esm_falsePositives(e,t){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["logicalAnd"])(e.equal(0),t.equal(1)).sum().cast("float32")})}function tf_layers_esm_precision(e,t){return Object(tf_core_esm["tidy"])(function(){var n=tf_layers_esm_truePositives(e,t),r=tf_layers_esm_falsePositives(e,t),i=n.add(r);return Object(tf_core_esm["where"])(Object(tf_core_esm["greater"])(i,0),n.div(i),0).cast("float32")})}function tf_layers_esm_recall(e,t){return Object(tf_core_esm["tidy"])(function(){var n=tf_layers_esm_truePositives(e,t),r=tf_layers_esm_falseNegatives(e,t),i=n.add(r);return Object(tf_core_esm["where"])(Object(tf_core_esm["greater"])(i,0),n.div(i),0).cast("float32")})}function tf_layers_esm_binaryCrossentropy$1(e,t){return tf_layers_esm_binaryCrossentropy(e,t)}function tf_layers_esm_sparseCategoricalAccuracy(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),(t=t.argMax(-1)).dtype!==e.dtype&&(t=t.asType(e.dtype)),Object(tf_core_esm["equal"])(e,t).asType("float32")}var tf_layers_esm_mse$1=tf_layers_esm_meanSquaredError,tf_layers_esm_MSE$1=tf_layers_esm_meanSquaredError,tf_layers_esm_mae$1=tf_layers_esm_meanAbsoluteError,tf_layers_esm_MAE$1=tf_layers_esm_meanAbsoluteError,tf_layers_esm_mape$1=tf_layers_esm_meanAbsolutePercentageError,tf_layers_esm_MAPE$1=tf_layers_esm_meanAbsolutePercentageError,tf_layers_esm_categoricalCrossentropy$1=tf_layers_esm_categoricalCrossentropy,tf_layers_esm_cosine$1=tf_layers_esm_cosineProximity,tf_layers_esm_sparseCategoricalCrossentropy$1=tf_layers_esm_sparseCategoricalCrossentropy,tf_layers_esm_metricsMap={binaryAccuracy:tf_layers_esm_binaryAccuracy,categoricalAccuracy:tf_layers_esm_categoricalAccuracy,precision:tf_layers_esm_precision,categoricalCrossentropy:tf_layers_esm_categoricalCrossentropy$1,sparseCategoricalCrossentropy:tf_layers_esm_sparseCategoricalCrossentropy$1,mse:tf_layers_esm_mse$1,MSE:tf_layers_esm_MSE$1,mae:tf_layers_esm_mae$1,MAE:tf_layers_esm_MAE$1,mape:tf_layers_esm_mape$1,MAPE:tf_layers_esm_MAPE$1,cosine:tf_layers_esm_cosine$1};function tf_layers_esm_get$1(e){if("string"==typeof e&&e in tf_layers_esm_metricsMap)return tf_layers_esm_metricsMap[e];if("string"!=typeof e&&null!=e)return e;throw new tf_layers_esm_ValueError("Unknown metric "+e)}function tf_layers_esm_getLossOrMetricName(e){if(tf_layers_esm_assert(null!==e,"Unknown LossOrMetricFn "+e),"string"==typeof e)return e;for(var t=void 0,n=0,r=Object.keys(tf_layers_esm_lossesMap);n<r.length;n++){var i=r[n];if(tf_layers_esm_lossesMap[i]===e){t=i;break}}if(void 0!==t)return t;for(var a=0,o=Object.keys(tf_layers_esm_metricsMap);a<o.length;a++){i=o[a];if(tf_layers_esm_metricsMap[i]===e){t=i;break}}return void 0!==t?t:e.name}function tf_layers_esm_getOptimizer(e){var t={Adagrad:function(){return tf_core_esm["train"].adagrad(.01)},Adadelta:function(){return tf_core_esm["train"].adadelta(1,.95,dist_tf_layers_esm_epsilon())},Adam:function(){return tf_core_esm["train"].adam(.001,.9,.999,dist_tf_layers_esm_epsilon())},Adamax:function(){return tf_core_esm["train"].adamax(.002,.9,.999,dist_tf_layers_esm_epsilon(),0)},RMSProp:function(){return tf_core_esm["train"].rmsprop(.001,.9,0,dist_tf_layers_esm_epsilon())},SGD:function(){return tf_core_esm["train"].sgd(.01)}};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new tf_layers_esm_ValueError("Unknown Optimizer "+e)}var tf_layers_esm_MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH=1048576;function tf_layers_esm_checkUserDefinedMetadata(e,t,n){if(void 0===n&&(n=!1),null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!tf_layers_esm_plainObjectCheck(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){var r=JSON.stringify(e);r.length>tf_layers_esm_MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH&&console.warn('User-defined metadata of model "'+t+'" is too large in size (length='+r.length+" when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+tf_layers_esm_MAX_USER_DEFINED_METADATA_SERIALIZED_LENGTH+".")}}function tf_layers_esm_plainObjectCheck(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){for(var t=0,n=Object.keys(e);t<n.length;t++){var r=n[t];if("string"!=typeof r)return!1;if(!tf_layers_esm_plainObjectCheck(e[r]))return!1}return!0}if(Array.isArray(e)){for(var i=0,a=e;i<a.length;i++){if(!tf_layers_esm_plainObjectCheck(a[i]))return!1}return!0}return!1}var o=typeof e;return"string"===o||"number"===o||"boolean"===o}function tf_layers_esm_printSummary(e,t,n,r){void 0===r&&(r=console.log);var i,a=tf_layers_esm_isModelSequentialLike(e),o=["Layer (type)","Output shape","Param #"];if(a?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(function(e){return Math.floor(t*e)})),!a)for(var s in o.push("Receives inputs"),i=[],e.nodesByDepth)i.push.apply(i,e.nodesByDepth[s]);r("_".repeat(t)),tf_layers_esm_printRow(o,n,r),r("=".repeat(t));for(var l=e.layers,u=0;u<l.length;++u)a?tf_layers_esm_printLayerSummary(l[u],n,r):tf_layers_esm_printLayerSummaryWithConnections(l[u],n,i,r),r((u===l.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();var c=tf_layers_esm_countTrainableParams(e),p=tf_layers_esm_countParamsInWeights(e.nonTrainableWeights);r("Total params: "+(c+p)),r("Trainable params: "+c),r("Non-trainable params: "+p),r("_".repeat(t))}function tf_layers_esm_countTrainableParams(e){return null!=e.collectedTrainableWeights?tf_layers_esm_countParamsInWeights(e.collectedTrainableWeights):tf_layers_esm_countParamsInWeights(e.trainableWeights)}function tf_layers_esm_isModelSequentialLike(e){var t=!0,n=[],r=[];for(var i in e.nodesByDepth)n.push(e.nodesByDepth[i]);for(var a=0,o=n;a<o.length;a++){var s=o[a];if(s.length>1||1===s.length&&s[0].inboundLayers.length>1){t=!1;break}r.push.apply(r,s)}if(t)for(var l=0,u=e.layers;l<u.length;l++){for(var c=!1,p=0,h=u[l].inboundNodes;p<h.length;p++){var d=h[p];if(-1!==r.indexOf(d)){if(c){t=!1;break}c=!0}}if(!t)break}return t}function tf_layers_esm_printRow(e,t,n){void 0===n&&(n=console.log);for(var r="",i=0;i<e.length;++i)i>0&&(r=r.slice(0,r.length-1)+" "),r=(r+=e[i]).slice(0,t[i]),r+=" ".repeat(t[i]-r.length);n(r)}function tf_layers_esm_printLayerSummary(e,t,n){var r;try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}tf_layers_esm_printRow([e.name+" ("+e.getClassName()+")",r,e.countParams().toString()],t,n)}function tf_layers_esm_printLayerSummaryWithConnections(e,t,n,r){var i;try{i=JSON.stringify(e.outputShape)}catch(e){i="multiple"}for(var a=[],o=0,s=e.inboundNodes;o<s.length;o++){var l=s[o];if(!(null!=n&&n.length>0&&-1===n.indexOf(l)))for(var u=0;u<l.inboundLayers.length;++u){var c=l.inboundLayers[u].name,p=l.nodeIndices[u],h=l.tensorIndices[u];a.push(c+"["+p+"]["+h+"]")}}var d=e.name,f=e.getClassName(),g=0===a.length?"":a[0];tf_layers_esm_printRow([d+" ("+f+")",i,e.countParams().toString(),g],t,r);for(u=1;u<a.length;++u)tf_layers_esm_printRow(["","","",a[u]],t,r)}function tf_layers_esm_isArrayItemInputOrOutputName(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n}function tf_layers_esm_convertPythonicToTs(e,t){if(null===e)return null;if("string"==typeof e)return tf_layers_esm_toCamelCase(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var n=[],r=e.length,i=0;i<r;++i){var a=e[i];tf_layers_esm_isArrayItemInputOrOutputName(t,i,a)?n.push(a):n.push(tf_layers_esm_convertPythonicToTs(a,t))}return n}for(var o={},s=0,l=Object.keys(e);s<l.length;s++){var u=l[s],c=e[u];if("name"===u&&"string"==typeof c)o[u]=c;else{var p=tf_layers_esm_toCamelCase(u);o[p]=tf_layers_esm_convertPythonicToTs(c,p)}}return o}function tf_layers_esm_convertTsToPythonic(e,t){if(null===e||void 0===e)return null;if("string"==typeof e)return tf_layers_esm_toSnakeCase(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var n=[],r=e.length,i=0;i<r;++i){var a=e[i];tf_layers_esm_isArrayItemInputOrOutputName(t,i,a)?n.push(a):n.push(tf_layers_esm_convertTsToPythonic(a,t))}return n}for(var o={},s=0,l=Object.keys(e);s<l.length;s++){var u=l[s],c=e[u],p=tf_layers_esm_toSnakeCase(u);o[p]="name"!==u&&"className"!==u||"string"!=typeof c?tf_layers_esm_convertTsToPythonic(c,u):c}return o}var tf_layers_esm_version="1.7.2";function tf_layers_esm_assertFeedCompatibility(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return Object(tf_core_esm["cast"])(t,e.dtype)}catch(n){throw new tf_layers_esm_ValueError("The dtype of the feed ("+t.dtype+") can not be cast to the dtype of the key '"+e.name+"' ("+e.dtype+").")}}var tf_layers_esm_FeedDict=function(){function e(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof e)for(var n in t.id2Value)this.id2Value[n]=t.id2Value[n],n in t.id2Mask&&(this.id2Mask[n]=t.id2Mask[n]);else{if(null==t)return;for(var r=0,i=t;r<i.length;r++){var a=i[r];this.add(a.key,a.value)}}}return e.prototype.add=function(e,t,n){if(null!=this.id2Value[e.id])throw new tf_layers_esm_ValueError("Duplicate key: name="+e.name+", id="+e.id);return this.id2Value[e.id]=tf_layers_esm_assertFeedCompatibility(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this},e.prototype.addFeed=function(e){this.add(e.key,e.value)},e.prototype.hasKey=function(e){return null!=this.id2Value[e.id]},e.prototype.names=function(){return Object.keys(this.name2Id)},e.prototype.getValue=function(e){if(e instanceof tf_layers_esm_SymbolicTensor){if(null==this.id2Value[e.id])throw new tf_layers_esm_ValueError("Nonexistent key: "+e.name);return this.id2Value[e.id]}var t=this.name2Id[e];if(null==t)throw new tf_layers_esm_ValueError("Feed dict has no SymbolicTensor name: "+e);return this.id2Value[t]},e.prototype.getMask=function(e){if(e instanceof tf_layers_esm_SymbolicTensor){if(null==this.id2Value[e.id])throw new tf_layers_esm_ValueError("Nonexistent key: "+e.name);return this.id2Mask[e.id]}var t=this.name2Id[e];if(null==t)throw new tf_layers_esm_ValueError("Feed dict has no SymbolicTensor name: "+e);return this.id2Mask[t]},e.prototype.disposeMasks=function(){null!=this.id2Mask&&Object(tf_core_esm["dispose"])(this.id2Mask)},e}(),tf_layers_esm_cachedSorted={},tf_layers_esm_cachedRecipientCounts={};function tf_layers_esm_execute(e,t,n,r){for(var i=null!=n&&n.training,a=Array.isArray(e),o=a?e:[e],s=o.map(function(e){return e.name}),l=[],u=t.names(),c=0,p=s;c<p.length;c++){var h=p[c];-1!==u.indexOf(h)?l.push(t.getValue(h)):l.push(null)}null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);var d,f,g=s.join(",")+"|"+t.names().join(",");if(null==tf_layers_esm_cachedSorted[g]){var m=tf_layers_esm_getTopologicalSortAndRecipientCounts(o,t);d=m.sorted,f=m.recipientCounts,tf_layers_esm_cachedSorted[g]=d,tf_layers_esm_cachedRecipientCounts[g]=f}d=tf_layers_esm_cachedSorted[g],f={},i||Object.assign(f,tf_layers_esm_cachedRecipientCounts[g]);for(var y=new tf_layers_esm_FeedDict(t),v=0;v<d.length;++v){if(null!=r){var b=Object(tf_core_esm["memory"])().numTensors;b>r.maxNumTensors&&(r.maxNumTensors=b),b<r.minNumTensors&&(r.minNumTensors=b)}var w=d[v],z=w.sourceLayer;if(!(z instanceof tf_layers_esm_InputLayer)){for(var S=[],A=[],_=[],I=!1,C=0,E=w.inputs;C<E.length;C++){var N=E[C],k=y.getValue(N),x=y.getMask(N);S.push(k),A.push(x),null!=x&&(I=!0),i||(f[N.name]--,0!==f[N.name]||t.hasKey(N)||-1!==s.indexOf(N.name)||k.isDisposed||!0===N.sourceLayer.stateful||_.push(k))}I&&((n=n||{}).mask=A[0]);var L=tf_layers_esm_toList(z.apply(S,n)),T=null;z.supportsMasking&&(T=z.computeMask(S,A));for(var D=tf_layers_esm_getNodeOutputs(w),O=Array.isArray(D)?D:[D],R=0;R<O.length;++R){y.hasKey(O[R])||y.add(O[R],L[R],Array.isArray(T)?T[0]:T);var M=s.indexOf(O[R].name);-1!==M&&(l[M]=L[R])}i||Object(tf_core_esm["dispose"])(_)}}return y.disposeMasks(),a?l:l[0]}function tf_layers_esm_getTopologicalSortAndRecipientCounts(e,t){tf_core_esm["util"].assert(null!=e&&e.length>0,function(){return"Expected at least one fetch, got none"});var n=[],r={};if(1===e.length){var i=tf_layers_esm_getTopologicalSortAndRecipientCountsForOneFetch(e[0],t);n=i.sorted,r=i.recipientMap}else for(var a=new Set,o=0,s=e;o<s.length;o++){for(var l=tf_layers_esm_getTopologicalSortAndRecipientCountsForOneFetch(s[o],t),u=l.sorted,c=l.recipientMap,p=0,h=u;p<h.length;p++){var d=h[p];a.has(d.name)||(n.push(d),a.add(d.name))}var f=function(e){null==r[e]&&(r[e]=new Set),c[e].forEach(function(t){return r[e].add(t)})};for(var g in c)f(g)}return{sorted:n,recipientCounts:tf_layers_esm_recipientMap2Counts(r)}}function tf_layers_esm_recipientMap2Counts(e){var t={};for(var n in e)t[n]=e[n].size;return t}function tf_layers_esm_getTopologicalSortAndRecipientCountsForOneFetch(e,t){for(var n=new Set,r=[],i={},a=0,o=t.names();a<o.length;a++){var s=o[a];n.add(s)}var l=[],u=[];for(l.push(e);l.length>0;){var c=l[l.length-1];if(n.has(c.name))l.pop();else{var p=u[u.length-1]===l.length-1;if(0===c.inputs.length||p)l.pop(),r.push(c),n.add(c.name),p&&u.pop();else{u.push(l.length-1);for(var h=0,d=c.inputs;h<d.length;h++){var f=d[h];null==i[f.name]&&(i[f.name]=new Set),i[f.name].add(c.name),n.has(f.name)||l.push(f)}}}}return{sorted:r,recipientMap:i}}function tf_layers_esm_getNodeOutputs(e){var t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{for(var n=null,r=0;r<e.sourceLayer.inboundNodes.length;++r)for(var i=0,a=e.sourceLayer.inboundNodes[r].outputTensors;i<a.length;i++){if(a[i].id===e.id){n=r;break}}t=e.sourceLayer.getOutputAt(n)}return t}var tf_layers_esm_Container=function(e){function t(n){var r=e.call(this,{})||this;if(r.containerNodes=new Set,r.name=n.name,null==r.name){var i=r.getClassName().toLowerCase();r.name=tf_layers_esm_getUid(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],tf_layers_esm_unique(r.inputs).length!==r.inputs.length)throw new tf_layers_esm_ValueError("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map(function(e){return e.name}));tf_layers_esm_unique(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(e){return e.name})),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[],r.internalContainerRefs=[];for(var a=0,o=r.outputs;a<o.length;a++){var s=(C=o[a]).sourceLayer,l=C.nodeIndex,u=C.tensorIndex;r.outputLayers.push(s),r.outputLayersNodeIndices.push(l),r.outputLayersTensorIndices.push(u)}for(var c=0,p=r.inputs;c<p.length;c++){s=(C=p[c]).sourceLayer,l=C.nodeIndex,u=C.tensorIndex;tf_layers_esm_assert(0===l,"input layer has >1 nodes"),tf_layers_esm_assert(0===u,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(l),r.inputLayersTensorIndices.push(u)}r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var h=0;h<r.inputLayers.length;h++){if(!((s=r.inputLayers[h])instanceof tf_layers_esm_InputLayer))throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: "+n.inputs+". Input "+h+" (0-based) originates from layer type "+s.getClassName()+".");r.inputNames.push(s.name),r.feedInputShapes.push(s.batchInputShape),r.feedInputNames.push(s.name)}for(var d=0,f=r.outputLayers;d<f.length;d++){s=f[d];r.outputNames.push(s.name)}r.internalInputShapes=r.inputs.map(function(e){return e.shape}),r.internalOutputShapes=r.outputs.map(function(e){return e.shape});for(var g={},m={},y={},v={},b={},w=[],z=function(e,n,i,a,o,s){null!=a&&null!=o&&null!=s||(a=e.sourceLayer,o=e.nodeIndex,s=e.tensorIndex);var l=a.inboundNodes[o];if(-1!==i.indexOf(l))throw new tf_layers_esm_RuntimeError("The tensor "+e.name+' at layer "'+a.name+'" is part of a cycle.');if(-1===n.indexOf(l)){r.containerNodes.add(t.nodeKey(a,o)),a.id in b||(b[a.id]=Object.keys(b).length),-1===i.indexOf(l)&&i.push(l);for(var u=l.inboundLayers.length,c=0;c<u;c++){var p=l.inputTensors[c],h=l.inboundLayers[c],d=l.nodeIndices[c],f=l.tensorIndices[c];z(p,n,i,h,d,f)}for(n.push(l);i.indexOf(l)>=0;)i.splice(i.indexOf(l),1);w.push(l)}},S=[],A=[],_=0,I=r.outputs;_<I.length;_++){var C=I[_];z(C,S,A)}for(var E=0,N=w.slice().reverse();E<N.length;E++){m[(K=N[E]).id]=K,K.id in g||(g[K.id]=0);var k=g[K.id],x=null==y[K.outboundLayer.id]?0:y[K.outboundLayer.id];k=Math.max(k,x),y[K.outboundLayer.id]=k,v[K.outboundLayer.id]=K.outboundLayer,g[K.id]=k;for(h=0;h<K.inboundLayers.length;h++){var L=K.inboundLayers[h],T=(l=K.nodeIndices[h],L.inboundNodes[l]),D=null==g[T.id]?0:g[T.id];g[T.id]=Math.max(k+1,D),m[T.id]=T}}var O={};for(var R in g){(k=g[R])in O||(O[k]=[]),O[k].push(m[R])}var M={};for(var P in y){(k=y[P])in M||(M[k]=[]),M[k].push(v[P])}var F=Object.keys(M).map(function(e){return parseInt(e,10)}).sort(tf_layers_esm_reverseNumberCompare);r.layers=[];for(var V=0,B=F;V<B.length;V++){var U=M[k=B[V]];U.sort(function(e,t){var n=b[e.id],r=b[t.id];return n<r?-1:n>r?1:0});for(var j=0,W=U;j<W.length;j++){(s=W[j])instanceof t&&r.internalContainerRefs.push(s),r.layers.push(s)}}r.layersByDepth=M,F=Object.keys(O).map(function(e){return parseInt(e,10)}).sort(tf_layers_esm_reverseNumberCompare);for(var $=r.inputs.slice(),q=[],G=0,H=F;G<H.length;G++)for(var J=0,Z=O[k=H[G]];J<Z.length;J++){var K;if(null!=(s=(K=Z[J]).outboundLayer)){for(var Y=0,X=K.inputTensors;Y<X.length;Y++){C=X[Y];if(-1===$.indexOf(C))throw new tf_layers_esm_RuntimeError("Graph disconnected: cannot obtain value for tensor "+C+' at layer "'+s.name+'". The following previous layers were accessed without issue: '+q)}for(var Q=0,ee=K.outputTensors;Q<ee.length;Q++){C=ee[Q];$.push(C)}q.push(s.name)}}r.nodesByDepth=O;for(var te=r.layers.map(function(e){return e.name}),ne=function(e){var t=te.filter(function(t){return t===e}).length;if(1!==t)throw new tf_layers_esm_RuntimeError('The name "'+e+'" is used '+t+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(te))},re=0,ie=te;re<ie.length;re++){ne(ie[re])}return r.outboundNodes=[],r.inboundNodes=[],new tf_layers_esm_Node({outboundLayer:r,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:r.inputs,outputTensors:r.outputs,inputMasks:r.inputs.map(function(e){return null}),outputMasks:r.outputs.map(function(e){return null}),inputShapes:r.inputs.map(function(e){return e.shape}),outputShapes:r.outputs.map(function(e){return e.shape})}),r.built=!0,r._refCount=1,r}return tf_layers_esm_extends(t,e),t.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Container '"+this.name+"' is already disposed.")},t.prototype.dispose=function(){this.assertNotDisposed();var e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(var t=0,n=this.layers;t<n.length;t++){var r=n[t];e.numDisposedVariables+=r.dispose().numDisposedVariables}for(var i=0,a=this.internalContainerRefs;i<a.length;i++){var o=a[i];e.numDisposedVariables+=o.dispose().numDisposedVariables}}return e.refCountAfterDispose=this._refCount,e},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this.layers.forEach(function(t){t._trainableWeights.forEach(function(t){return t.trainable=e})}),this.trainable_=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){if(this._trainableWeights.length>0)throw new tf_layers_esm_ValueError("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 e=[],t=0,n=this.layers;t<n.length;t++){var r=n[t];e=e.concat(r.trainableWeights)}return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){for(var e=[],t=0,n=this.layers;t<n.length;t++){var r=n[t];e.push.apply(e,r.nonTrainableWeights)}if(!this.trainable){for(var i=[],a=0,o=this.layers;a<o.length;a++){r=o[a];i.push.apply(i,r.trainableWeights)}return i.concat(e)}return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),t.prototype.loadWeights=function(e,t){void 0===t&&(t=!0);for(var n={},r=0,i=0,a=this.layers;i<a.length;i++)for(var o=0,s=a[i].weights;o<s.length;o++){var l=s[o];if(null!=n[l.originalName])throw new tf_layers_esm_ValueError("Duplicate weight name: "+l.originalName);n[l.originalName]=l,r++}var u=[];for(var c in e){if(null!=n[c])u.push([n[c],e[c]]);else if(t)throw new tf_layers_esm_ValueError("Provided weight data has no target variable: "+c);delete n[c]}if(t){var p=[];for(var h in n)p.push(h);if(p.length>0)throw new tf_layers_esm_ValueError(p.length+" of "+r+" weights are not set: "+p)}tf_layers_esm_batchSetValue(u)},t.prototype.updatedConfig=function(){var e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion="tfjs-layers "+tf_layers_esm_version,t.backend="TensorFlow.js",t},t.prototype.toJSON=function(e,t){void 0===t&&(t=!0);var n=tf_layers_esm_convertTsToPythonic(this.updatedConfig());return t?JSON.stringify(n):n},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){e=tf_layers_esm_toList(e);for(var r=new tf_layers_esm_FeedDict,i=0;i<n.inputs.length;++i)r.add(n.inputs[i],e[i]);return tf_layers_esm_execute(n.outputs,r,t)})},t.prototype.computeMask=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var r;return e=tf_layers_esm_toList(e),r=null==t?tf_layers_esm_pyListRepeat(null,e.length):tf_layers_esm_toList(t),n.runInternalGraph(e,r)[1]})},t.prototype.computeOutputShape=function(e){var t=tf_layers_esm_normalizeShapeList(e);if(t.length!==this.inputLayers.length)throw new tf_layers_esm_ValueError("Invalid inputShape argument "+e+": model has "+this.inputLayers.length+" tensor inputs.");for(var n={},r=0;r<t.length;r++){var i=this.inputLayers[r],a=t[r];n[A=i.name+"_0_0"]=a}var o=Object.keys(this.nodesByDepth).map(function(e){return parseInt(e,10)}).sort(tf_layers_esm_reverseNumberCompare);if(o.length>1)for(var s=0,l=o;s<l.length;s++)for(var u=l[s],c=0,p=this.nodesByDepth[u];c<p.length;c++){var h=p[c];i=h.outboundLayer;if(-1===this.inputLayers.map(function(e){return e.id}).indexOf(i.id)){for(var d=[],f=0;f<h.inboundLayers.length;f++){var g=h.inboundLayers[f],m=h.nodeIndices[f],y=h.tensorIndices[f],v=n[A=g.name+"_"+m+"_"+y];d.push(v)}var b=tf_layers_esm_normalizeShapeList(i.computeOutputShape(tf_layers_esm_singletonOrArray(d))),w=i.inboundNodes.indexOf(h);for(f=0;f<b.length;f++){n[A=i.name+"_"+w+"_"+f]=b[f]}}}var z=[],S=[];for(r=0;r<this.outputLayers.length;r++){i=this.outputLayers[r],w=this.outputLayersNodeIndices[r],y=this.outputLayersTensorIndices[r];var A=i.name+"_"+w+"_"+y;S.push(A)}for(r=0;r<S.length;r++){var _=S[r];tf_layers_esm_assert(_ in n),z.push(n[_])}return tf_layers_esm_singletonOrArray(z)},t.prototype.runInternalGraph=function(e,t){null==t&&(t=tf_layers_esm_pyListRepeat(null,e.length));for(var n={},r=0;r<this.inputs.length;++r){var i=this.inputs[r],a=e[r],o=t[r];n[i.id]=[a,o]}for(var s=0,l=Object.keys(this.nodesByDepth).map(function(e){return parseInt(e,10)}).sort(tf_layers_esm_reverseNumberCompare);s<l.length;s++)for(var u=l[s],c=0,p=this.nodesByDepth[u];c<p.length;c++){for(var h=p[c],d=h.outboundLayer,f=h.inputTensors,g=h.outputTensors,m=new Array,y=0,v=f;y<v.length;y++){(i=v[y]).id in n&&m.push(n[i.id])}if(m.length===f.length){var b={},w=void 0,z=void 0,S=void 0,A=void 0;if(null!=h.callArgs&&(b=h.callArgs),1===m.length){var _=m[0],I=_[0],C=_[1];null==b.mask&&(b.mask=C),S=tf_layers_esm_toList(d.call(I,b)),A=tf_layers_esm_toList(d.computeMask(I,C)),w=[I],z=[C]}else w=m.map(function(e){return e[0]}),z=m.map(function(e){return e[1]}),null==b.mask&&(b.mask=z),S=tf_layers_esm_toList(d.call(w,b)),A=tf_layers_esm_toList(d.computeMask(w,z));if(d.activityRegularizer)throw new tf_layers_esm_NotImplementedError("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(r=0;r<g.length;++r){i=g[r],a=S[r],o=A[r];n[i.id]=[a,o]}}}for(var E=[],N=[],k=[],x=0,L=this.outputs;x<L.length;x++){tf_layers_esm_assert((i=L[x]).id in n,"Could not compute output "+i.name+" : "+i.id);var T=n[i.id],D=T[0];o=T[1];k.push(D.shape),E.push(D),N.push(o)}return[E,N,k]},t.prototype.buildNodeConversionMap=function(e){for(var n,r={},i=0,a=this.layers;i<a.length;i++){var o=a[i];n=o instanceof t?1:0;for(var s=0;s<o.inboundNodes.length;s++){var l=t.nodeKey(o,s);this.containerNodes.has(l)&&(r[l]=n,n+=1)}}return r},t.prototype.getLayer=function(e,t){if(null!=t){if(this.layers.length<=t)throw new tf_layers_esm_ValueError("Was asked to retrieve layer at index "+t+", but model only has "+this.layers.length+" layer(s).");return this.layers[t]}if(null==e)throw new tf_layers_esm_ValueError("Provide either a layer name or layer index");for(var n=0,r=this.layers;n<r.length;n++){var i=r[n];if(i.name===e)return i}throw new tf_layers_esm_ValueError("No such layer: "+e)},t.prototype.calculateLosses=function(){var e=this;return Object(tf_core_esm["tidy"])(function(){for(var n=[],r=0,i=e.layers;r<i.length;r++)for(var a=i[r],o=0;o<a.inboundNodes.length;++o){var s=t.nodeKey(a,o);e.containerNodes.has(s)&&n.push.apply(n,a.calculateLosses())}return n})},t.prototype.getConfig=function(){for(var e={name:this.name},n=this.buildNodeConversionMap(this.layers),r=[],i=0,a=this.layers;i<a.length;i++){for(var o=(w=a[i]).getClassName(),s=w.getConfig(),l=[],u=0;u<w.inboundNodes.length;u++){var c=w.inboundNodes[u],p=t.nodeKey(w,u),h={};if(this.containerNodes.has(p)){if(c.callArgs)try{JSON.stringify(c.callArgs),h=c.callArgs}catch(e){console.warn("Layer "+w.name+" was passed non-serializable keyword arguments: "+c.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),h={}}if(c.inboundLayers.length>0){for(var d=[],f=0;f<c.inboundLayers.length;f++){var g=c.inboundLayers[f],m=c.nodeIndices[f],y=c.tensorIndices[f];null==(S=n[t.nodeKey(g,m)])&&(S=0),d.push([g.name,S,y,h])}l.push(d)}}}var v={};v.name=w.name,v.className=o,v.config=s,v.inboundNodes=l,r.push(v)}e.layers=r;var b=[];for(f=0;f<this.inputLayers.length;f++){var w=this.inputLayers[f];m=this.inputLayersNodeIndices[f],p=t.nodeKey(w,m);if(this.containerNodes.has(p)){null!==(S=n[p])&&void 0!==S||(S=0);y=this.inputLayersTensorIndices[f];b.push([w.name,S,y])}}e.inputLayers=b;var z=[];for(f=0;f<this.outputLayers.length;f++){w=this.outputLayers[f],m=this.outputLayersNodeIndices[f],p=t.nodeKey(w,m);if(this.containerNodes.has(p)){var S;null!==(S=n[p])&&void 0!==S||(S=0);y=this.outputLayersTensorIndices[f];z.push([w.name,S,y])}}return e.outputLayers=z,e},t.fromConfig=function(e,t,n,r){void 0===n&&(n={}),void 0===r&&(r=!1);var i={},a={};function o(e,t){e.name in a?a[e.name].push(t):a[e.name]=[t]}function s(e,t){for(var n,r=[],a=0,s=t;a<s.length;a++){var l=s[a],u=l[0],c=l[1],p=l[2];if(n=null==l[3]?{}:l[3],!(u in i))return void o(e,t);var h=i[u];if(h.inboundNodes.length<=c)return void o(e,t);var d=h.inboundNodes[c];r.push(d.outputTensors[p])}r.length>0&&e.apply(tf_layers_esm_singletonOrArray(r),n)}function l(e){var n=e.name,a=tf_layers_esm_deserialize(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(r),i[n]=a,e.inboundNodes.forEach(function(e){if(!(e instanceof Array))throw new tf_layers_esm_ValueError("Corrupted configuration, expected array for nodeData: "+e);o(a,e)})}for(var u=t.name,c=t.layers,p=0,h=c;p<h.length;p++){l(g=h[p])}for(;!tf_layers_esm_isObjectEmpty(a);)for(var d=0,f=c;d<f.length;d++){var g=f[d];if((k=i[g.name]).name in a){var m=a[k.name];delete a[k.name];for(var y=0,v=m;y<v.length;y++){s(k,v[y])}}}for(var b=[],w=[],z=0,S=t.inputLayers;z<S.length;z++){var A=(g=S[z])[0],_=g[1],I=g[2];tf_layers_esm_assert(A in i);var C=(k=i[A]).inboundNodes[_].outputTensors;b.push(C[I])}for(var E=0,N=t.outputLayers;E<N.length;E++){A=(g=N[E])[0],_=g[1],I=g[2];tf_layers_esm_assert(A in i);var k;C=(k=i[A]).inboundNodes[_].outputTensors;w.push(C[I])}return new e({inputs:b,outputs:w,name:u})},Object.defineProperty(t.prototype,"stateful",{get:function(){if(this._stateful)throw new tf_layers_esm_ValueError("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(var e=0,t=this.layers;e<t.length;e++){if(t[e].stateful)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){var e=this;Object(tf_core_esm["tidy"])(function(){e.layers.forEach(function(e){e.stateful&&e.resetStates()})})},t}(tf_layers_esm_Layer);function tf_layers_esm_standardizeSampleOrClassWeights(e,t,n){var r=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map(function(e){return null});if(1===r)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==r)throw new Error("Provided "+n+" is an array of "+e.length+" element(s), but the model has "+r+" outputs. Make sure a set of weights is provided for each model output.");return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){var i=[];return t.forEach(function(t){t in e?i.push(e[t]):i.push(null)}),i}throw new Error("The model has multiple ("+r+") outputs, so "+n+" must be either an array with "+r+" elements or an object with "+t+" keys. Provided "+n+" not understood: "+JSON.stringify(e))}function tf_layers_esm_standardizeClassWeights(e,t){return tf_layers_esm_standardizeSampleOrClassWeights(e,t,"classWeight")}function tf_layers_esm_standardizeWeights(e,t,n,r){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var i,a,o,s,l;return tf_layers_esm_generator(this,function(u){switch(u.label){case 0:if(null!=t||null!=r)throw new Error("Support sampleWeight is not implemented yet");return null==n?[3,2]:(i=Object(tf_core_esm["tidy"])(function(){if(1===e.shape.length)return e.clone();if(2===e.shape.length){if(e.shape[1]>1){return e.argMax(1)}if(1===e.shape[1])return e.reshape([e.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+e.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}throw new Error("Unexpected rank of target (y) tensor ("+e.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),s=(o=Array).from,[4,i.data()]);case 1:return a=s.apply(o,[u.sent()]),Object(tf_core_esm["dispose"])(i),l=[],a.forEach(function(e){if(null==n[e])throw new Error("classWeight must contain all classes in the training data. The class "+e+" exists in the data but not in classWeight");l.push(n[e])}),[2,Object(tf_core_esm["tensor1d"])(l,"float32")];case 2:return[2,null]}})})}function tf_layers_esm_computeWeightedLoss(e,t){return Object(tf_core_esm["mul"])(e,t)}var tf_layers_esm_DEFAULT_VALIDATION_BATCH_SIZE=32;function tf_layers_esm_standardizeDataIteratorOutput(e,t){var n,r,i=t;n=i.xs,r=i.ys,tf_core_esm["util"].assert(null!=n&&null!=r,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+t});var a=tf_layers_esm_flattenTensorOrArrayOrMap("input",e.inputNames,n),o=tf_layers_esm_flattenTensorOrArrayOrMap("output",e.outputNames,r),s=a[0].shape[0];tf_core_esm["util"].assert(a.length===e.inputs.length,function(){return"LayersModel has "+e.inputs.length+" inputs, but the dataset provides "+a.length+" inputs. (Expected input keys: "+JSON.stringify(e.inputNames)+")"}),tf_core_esm["util"].assert(o.length===e.outputs.length,function(){return"LayersModel has "+e.outputs.length+" outputs, but the dataset provides "+o.length+" outputs. (Expected output keys: "+JSON.stringify(e.outputNames)+")"});for(var l=function(t){tf_core_esm["util"].assert(a[t].shape[0]===s,function(){return"Batch size mismatch: input "+e.inputNames[t]+" has "+a[t].shape[0]+"; expected "+s+" based on input "+e.inputNames[0]+"."})},u=0;u<a.length;u++)l(u);for(var c=function(t){tf_core_esm["util"].assert(o[t].shape[0]===s,function(){return"Batch size mismatch: output "+e.outputNames[t]+" has "+o[t].shape[0]+"; expected "+s+" based on input "+e.inputNames[0]+"."})},p=0;p<o.length;p++)c(p);return{xs:a,ys:o}}function tf_layers_esm_flattenTensorOrArrayOrMap(e,t,n){if(n instanceof tf_core_esm["Tensor"])return[n];if(Array.isArray(n))return tf_core_esm["util"].assert(n.length===t.length,function(){return"Received an array of "+n.length+" Tensors, but expected "+t.length+" to match the "+e+" keys "+t+"."}),n;for(var r=[],i=0,a=t;i<a.length;i++){var o=a[i];if(null==n[o])throw new tf_layers_esm_ValueError("The feature data generated by the dataset lacks the required "+e+" key '"+o+"'.");r.push(n[o])}return r}function tf_layers_esm_standardizeTensorValidationData(e){if(3===e.length)throw new tf_layers_esm_NotImplementedError("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}function tf_layers_esm_fitDataset(e,t,n){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var r,i,a,o,s,l,u,c,p,h,d,f,g,m,y,v,b,w,z,S,A,_,I,C,E,N,k,x,L,T,D,O,R,M;return tf_layers_esm_generator(this,function(P){switch(P.label){case 0:if(r=null!=n.batchesPerEpoch,tf_core_esm["util"].assert(null!=e.optimizer,function(){return"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."}),tf_core_esm["util"].assert(null!=n,function(){return"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."}),tf_core_esm["util"].assert(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+n.epochs}),tf_core_esm["util"].assert(!r||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}),tf_core_esm["util"].assert(null==n.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0,P.label=1;case 1:return P.trys.push([1,,26,27]),i=null!=n.validationData,a=void 0,o=void 0,i&&(tf_layers_esm_isDatasetObject(n.validationData)?tf_core_esm["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}):(s=tf_layers_esm_standardizeTensorValidationData(n.validationData),a=s.xs,o=s.ys)),l=e.makeTrainFunction(),u=e.getDedupedMetricsNames(),c=void 0,c=i?u.slice().concat(u.map(function(e){return"val_"+e})):u.slice(),p=tf_layers_esm_standardizeCallbacks(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,d=tf_layers_esm_configureCallbacks(p,h,n.epochs,null,null,tf_layers_esm_getStepsPerEpoch(t,n),null,i,c),f=d.callbackList,g=d.history,f.setModel(e),e.history=g,[4,f.onTrainBegin()];case 2:return P.sent(),e.stopTraining_=!1,m=null==n.initialEpoch?0:n.initialEpoch,[4,t.iterator()];case 3:y=P.sent(),P.label=4;case 4:return m<n.epochs?(v={},[4,f.onEpochBegin(m)]):[3,23];case 5:return P.sent(),b=0,w=0,r?[3,7]:[4,t.iterator()];case 6:y=P.sent(),P.label=7;case 7:return!r||b<n.batchesPerEpoch?[4,y.next()]:[3,21];case 8:return z=P.sent(),r&&z.done?(console.warn("You provided `batchesPerEpoch` as "+n.batchesPerEpoch+", but your dataset iterator ran out of data after "+b+" batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, "+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset."),[3,21]):null==z.value?[3,15]:(S=tf_layers_esm_standardizeDataIteratorOutput(e,z.value),A=S.xs,_=S.ys,(I={}).batch=w,I.size=A[0].shape[0],[4,f.onBatchBegin(w,I)]);case 9:if(P.sent(),C=[],null==n.classWeight)return[3,13];E=tf_layers_esm_standardizeClassWeights(n.classWeight,e.outputNames),M=0,P.label=10;case 10:return M<E.length?(k=(N=C).push,[4,tf_layers_esm_standardizeWeights(_[M],null,E[M])]):[3,13];case 11:k.apply(N,[P.sent()]),P.label=12;case 12:return++M,[3,10];case 13:for(x=A.concat(_).concat(C),L=l(x),Object(tf_core_esm["dispose"])(x),M=0;M<u.length;++M)T=u[M],D=L[M],I[T]=D,Object(tf_core_esm["keep"])(D);return[4,f.onBatchEnd(w,I)];case 14:P.sent(),tf_layers_esm_disposeTensorsInLogs(I),w++,b++,P.label=15;case 15:return(r?b>=n.batchesPerEpoch:z.done)?i?(O=void 0,tf_layers_esm_isDatasetObject(n.validationData)?(R=tf_layers_esm_toList,[4,e.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return O=R.apply(void 0,[P.sent()]),[3,18];case 17:O=tf_layers_esm_toList(e.evaluate(a,o,{batchSize:null==n.validationBatchSize?tf_layers_esm_DEFAULT_VALIDATION_BATCH_SIZE:n.validationBatchSize,verbose:0})),P.label=18;case 18:for(M=0;M<e.metricsNames.length;++M)v["val_"+e.metricsNames[M]]=O[M];P.label=19;case 19:return[3,21];case 20:return e.stopTraining_?[3,21]:[3,7];case 21:return[4,f.onEpochEnd(m,v)];case 22:return P.sent(),m++,e.stopTraining_?[3,23]:[3,4];case 23:return[4,f.onTrainEnd()];case 24:return P.sent(),[4,e.history.syncData()];case 25:return P.sent(),[2,e.history];case 26:return e.isTraining=!1,[7];case 27:return[2]}})})}function tf_layers_esm_getStepsPerEpoch(e,t){var n=null;return null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function tf_layers_esm_isDatasetObject(e){return"function"==typeof e.iterator}function tf_layers_esm_isLazyIteratorObject(e){return"function"==typeof e.next}function tf_layers_esm_evaluateDataset(e,t,n){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var r,i,a,o,s,l,u,c,p,h;return tf_layers_esm_generator(this,function(d){switch(d.label){case 0:if(r=null!=(n=n||{}).batches,i=e.testFunction,a=[],n.verbose>0)throw new tf_layers_esm_NotImplementedError("Verbose mode is not implemented yet.");return tf_core_esm["util"].assert(!r||n.batches>0&&Number.isInteger(n.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)}),tf_layers_esm_isLazyIteratorObject(t)?(s=t,[3,3]):[3,1];case 1:return[4,t.iterator()];case 2:s=d.sent(),d.label=3;case 3:o=s,l=0,u=0,c=function(){var t;return tf_layers_esm_generator(this,function(s){switch(s.label){case 0:return[4,o.next()];case 1:return t=s.sent(),a=Object(tf_core_esm["tidy"])(function(){if(t.value){var n=tf_layers_esm_standardizeDataIteratorOutput(e,t.value),r=n.xs,o=n.ys,s=r.concat(o),c=Object(tf_core_esm["tidy"])(function(){return i(s)});if(Object(tf_core_esm["dispose"])(s),0===u)for(var p=0;p<c.length;++p)a.push(Object(tf_core_esm["scalar"])(0));var h=s[0].shape[0],d=function(e){var t=c[e],n=a[e];a[e]=Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["add"])(a[e],Object(tf_core_esm["mul"])(h,t))}),u>0&&Object(tf_core_esm["dispose"])(n)};for(p=0;p<c.length;++p)d(p);Object(tf_core_esm["dispose"])(c),l+=h,++u}return a}),t.done?(r&&console.warn("Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least `batches` batches (in this case, "+n.batches+" batches). You may need to use the repeat() function when building your dataset."),[2,"break"]):[2]}})},d.label=4;case 4:return!r||u<n.batches?[5,c()]:[3,6];case 5:return"break"===d.sent()?[3,6]:[3,4];case 6:for(p=0;p<a.length;++p)h=a[p],a[p]=Object(tf_core_esm["div"])(a[p],l),Object(tf_core_esm["dispose"])(h);return[2,tf_layers_esm_singletonOrArray(a)]}})})}function tf_layers_esm_checkBatchSize(e){tf_core_esm["util"].assert(e>0&&Number.isInteger(e),function(){return"batchSize is required to be a positive integer, but got "+e})}function tf_layers_esm_sliceArrays(e,t,n){return null==e?[null]:Array.isArray(e)?e.map(function(e){return tf_layers_esm_sliceAlongFirstAxis(e,t,n-t)}):tf_layers_esm_sliceAlongFirstAxis(e,t,n-t)}function tf_layers_esm_sliceArraysByIndices(e,t){return Object(tf_core_esm["tidy"])(function(){return null==e?null:Array.isArray(e)?e.map(function(e){return tf_layers_esm_sliceArraysByIndices(e,t)}):tf_layers_esm_gather$1(e,"int32"===t.dtype?t:t.toInt())})}function tf_layers_esm_makeBatches(e,t){for(var n=[],r=0,i=null;r<e;)(i=r+t)>=e&&(i=e),n.push([r,i]),r=i;return n}function tf_layers_esm_fitLoop(e,t,n,r,i,a,o,s,l,u,c,p,h,d,f){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var g,m,y,v,b,w,z,S;return tf_layers_esm_generator(this,function(A){switch(A.label){case 0:if(null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0),g=!1,null!=l&&null!=u&&(g=!0),null!=f&&(g=!0,null==d))throw new tf_layers_esm_ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(m=e.checkNumSamples(n,i,d,"steps_per_epoch"))&&(y=tf_layers_esm_range(0,m)),null==o&&(o=1),v=tf_layers_esm_configureCallbacks(s,o,a,h,m,d,i,g,p),b=v.callbackList,w=v.history,b.setModel(e),e.history=w,[4,b.onTrainBegin()];case 1:A.sent(),e.stopTraining_=!1,z=function(a){var o,s,p,h,f;return tf_layers_esm_generator(this,function(v){switch(v.label){case 0:return[4,b.onEpochBegin(a)];case 1:if(v.sent(),o={},null==d)return[3,2];throw new tf_layers_esm_NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new tf_layers_esm_NotImplementedError("batch shuffling is not implemneted yet");c&&tf_core_esm["util"].shuffle(y),s=Object(tf_core_esm["tensor1d"])(y),p=tf_layers_esm_makeBatches(m,i),h=function(a){var c;return tf_layers_esm_generator(this,function(h){switch(h.label){case 0:return c={},[4,b.onBatchBegin(a,c)];case 1:return h.sent(),Object(tf_core_esm["tidy"])(function(){var h=p[a][0],d=p[a][1],f=tf_layers_esm_sliceAlongFirstAxis(s,h,d-h);c.batch=a,c.size=d-h;for(var m=tf_layers_esm_sliceArraysByIndices(n,f),y=t(m),v=0;v<r.length;++v){var b=r[v],w=y[v];c[b]=w,Object(tf_core_esm["keep"])(w)}if(a===p.length-1&&g){var z=e.testLoop(l,u,i);for(v=0;v<r.length;++v){b=r[v],w=z[v];Object(tf_core_esm["keep"])(w),o["val_"+b]=w}}}),[4,b.onBatchEnd(a,c)];case 2:return h.sent(),tf_layers_esm_disposeTensorsInLogs(c),e.stopTraining_?[2,"break"]:[2]}})},f=0,v.label=3;case 3:return f<p.length?[5,h(f)]:[3,6];case 4:if("break"===v.sent())return[3,6];v.label=5;case 5:return++f,[3,3];case 6:s.dispose(),v.label=7;case 7:return[4,b.onEpochEnd(a,o)];case 8:return v.sent(),e.stopTraining_?[2,"break"]:[2]}})},S=h,A.label=2;case 2:return S<a?[5,z(S)]:[3,5];case 3:if("break"===A.sent())return[3,5];A.label=4;case 4:return++S,[3,2];case 5:return[4,b.onTrainEnd()];case 6:return A.sent(),[4,e.history.syncData()];case 7:return A.sent(),[2,e.history]}})})}function tf_layers_esm_fitTensors(e,t,n,r){return void 0===r&&(r={}),tf_layers_esm_awaiter(this,void 0,void 0,function(){var i,a,o,s,l,u,c,p,h,d,f,g,m,y,v,b,w,z,S,A,_,I;return tf_layers_esm_generator(this,function(C){switch(C.label){case 0:if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0,C.label=1;case 1:return C.trys.push([1,,7,8]),tf_layers_esm_checkBatchSize(p=null==r.batchSize?32:r.batchSize),h=!1,[4,e.standardizeUserData(t,n,r.sampleWeight,r.classWeight,h,p)];case 2:if(d=C.sent(),i=d[0],a=d[1],c=d[2],f=!1,g=void 0,!(null!=r.validationData&&r.validationData.length>0))return[3,4];if(f=!0,2!==r.validationData.length)throw 3===r.validationData.length?new tf_layers_esm_NotImplementedError("validationData including sample weights is not supported yet."):new tf_layers_esm_ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+r.validationData+" is invalid.");return o=r.validationData[0],s=r.validationData[1],m=!0,[4,e.standardizeUserData(o,s,null,null,m,p)];case 3:return y=C.sent(),l=y[0],u=y[1],g=l.concat(u),[3,5];case 4:null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(f=!0,v=Math.floor(i[0].shape[0]*(1-r.validationSplit)),b=i[0].shape[0],l=tf_layers_esm_sliceArrays(i,v,b),i=tf_layers_esm_sliceArrays(i,0,v),u=tf_layers_esm_sliceArrays(a,v,b),a=tf_layers_esm_sliceArrays(a,0,v),g=l.concat(u)):null!=r.validationSteps&&(f=!0),C.label=5;case 5:return w=i.concat(a).concat(c),e.checkTrainableWeightsConsistency(),z=e.makeTrainFunction(),S=e.getDedupedMetricsNames(),A=void 0,_=void 0,f?(e.makeTestFunction(),A=e.testFunction,_=S.slice().concat(S.map(function(e){return"val_"+e}))):(A=null,g=[],_=S.slice()),I=tf_layers_esm_standardizeCallbacks(r.callbacks,r.yieldEvery),[4,tf_layers_esm_fitLoop(e,z,w,S,p,r.epochs,r.verbose,I,A,g,r.shuffle,_,r.initialEpoch,null,null)];case 6:return[2,C.sent()];case 7:return e.isTraining=!1,tf_layers_esm_disposeNewTensors(i,t),tf_layers_esm_disposeNewTensors(a,n),tf_layers_esm_disposeNewTensors(l,o),tf_layers_esm_disposeNewTensors(u,s),null!=c&&Object(tf_core_esm["dispose"])(c),[7];case 8:return[2]}})})}function tf_layers_esm_ensureTensorsRank2OrHigher(e){var t=[];e instanceof tf_core_esm["Tensor"]&&(e=[e]);for(var n=0;n<e.length;++n){var r=e[n];if(1===r.rank)t.push(tf_layers_esm_expandDims$1(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r)}}return t}function tf_layers_esm_disposeNewTensors(e,t){if(null!=e){var n=[];if(t instanceof tf_core_esm["Tensor"])n.push(t.id);else if(Array.isArray(t))t.forEach(function(e){return n.push(e.id)});else if(null!=t)for(var r in t){var i=t[r];n.push(i.id)}var a=[];if(e instanceof tf_core_esm["Tensor"])-1===n.indexOf(e.id)&&a.push(e);else if(Array.isArray(e))e.forEach(function(e){-1===n.indexOf(e.id)&&a.push(e)});else if(null!=e)for(var o in e){var s=e[o];-1===n.indexOf(s.id)&&a.push(s)}a.forEach(function(e){e.isDisposed||e.dispose()})}}function tf_layers_esm_isDataTensor(e){return e instanceof tf_core_esm["Tensor"]}function tf_layers_esm_isDataArray(e){return Array.isArray(e)}function tf_layers_esm_isDataDict(e){return!tf_layers_esm_isDataTensor(e)&&!tf_layers_esm_isDataArray(e)}function tf_layers_esm_standardizeInputData(e,t,n,r,i){if(void 0===r&&(r=!0),void 0===i&&(i=""),null==t||0===t.length){if(null!=e){var a=!1;if(tf_layers_esm_isDataArray(e)&&e.length>0)a=!0;else if(tf_layers_esm_isDataDict(e)){for(var o in e)if(e.hasOwnProperty(o)){a=!0;break}}else a=!0;if(a)throw new tf_layers_esm_ValueError("Error when checking model "+i+" expected no data, but got "+e)}return[]}if(null==e)return t.map(function(e){return null});var s;if(tf_layers_esm_isDataDict(e)){e=e,s=[];for(var l=0,u=t;l<u.length;l++){var c=u[l];if(null==e[c])throw new tf_layers_esm_ValueError('No data provided for "'+c+'". Need data for each key in: '+t);s.push(e[c])}}else if(tf_layers_esm_isDataArray(e)){if((e=e).length!==t.length)throw new tf_layers_esm_ValueError("Error when checking model "+i+": the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see "+t.length+" Tensor(s), but instead got the following list of Tensor(s): "+e);s=e}else{if(e=e,t.length>1)throw new tf_layers_esm_ValueError("The model "+i+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e]}if(s=tf_layers_esm_ensureTensorsRank2OrHigher(s),null!=n)for(var p=0;p<t.length;++p)if(null!=n[p]){var h=s[p];if(h.shape.length!==n[p].length)throw new tf_layers_esm_ValueError("Error when checking "+i+": expected "+t[p]+" to have "+n[p].length+" dimension(s). but got array with shape "+h.shape);for(var d=0;d<n[p].length;++d)if(0!==d||r){var f=h.shape[d],g=n[p][d];if(null!=g&&g>=0&&f!==g)throw new tf_layers_esm_ValueError("Error when checking "+i+": expected "+t[p]+" to have shape ["+n[p]+"], but got array with shape ["+h.shape+"].")}}return s}function tf_layers_esm_checkArrayLengths(e,t,n){var r=tf_layers_esm_unique(e.map(function(e){return e.shape[0]}));r.sort();var i=tf_layers_esm_unique(t.map(function(e){return e.shape[0]}));if(i.sort(),r.length>1)throw new tf_layers_esm_ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape})));if(i.length>1)throw new tf_layers_esm_ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape})));if(r.length>0&&i.length>0&&!tf_core_esm["util"].arraysEqual(r,i))throw new tf_layers_esm_ValueError("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+i[0]+" target sample(s).")}function tf_layers_esm_checkLossAndTargetCompatibility(e,t,n){for(var r=[tf_layers_esm_meanSquaredError,tf_layers_esm_binaryCrossentropy,tf_layers_esm_categoricalCrossentropy],i=0;i<e.length;++i){var a=e[i],o=t[i],s=n[i];if(null!=o){if(o===tf_layers_esm_categoricalCrossentropy&&1===a.shape[a.shape.length-1])throw new tf_layers_esm_ValueError("You are passing a target array of shape "+a.shape+" while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if(-1!==r.indexOf(o))for(var l=a.shape.slice(1),u=s.slice(1),c=0;c<l.length;++c){var p=l[c],h=u[c];if(null!=h&&p!==h)throw new tf_layers_esm_ValueError("A target Tensor with shape "+a.shape+" was passed for an output of shape "+s+", while using a loss function that expects targets to have the same shape as the output.")}}}}function tf_layers_esm_checkInputData(e,t,n,r,i){var a;if(void 0===r&&(r=!0),void 0===i&&(i=""),Array.isArray(e)){if(e.length!==t.length)throw new tf_layers_esm_ValueError("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 "+t.length+" Tensor(s), but instead got "+e.length+" Tensors(s).");a=e}else{if(t.length>1)throw new tf_layers_esm_ValueError("The model expects "+t.length+" "+i+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");a=[e]}if(null!=n)for(var o=0;o<t.length;++o)if(null!=n[o]){var s=a[o];if(s.shape.length!==n[o].length)throw new tf_layers_esm_ValueError("Error when checking "+i+": expected "+t[o]+" to have "+n[o].length+" dimension(s), but got array with shape "+JSON.stringify(s.shape));for(var l=0;l<n[o].length;++l)if(0!==l||r){var u=s.shape[l],c=n[o][l];if(null!=c&&c!==u)throw new tf_layers_esm_ValueError("Error when checking "+i+": expected "+t[o]+" to have shape "+JSON.stringify(n[o])+" but got array with shape "+JSON.stringify(s.shape)+".")}}}function tf_layers_esm_collectMetrics(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map(function(e){return[]});var n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError("Type of metrics argument not understood. Expected an string,function, Array, or Object, found: "+e);n=e}if(Array.isArray(n))return t.map(function(e){return n});for(var r=[],i=0,a=t;i<a.length;i++){var o=a[i],s=n.hasOwnProperty(o)?n[o]:[];Array.isArray(s)||(s=[s]),r.push(s)}return r}var tf_layers_esm_LAYERS_MODEL_FORMAT_NAME="layers-model",tf_layers_esm_LayersModel=function(e){function t(t){var n=e.call(this,t)||this;return n.isTraining=!1,n}return tf_layers_esm_extends(t,e),t.prototype.summary=function(e,t,n){if(void 0===n&&(n=console.log),!this.built)throw new tf_layers_esm_ValueError("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");tf_layers_esm_printSummary(this,e,t,n)},t.prototype.compile=function(e){var t=this;if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=tf_layers_esm_getOptimizer(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof tf_core_esm["Optimizer"]))throw new tf_layers_esm_ValueError("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}var n=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new tf_layers_esm_ValueError("When passing an Array as loss, it should have one entry per model output. The model has "+this.outputs.length+" output(s), but you passed loss="+e.loss+".");var r=e.loss;n=r.map(function(e){return tf_layers_esm_get(e)})}else{var i=tf_layers_esm_get(e.loss);this.outputs.forEach(function(e){n.push(i)})}else{for(var a in e.loss=e.loss,e.loss)if(-1===this.outputNames.indexOf(a))throw new tf_layers_esm_ValueError('Unknown entry in loss dictionary: "'+a+'". Only expected the following keys: '+this.outputNames);for(var o=0,s=this.outputNames;o<s.length;o++){var l=s[o];null==e.loss[l]&&console.warn('Output "'+l+'" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to '+l+" during training"),n.push(tf_layers_esm_get(e.loss[l]))}}this.lossFunctions=n,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var u=0;u<this.outputs.length;++u){var c=this.internalOutputShapes[u],p=this.outputNames[u];this.feedOutputNames.push(p),this.feedOutputShapes.push(c),this.feedLossFns.push(this.lossFunctions[u])}var h=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],tf_layers_esm_nameScope("loss",function(){for(var e=0;e<t.outputs.length;++e)if(-1===h.indexOf(e)){var n=t.lossFunctions[e];t.outputs.length>1&&(t.metricsTensors.push([n,e]),t.metricsNames.push(t.outputNames[e]+"_loss"))}});var d=tf_layers_esm_collectMetrics(e.metrics,this.outputNames);tf_layers_esm_nameScope("metric",function(){for(var e=function(e){if(-1!==h.indexOf(e))return"continue";!function(n){for(var r,i,a,o=function(n){if("string"==typeof n&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(n)){var o=t.internalOutputShapes[e];1===o[o.length-1]||t.lossFunctions[e]===tf_layers_esm_binaryCrossentropy?-1!==["accuracy","acc"].indexOf(n)?i=tf_layers_esm_binaryAccuracy:-1!==["crossentropy","ce"].indexOf(n)&&(i=tf_layers_esm_binaryCrossentropy$1):t.lossFunctions[e]===tf_layers_esm_sparseCategoricalCrossentropy?-1!==["accuracy","acc"].indexOf(n)?i=tf_layers_esm_sparseCategoricalAccuracy:-1!==["crossentropy","ce"].indexOf(n)&&(i=tf_layers_esm_sparseCategoricalCrossentropy$1):-1!==["accuracy","acc"].indexOf(n)?i=tf_layers_esm_categoricalAccuracy:-1!==["crossentropy","ce"].indexOf(n)&&(i=tf_layers_esm_categoricalCrossentropy$1);var s=void 0;-1!==["accuracy","acc"].indexOf(n)?s="acc":-1!==["crossentropy","ce"].indexOf(n)&&(s="ce"),a=i,r=""+s}else{var l=tf_layers_esm_get$1(n);a=l,r=""+tf_layers_esm_getLossOrMetricName(n)}var u;tf_layers_esm_nameScope(r,function(){u=a}),function(e,n,r){t.outputNames.length>1&&(n=t.outputNames[e]+"_"+n),t.metricsNames.push(n),t.metricsTensors.push([r,e])}(e,r,u)},s=0,l=n;s<l.length;s++)o(l[s])}(d[e])},n=0;n<t.outputs.length;++n)e(n)}),this.collectedTrainableWeights=this.trainableWeights},t.prototype.checkTrainableWeightsConsistency=function(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")},t.prototype.evaluate=function(e,t,n){void 0===n&&(n={});var r=null==n.batchSize?32:n.batchSize;tf_layers_esm_checkBatchSize(r);var i=this.standardizeUserDataXY(e,t,!0,r);try{var a=i[0].concat(i[1]);this.makeTestFunction();var o=this.testFunction;return tf_layers_esm_singletonOrArray(this.testLoop(o,a,r,n.verbose,n.steps))}finally{tf_layers_esm_disposeNewTensors(i[0],e),tf_layers_esm_disposeNewTensors(i[1],t)}},t.prototype.evaluateDataset=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){return this.makeTestFunction(),[2,tf_layers_esm_evaluateDataset(this,e,t)]})})},t.prototype.checkNumSamples=function(e,t,n,r){var i;if(void 0===r&&(r="steps"),null!=n){if(i=null,null!=t)throw new tf_layers_esm_ValueError("If "+r+" is set, batchSize must be null or undefined.Got batchSize = "+t)}else{if(null==e)throw new tf_layers_esm_ValueError("Either the input data should have a defined shape, or "+r+" shoud be specified.");i=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return i},t.prototype.execute=function(e,t){if(Array.isArray(t)&&0===t.length)throw new tf_layers_esm_ValueError("`outputs` is an empty Array, which is not allowed.");var n=Array.isArray(t),r=n?t:[t],i=this.retrieveSymbolicTensors(r),a=new tf_layers_esm_FeedDict;if(e instanceof tf_core_esm["Tensor"]&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new tf_layers_esm_ValueError("The number of inputs provided ("+e.length+") does not match the number of inputs of this model ("+this.inputs.length+").");for(var o=0;o<this.inputs.length;++o)a.add(this.inputs[o],e[o])}else for(var s=0,l=this.inputs;s<l.length;s++){var u=l[s],c=e[u.name];if(null==c)throw new tf_layers_esm_ValueError("No value is provided for the model's input "+u.name);a.add(u,c)}var p=tf_layers_esm_execute(i,a);return n?p:p[0]},t.prototype.retrieveSymbolicTensors=function(e){for(var t=tf_layers_esm_pyListRepeat(null,e.length),n=e.length,r=0,i=this.layers;r<i.length;r++){for(var a=i[r],o=Array.isArray(a.output)?a.output:[a.output],s=o.map(function(e){return e.name}),l=0;l<e.length;++l){var u=s.indexOf(e[l]);if(-1!==u&&(t[l]=o[u],n--),0===n)break}if(0===n)break}if(n>0){var c=[];throw t.forEach(function(t,n){null==t&&c.push(e[n])}),new tf_layers_esm_ValueError("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return t},t.prototype.predictLoop=function(e,t,n){var r=this;return void 0===t&&(t=32),void 0===n&&(n=!1),Object(tf_core_esm["tidy"])(function(){var i=r.checkNumSamples(e);if(n)throw new tf_layers_esm_NotImplementedError("Verbose predictLoop() is not implemented yet.");for(var a=tf_layers_esm_makeBatches(i,t),o=r.outputs.map(function(e){return[]}),s=function(t){Object(tf_core_esm["tidy"])(function(){var n=a[t][0],i=a[t][1],o=tf_layers_esm_sliceArrays(e,n,i),s=[];if(Array.isArray(o))for(var l=0;l<o.length;++l)s.push({key:r.inputs[l],value:o[l]});else s.push({key:r.inputs[0],value:o});var u=new tf_layers_esm_FeedDict(s);return tf_layers_esm_execute(r.outputs,u)}).forEach(function(e,t){return o[t].push(e)})},l=0;l<a.length;++l)s(l);return tf_layers_esm_singletonOrArray(o.map(function(e){return Object(tf_core_esm["concat"])(e,0)}))})},t.prototype.predict=function(e,t){void 0===t&&(t={});var n=tf_layers_esm_ensureTensorsRank2OrHigher(e);tf_layers_esm_checkInputData(n,this.inputNames,this.feedInputShapes,!1);try{var r=null==t.batchSize?32:t.batchSize;return tf_layers_esm_checkBatchSize(r),this.predictLoop(n,r)}finally{tf_layers_esm_disposeNewTensors(n,e)}},t.prototype.predictOnBatch=function(e){tf_layers_esm_checkInputData(e,this.inputNames,this.feedInputShapes,!0);var t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)},t.prototype.standardizeUserDataXY=function(e,t,n,r){if(void 0===n&&(n=!0),null==this.optimizer_)throw new tf_layers_esm_RuntimeError("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for(var i=[],a=0;a<this.feedOutputShapes.length;++a){var o=this.feedOutputShapes[a];this.feedLossFns[a]===tf_layers_esm_sparseCategoricalCrossentropy?i.push(o.slice(0,o.length-1).concat([1])):i.push(o)}if(tf_layers_esm_checkArrayLengths(e=tf_layers_esm_standardizeInputData(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=tf_layers_esm_standardizeInputData(t,this.feedOutputNames,i,!1,"target"),null),tf_layers_esm_checkLossAndTargetCompatibility(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&e[0].shape[0]%r!=0)throw new tf_layers_esm_ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+e[0].shape[0]+" sample(s).");return[e,t]},t.prototype.standardizeUserData=function(e,t,n,r,i,a){return void 0===i&&(i=!0),tf_layers_esm_awaiter(this,void 0,void 0,function(){var o,s,l,u,c,p,h,d;return tf_layers_esm_generator(this,function(f){switch(f.label){case 0:if(o=this.standardizeUserDataXY(e,t,i,a),s=o[0],l=o[1],null!=n)throw new Error("sample weight is not supported yet.");if(u=null,null==r)return[3,4];c=tf_layers_esm_standardizeClassWeights(r,this.outputNames),u=[],p=0,f.label=1;case 1:return p<c.length?(d=(h=u).push,[4,tf_layers_esm_standardizeWeights(l[p],null,c[p])]):[3,4];case 2:d.apply(h,[f.sent()]),f.label=3;case 3:return++p,[3,1];case 4:return[2,[s,l,u]]}})})},t.prototype.testLoop=function(e,t,n,r,i){var a=this;return void 0===r&&(r=0),Object(tf_core_esm["tidy"])(function(){var o=a.checkNumSamples(t,n,i,"steps"),s=[];if(r>0)throw new tf_layers_esm_NotImplementedError("Verbose mode is not implemented yet.");if(null!=i)throw new tf_layers_esm_NotImplementedError("steps mode in testLoop() is not implemented yet");for(var l=tf_layers_esm_makeBatches(o,n),u=Object(tf_core_esm["tensor1d"])(tf_layers_esm_range(0,o)),c=0;c<l.length;++c){var p=l[c][0],h=l[c][1],d=tf_layers_esm_sliceAlongFirstAxis(u,p,h-p),f=tf_layers_esm_sliceArraysByIndices(t,d),g=e(f);if(0===c)for(var m=0;m<g.length;++m)s.push(Object(tf_core_esm["scalar"])(0));for(m=0;m<g.length;++m){var y=g[m];s[m]=Object(tf_core_esm["add"])(s[m],Object(tf_core_esm["mul"])(h-p,y))}}for(m=0;m<s.length;++m)s[m]=Object(tf_core_esm["div"])(s[m],o);return s})},t.prototype.getDedupedMetricsNames=function(){for(var e=this.metricsNames,t=[],n=0;n<e.length;++n){var r=e[n],i=r;if(tf_layers_esm_count(e,r)>1)i+="_"+tf_layers_esm_count(e.slice(0,n),r);t.push(i)}return t},t.prototype.makeTrainFunction=function(){var e=this;return function(t){var n=[],r=t.slice(0,e.inputs.length),i=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),a=t.slice(e.inputs.length+e.outputs.length,e.inputs.length+2*e.outputs.length),o=[],s=e.collectedTrainableWeights.map(function(e){return e.read()});return[e.optimizer_.minimize(function(){for(var t=[],s=0;s<e.inputs.length;++s)t.push({key:e.inputs[s],value:r[s]});var l,u=new tf_layers_esm_FeedDict(t),c=tf_layers_esm_execute(e.outputs,u,{training:!0});for(s=0;s<e.lossFunctions.length;++s){var p=(0,e.lossFunctions[s])(i[s],c[s]);null!=a[s]&&(p=tf_layers_esm_computeWeightedLoss(p,a[s]));var h=Object(tf_core_esm["mean"])(p);n.push(h),l=0===s?p:Object(tf_core_esm["add"])(l,p)}for(s=0;s<e.metricsTensors.length;++s){var d=void 0;if(e.outputs.length>1&&s<e.outputs.length)d=n[s];else{var f=e.metricsTensors[s][0],g=e.metricsTensors[s][1];d=Object(tf_core_esm["mean"])(f(i[g],c[g]))}Object(tf_core_esm["keep"])(d),o.push(d)}return l=Object(tf_core_esm["mean"])(l),e.calculateLosses().forEach(function(e){l=Object(tf_core_esm["add"])(l,e)}),l},!0,s)].concat(o)}},t.prototype.makeTestFunction=function(){var e=this;this.testFunction=function(t){return Object(tf_core_esm["tidy"])(function(){for(var n,r=[],i=t.slice(0,e.inputs.length),a=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),o=[],s=0;s<e.inputs.length;++s)o.push({key:e.inputs[s],value:i[s]});var l=new tf_layers_esm_FeedDict(o),u=tf_layers_esm_execute(e.outputs,l);for(s=0;s<e.lossFunctions.length;++s){var c=e.lossFunctions[s],p=Object(tf_core_esm["mean"])(c(a[s],u[s]));n=0===s?p:Object(tf_core_esm["add"])(n,p),r.push(n)}for(s=0;s<e.metricsTensors.length;++s){var h=e.metricsTensors[s][0],d=e.metricsTensors[s][1],f=Object(tf_core_esm["mean"])(h(a[d],u[d]));r.push(f)}return r})}},t.prototype.fit=function(e,t,n){return void 0===n&&(n={}),tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(r){return[2,tf_layers_esm_fitTensors(this,e,t,n)]})})},t.prototype.fitDataset=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){return[2,tf_layers_esm_fitDataset(this,e,t)]})})},t.prototype.trainOnBatch=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r,i,a,o,s,l,u,c;return tf_layers_esm_generator(this,function(p){switch(p.label){case 0:return[4,this.standardizeUserData(e,t)];case 1:n=p.sent(),r=n[0],i=n[1],a=this.makeTrainFunction(),o=a(r.concat(i)),s=[],l=0,u=o,p.label=2;case 2:return l<u.length?[4,u[l].data()]:[3,5];case 3:c=p.sent(),s.push(c[0]),p.label=4;case 4:return l++,[3,2];case 5:return Object(tf_core_esm["dispose"])(o),[2,tf_layers_esm_singletonOrArray(s)]}})})},t.prototype.getNamedWeights=function(e){for(var t=[],n=null!=e&&e.trainableOnly,r=n?this.trainableWeights:this.weights,i=this.getWeights(n),a=0;a<r.length;++a)n&&!r[a].trainable||t.push({name:r[a].originalName,tensor:i[a]});return t},Object.defineProperty(t.prototype,"stopTraining",{get:function(){return this.stopTraining_},set:function(e){this.stopTraining_=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"optimizer",{get:function(){return this.optimizer_},set:function(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=e.prototype.dispose.call(this);if(0===t.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){var n=Object(tf_core_esm["memory"])().numTensors;this.optimizer_.dispose(),t.numDisposedVariables+=n-Object(tf_core_esm["memory"])().numTensors}return t},t.prototype.getLossIdentifiers=function(){var e;if("string"==typeof this.loss)e=tf_layers_esm_toSnakeCase(this.loss);else if(Array.isArray(this.loss)){for(var t=0,n=this.loss;t<n.length;t++){if("string"!=typeof n[t])throw new Error("Serialization of non-string loss is not supported.")}e=this.loss.map(function(e){return tf_layers_esm_toSnakeCase(e)})}else{var r=Object.keys(this.loss);e={};for(var i=this.loss,a=0,o=r;a<o.length;a++){var s=o[a];if("string"!=typeof i[s])throw new Error("Serialization of non-string loss is not supported.");e[s]=tf_layers_esm_toSnakeCase(i[s])}}return e},t.prototype.getMetricIdentifiers=function(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[tf_layers_esm_toSnakeCase(tf_layers_esm_getLossOrMetricName(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(function(e){return tf_layers_esm_toSnakeCase(tf_layers_esm_getLossOrMetricName(e))});var e={};for(var t in this.metrics)e[t]=tf_layers_esm_toSnakeCase(tf_layers_esm_getLossOrMetricName(this.metrics[t]));return e},t.prototype.getTrainingConfig=function(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}},t.prototype.loadTrainingConfig=function(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");var t,n,r=tf_layers_esm_deserialize(tf_layers_esm_convertPythonicToTs(e.optimizer_config));if("string"==typeof e.loss)t=tf_layers_esm_toCamelCase(e.loss);else if(Array.isArray(e.loss))t=e.loss.map(function(e){return tf_layers_esm_toCamelCase(e)});else if(null!=e.loss)for(var i in t={},e.loss)t[i]=tf_layers_esm_toCamelCase(e.loss[i]);if(Array.isArray(e.metrics))n=e.metrics.map(function(e){return tf_layers_esm_toCamelCase(e)});else if(null!=e.metrics)for(var i in n={},e.metrics)n[i]=tf_layers_esm_toCamelCase(e.metrics[i]);this.compile({loss:t,metrics:n,optimizer:r})},t.prototype.save=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r,i,a,o,s,l,u,c,p,h,d,f,g;return tf_layers_esm_generator(this,function(m){switch(m.label){case 0:if("string"==typeof e){if(0===(n=tf_core_esm["io"].getSaveHandlers(e)).length)throw new tf_layers_esm_ValueError("Cannot find any save handlers for URL '"+e+"'");if(n.length>1)throw new tf_layers_esm_ValueError("Found more than one ("+n.length+") save handlers for URL '"+e+"'");e=n[0]}if(null==e.save)throw new tf_layers_esm_ValueError("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,tf_core_esm["io"].encodeWeights(this.getNamedWeights(t))];case 1:return r=m.sent(),i=!1,a=null,o=this.toJSON(a,i),s={modelTopology:o,format:tf_layers_esm_LAYERS_MODEL_FORMAT_NAME,generatedBy:"TensorFlow.js tfjs-layers v"+tf_layers_esm_version,convertedBy:null},null!=t&&t.includeOptimizer&&null!=this.optimizer?(s.trainingConfig=this.getTrainingConfig(),l="optimizer",d=(h=tf_core_esm["io"]).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,d.apply(h,[m.sent(),l])];case 3:u=m.sent(),c=u.data,p=u.specs,(g=r.specs).push.apply(g,p),r.data=tf_core_esm["io"].concatenateArrayBuffers([r.data,c]),m.label=4;case 4:return null!=this.userDefinedMetadata&&(f=!0,tf_layers_esm_checkUserDefinedMetadata(this.userDefinedMetadata,this.name,f),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=r.data,s.weightSpecs=r.specs,[2,e.save(s)]}})})},t.prototype.setUserDefinedMetadata=function(e){tf_layers_esm_checkUserDefinedMetadata(e,this.name),this.userDefinedMetadata=e},t.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},t.className="Model",t}(tf_layers_esm_Container);function tf_layers_esm_modelFromJSON(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n,r,i,a,o,s,l,u;return tf_layers_esm_generator(this,function(c){switch(c.label){case 0:return"modelTopology"in e||(e={modelTopology:e}),null!=(n=(e=e).modelTopology).model_config&&(n=n.model_config),r=tf_layers_esm_convertPythonicToTs(n),i=tf_layers_esm_deserialize(r,t),null==e.weightsManifest?[3,2]:[4,tf_core_esm["io"].loadWeights(e.weightsManifest,e.pathPrefix,i.weights.map(function(e){return e.originalName}))];case 1:for(a=c.sent(),o={},s=0,l=i.weights;s<l.length;s++)u=l[s],o[u.originalName]=a[u.originalName];i.loadWeights(o),Object(tf_core_esm["dispose"])(a),c.label=2;case 2:return[2,i]}})})}function tf_layers_esm_loadLayersModelInternal(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n;return tf_layers_esm_generator(this,function(r){if(null==t&&(t={}),"string"==typeof e){if(0===(n=tf_core_esm["io"].getLoadHandlers(e,t.onProgress)).length)n.push(tf_core_esm["io"].browserHTTPRequest(e,t));else if(n.length>1)throw new tf_layers_esm_ValueError("Found more than one ("+n.length+") load handlers for URL '"+e+"'");e=n[0]}return[2,tf_layers_esm_loadLayersModelFromIOHandler(e,void 0,t)]})})}function tf_layers_esm_loadLayersModelFromIOHandler(e,t,n){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var r,i,a,o,s,l,u,c,p;return tf_layers_esm_generator(this,function(h){switch(h.label){case 0:if(null==n&&(n={}),null==e.load)throw new tf_layers_esm_ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(r=h.sent(),null!=(i=r.modelTopology).model_config&&(i=i.model_config),a=null==n.strict||n.strict,o=null!=r.weightData&&null!=r.weightSpecs&&a,s=tf_layers_esm_deserialize(tf_layers_esm_convertPythonicToTs(i),t,o),null!=(l=r.trainingConfig)&&s.loadTrainingConfig(l),null!=r.userDefinedMetadata&&s.setUserDefinedMetadata(r.userDefinedMetadata),null==r.weightData)return[3,4];if(null==r.weightSpecs)throw new tf_layers_esm_ValueError("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return u=tf_layers_esm_decodeModelAndOptimizerWeights(r.weightData,r.weightSpecs),c=u.modelWeights,p=u.optimizerWeights,s.loadWeights(c,a),null!=s.optimizer&&p.length>0?[4,s.optimizer.setWeights(p)]:[3,3];case 2:h.sent(),h.label=3;case 3:Object(tf_core_esm["dispose"])(c),Object(tf_core_esm["dispose"])(p.map(function(e){return e.tensor})),h.label=4;case 4:return[2,s]}})})}function tf_layers_esm_decodeModelAndOptimizerWeights(e,t){var n=tf_core_esm["io"].decodeWeights(e,t),r={},i=[];return t.forEach(function(e){"optimizer"===e.group?i.push({name:e.name,tensor:n[e.name]}):r[e.name]=n[e.name]}),{modelWeights:r,optimizerWeights:i}}tf_core_esm["serialization"].registerClass(tf_layers_esm_LayersModel);var tf_layers_esm_Sequential=function(e){function t(t){var n=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},n.trainable=!0,n.built=!1,n.name=null!=t.name?t.name:tf_layers_esm_getUid("sequential_"),null!=t.layers)for(var r=0,i=t.layers;r<i.length;r++){var a=i[r];n.add(a)}return n}return tf_layers_esm_extends(t,e),t.prototype.checkShape=function(e){if(e.inboundNodes[0].outputTensors[0].shape.some(function(e){return e<0}))throw new tf_layers_esm_ValueError("Negative dimension size caused by adding layer "+e.name+" with input shape ["+e.inboundNodes[0].inputTensors[0].shape+"]")},t.prototype.add=function(e){var n,r=e instanceof t||e instanceof tf_layers_esm_LayersModel;if(r){if(1!==(n=e).outputs.length)throw new tf_layers_esm_ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new tf_layers_esm_ValueError("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new tf_layers_esm_ValueError("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var i=tf_layers_esm_Input({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(i)}if(r)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new tf_layers_esm_ValueError("A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer "+e.name+" which has "+e.inboundNodes.length+" pre-existing inbound connections.");if(1!==e.inboundNodes[0].outputTensors.length)throw new tf_layers_esm_ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=tf_layers_esm_getSourceInputs(this.outputs[0])}this.inboundNodes=[],new tf_layers_esm_Node({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:tf_layers_esm_pyListRepeat(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(e){return e.shape}),outputShapes:this.outputs[0].shape})}else{var a=e.apply(this.outputs[0]);if(Array.isArray(a))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1},t.prototype.pop=function(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{var e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}},t.prototype.call=function(e,t){return null==this.model&&this.build(),this.model.call(e,t)},t.prototype.build=function(e){if(tf_layers_esm_getExactlyOneShape(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new tf_layers_esm_LayersModel({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0},t.prototype.countParams=function(){return this.built||this.build(),e.prototype.countParams.call(this)},t.prototype.summary=function(t,n,r){void 0===r&&(r=console.log),this.built||this.build(),e.prototype.summary.call(this,t,n,r)},t.prototype.setWeights=function(e){null==this.model&&this.build(),this.model.setWeights(e)},t.prototype.evaluate=function(e,t,n){if(void 0===n&&(n={}),!this.built)throw new tf_layers_esm_RuntimeError("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)},t.prototype.evaluateDataset=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){if(!this.built)throw new tf_layers_esm_RuntimeError("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(e,t)]})})},t.prototype.predict=function(e,t){return void 0===t&&(t={}),null==this.model&&this.build(),this.model.predict(e,t)},t.prototype.predictOnBatch=function(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)},t.prototype.compile=function(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames},Object.defineProperty(t.prototype,"optimizer",{get:function(){return null==this.model?void 0:this.model.optimizer},set:function(e){this.model.optimizer=e},enumerable:!0,configurable:!0}),t.prototype.fit=function(e,t,n){return void 0===n&&(n={}),tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(r){if(!this.built)throw new tf_layers_esm_RuntimeError("The model needs to be compiled before being used.");return[2,this.model.fit(e,t,n)]})})},t.prototype.fitDataset=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){if(!this.built)throw new tf_layers_esm_RuntimeError("The model needs to be compiled before being used.");return[2,this.model.fitDataset(e,t)]})})},t.prototype.trainOnBatch=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(n){return[2,this.model.trainOnBatch(e,t)]})})},t.fromConfig=function(e,n,r,i){var a;void 0===r&&(r={}),void 0===i&&(i=!1);var o={};if(n instanceof Array){if(null==n[0].className||"Merge"===n[0].className)throw new tf_layers_esm_ValueError("Legacy serialization format not supported yet.");a=n}else tf_core_esm["util"].assert(null!=n.layers,function(){return"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."}),a=n.layers,delete n.layers,o=n;var s=new e(o);if(!(s instanceof t))throw new tf_layers_esm_NotImplementedError("Sequential.fromConfig called on non-Sequential input: "+s);for(var l=0,u=a;l<u.length;l++){var c=tf_layers_esm_deserialize(u[l],void 0,i);i&&c.setFastWeightInitDuringBuild(!0),s.add(c)}return s},Object.defineProperty(t.prototype,"stopTraining",{get:function(){if(null==this.model)throw new tf_layers_esm_ValueError("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining},set:function(e){if(null==this.model)throw new tf_layers_esm_ValueError("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){for(var e=[],t=0,n=this.layers;t<n.length;t++){var r=n[t],i={};i.className=r.getClassName(),i.config=r.getConfig(),e.push(i)}return{name:this.name,layers:e}},t.className="Sequential",t}(tf_layers_esm_LayersModel);function tf_layers_esm_model(e){return new tf_layers_esm_LayersModel(e)}function tf_layers_esm_sequential(e){return new tf_layers_esm_Sequential(e)}function tf_layers_esm_loadLayersModel(e,t){return null==t&&(t={}),tf_layers_esm_loadLayersModelInternal(e,t)}function tf_layers_esm_input(e){return tf_layers_esm_Input(e)}function tf_layers_esm_registerCallbackConstructor(e,t){tf_layers_esm_CallbackConstructorRegistry.registerCallbackConstructor(e,t)}tf_core_esm["serialization"].registerClass(tf_layers_esm_Sequential);var tf_layers_esm_Activation=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.getConfig=function(){return{}},t}(tf_core_esm["serialization"].Serializable),tf_layers_esm_Elu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=1),tf_layers_esm_elu$1(e,t)},t.className="elu",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Elu);var tf_layers_esm_Selu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["selu"])(e)},t.className="selu",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Selu);var tf_layers_esm_Relu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["relu"])(e)},t.className="relu",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Relu);var tf_layers_esm_Relu6=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["tidy"])(function(){return Object(tf_core_esm["minimum"])(6,Object(tf_core_esm["relu"])(e))})},t.className="relu6",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Relu6);var tf_layers_esm_Linear=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return e},t.className="linear",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Linear);var tf_layers_esm_Sigmoid=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["sigmoid"])(e)},t.className="sigmoid",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Sigmoid);var tf_layers_esm_HardSigmoid=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return tf_layers_esm_hardSigmoid(e)},t.className="hardSigmoid",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_HardSigmoid);var tf_layers_esm_Softplus=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["softplus"])(e)},t.className="softplus",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Softplus);var tf_layers_esm_Softsign=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return tf_layers_esm_softsign(e)},t.className="softsign",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Softsign);var tf_layers_esm_Tanh=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){return Object(tf_core_esm["tanh"])(e)},t.className="tanh",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Tanh);var tf_layers_esm_Softmax=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=-1),Object(tf_core_esm["softmax"])(e,t)},t.className="softmax",t}(tf_layers_esm_Activation);tf_core_esm["serialization"].registerClass(tf_layers_esm_Softmax);var tf_layers_esm_LogSoftmax=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=-1),Object(tf_core_esm["logSoftmax"])(e,t)},t.className="logSoftmax",t}(tf_layers_esm_Activation);function tf_layers_esm_serializeActivation(e){return e.getClassName()}function tf_layers_esm_deserializeActivation(e,t){return void 0===t&&(t={}),tf_layers_esm_deserializeKerasObject(e,tf_core_esm["serialization"].SerializationMap.getMap().classNameMap,t,"activation")}function tf_layers_esm_getActivation(e){var t;return null==e?tf_layers_esm_deserializeActivation(t={className:"linear",config:{}}):"string"==typeof e?((t={}).className=e,t.config={},tf_layers_esm_deserializeActivation(t)):e instanceof tf_layers_esm_Activation?e:tf_layers_esm_deserializeActivation(e)}function tf_layers_esm_assertObjectArgs(e){if(null!=e&&"object"!=typeof e)throw new Error("Argument to L1L2 regularizer's constructor is expected to be an object, but received: "+e)}tf_core_esm["serialization"].registerClass(tf_layers_esm_LogSoftmax);var tf_layers_esm_Regularizer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t}(tf_core_esm["serialization"].Serializable),tf_layers_esm_L1L2=function(e){function t(t){var n=e.call(this)||this;return tf_layers_esm_assertObjectArgs(t),n.l1=null==t||null==t.l1?.01:t.l1,n.l2=null==t||null==t.l2?.01:t.l2,n.hasL1=0!==n.l1,n.hasL2=0!==n.l2,n}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e){var t=this;return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["zeros"])([1]);return t.hasL1&&(n=Object(tf_core_esm["add"])(n,Object(tf_core_esm["sum"])(Object(tf_core_esm["mul"])(t.l1,Object(tf_core_esm["abs"])(e))))),t.hasL2&&(n=Object(tf_core_esm["add"])(n,Object(tf_core_esm["sum"])(Object(tf_core_esm["mul"])(t.l2,tf_layers_esm_square(e))))),n.asScalar()})},t.prototype.getConfig=function(){return{l1:this.l1,l2:this.l2}},t.fromConfig=function(e,t){return new e({l1:t.l1,l2:t.l2})},t.className="L1L2",t}(tf_layers_esm_Regularizer);function tf_layers_esm_l1(e){return tf_layers_esm_assertObjectArgs(e),new tf_layers_esm_L1L2({l1:null!=e?e.l1:null,l2:0})}function tf_layers_esm_l2(e){return tf_layers_esm_assertObjectArgs(e),new tf_layers_esm_L1L2({l2:null!=e?e.l2:null,l1:0})}tf_core_esm["serialization"].registerClass(tf_layers_esm_L1L2);var tf_layers_esm_REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={l1l2:"L1L2"};function tf_layers_esm_serializeRegularizer(e){return tf_layers_esm_serializeKerasObject(e)}function tf_layers_esm_deserializeRegularizer(e,t){return void 0===t&&(t={}),tf_layers_esm_deserializeKerasObject(e,tf_core_esm["serialization"].SerializationMap.getMap().classNameMap,t,"regularizer")}function tf_layers_esm_getRegularizer(e){return null==e?null:"string"==typeof e?tf_layers_esm_deserializeRegularizer({className:e in tf_layers_esm_REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?tf_layers_esm_REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e,config:{}}):e instanceof tf_layers_esm_Regularizer?e:tf_layers_esm_deserializeRegularizer(e)}var tf_layers_esm_ReLU=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.supportsMasking=!0,null!=t&&(n.maxValue=t.maxValue),n}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){e=tf_layers_esm_getExactlyOneTensor(e);var n=Object(tf_core_esm["relu"])(e);return null!=this.maxValue&&(n=Object(tf_core_esm["clipByValue"])(n,0,this.maxValue)),n},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={maxValue:this.maxValue},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ReLU",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_ReLU);var tf_layers_esm_LeakyReLU=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_ALPHA=.3,null==t&&(t={}),n.alpha=null==t.alpha?n.DEFAULT_ALPHA:t.alpha,n}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=tf_layers_esm_getExactlyOneTensor(e);return Object(tf_core_esm["leakyRelu"])(n,this.alpha)},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={alpha:this.alpha},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="LeakyReLU",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_LeakyReLU);var tf_layers_esm_PReLU=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;if(n.DEFAULT_ALPHA_INITIALIZER="zeros",null==t&&(t={}),n.supportsMasking=!0,n.alphaInitializer=tf_layers_esm_getInitializer(t.alphaInitializer||n.DEFAULT_ALPHA_INITIALIZER),n.alphaRegularizer=tf_layers_esm_getRegularizer(t.alphaRegularizer),n.alphaConstraint=tf_layers_esm_getConstraint(t.alphaConstraint),null==t.sharedAxes)n.sharedAxes=null;else if(Array.isArray(t.sharedAxes))n.sharedAxes=t.sharedAxes;else{if("number"!=typeof t.sharedAxes)throw new tf_layers_esm_ValueError("Expected sharedAxes to be a number or an array of numbers, but got "+t.sharedAxes);n.sharedAxes=[t.sharedAxes]}return n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t=(e=tf_layers_esm_getExactlyOneShape(e)).slice(1);if(null!=this.sharedAxes)for(var n=0,r=this.sharedAxes;n<r.length;n++){t[(a=r[n])-1]=1}this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);var i={};if(null!=this.sharedAxes)for(var a=1;a<e.length;++a)i[a]=e[a];this.inputSpec=[new tf_layers_esm_InputSpec({ndim:e.length,axes:i})],this.built=!0},t.prototype.call=function(e,t){return e=tf_layers_esm_getExactlyOneTensor(e),Object(tf_core_esm["prelu"])(e,this.alpha.read())},t.prototype.getConfig=function(){var t={alphaInitializer:tf_layers_esm_serializeInitializer(this.alphaInitializer),alphaRegularizer:tf_layers_esm_serializeRegularizer(this.alphaRegularizer),alphaConstraint:tf_layers_esm_serializeConstraint(this.alphaConstraint),sharedAxes:this.sharedAxes},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="PReLU",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_PReLU);var tf_layers_esm_ELU=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;if(n.DEFAULT_ALPHA=1,null==t&&(t={}),null!=t.alpha&&t.alpha!==n.DEFAULT_ALPHA)throw new tf_layers_esm_NotImplementedError("Non-default alpha value ("+t.alpha+") is not supported by the ELU layer yet.");return n.alpha=null==t.alpha?n.DEFAULT_ALPHA:t.alpha,n}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=tf_layers_esm_getExactlyOneTensor(e);return Object(tf_core_esm["elu"])(n)},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={alpha:this.alpha},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ELU",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_ELU);var tf_layers_esm_ThresholdedReLU=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_THETA=1,null==t&&(t={}),n.theta=null==t.theta?n.DEFAULT_THETA:t.theta,n}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=tf_layers_esm_getExactlyOneTensor(e);return n.mul(tf_layers_esm_cast$1(n.greater(this.theta),"float32"))},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={theta:this.theta},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ThresholdedReLU",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_ThresholdedReLU);var tf_layers_esm_Softmax$1=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_AXIS=1,null==t&&(t={}),n.softmax=(new tf_layers_esm_Softmax).apply,n.axis=null==t.axis?n.DEFAULT_AXIS:t.axis,n}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=tf_layers_esm_getExactlyOneTensor(e);return this.softmax(n,this.axis)},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t={axis:this.axis},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Softmax",t}(tf_layers_esm_Layer);function tf_layers_esm_normalizeArray(e,t,n){if("number"==typeof e)return tf_layers_esm_pyListRepeat(e,t);if(e.length!==t)throw new tf_layers_esm_ValueError("The "+n+" argument must be an integer or tuple of "+t+" integers. Received: "+e.length+" elements.");for(var r=0;r<t;++r){var i=e[r];if(!tf_layers_esm_isInteger(i))throw new tf_layers_esm_ValueError("The "+n+" argument must be an integer or tuple of "+t+" integers. Received: "+JSON.stringify(e)+" including a non-integer number "+i)}return e}function tf_layers_esm_convOutputLength(e,t,n,r,i){return void 0===i&&(i=1),null==e?e:(a="same"===n?e:e-(t+(t-1)*(i-1))+1,Math.floor((a+r-1)/r));var a}function tf_layers_esm_deconvLength(e,t,n,r){if(null==e)return null;if("valid"===r)e=e*t+tf_layers_esm_max$1([n-t,0]);else{if("same"!==r)throw new tf_layers_esm_ValueError("Unsupport padding mode: "+r+".");e*=t}return e}function tf_layers_esm_preprocessConv2DInput(e,t){return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_checkDataFormat(t),"channelsFirst"===t?Object(tf_core_esm["transpose"])(e,[0,2,3,1]):e})}function tf_layers_esm_preprocessConv3DInput(e,t){return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_checkDataFormat(t),"channelsFirst"===t?Object(tf_core_esm["transpose"])(e,[0,2,3,4,1]):e})}function tf_layers_esm_conv1dWithBias(e,t,n,r,i,a,o){return void 0===r&&(r=1),void 0===i&&(i="valid"),void 0===o&&(o=1),Object(tf_core_esm["tidy"])(function(){if(null==a&&(a=tf_layers_esm_imageDataFormat()),tf_layers_esm_checkDataFormat(a),3!==e.shape.length)throw new tf_layers_esm_ValueError("The input of a conv1dWithBias operation should be 3, but is "+e.shape.length+" instead.");if(3!==t.shape.length)throw new tf_layers_esm_ValueError("The kernel for a conv1dWithBias operation should be 3, but is "+t.shape.length+" instead");if(null!=n&&1!==n.shape.length)throw new tf_layers_esm_ValueError("The bias for a conv1dWithBias operation should be 1, but is "+t.shape.length+" instead");if("channelsFirst"===a&&(e=Object(tf_core_esm["transpose"])(e,[0,2,1])),"causal"===i)throw new tf_layers_esm_NotImplementedError("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var s=Object(tf_core_esm["conv1d"])(e,t,r,"same"===i?"same":"valid","NWC",o);return null!=n&&(s=tf_layers_esm_biasAdd(s,n)),s})}function tf_layers_esm_conv2dWithBiasActivation(e,t,n,r,i,a,o,s){return void 0===r&&(r=[1,1]),void 0===i&&(i="valid"),void 0===s&&(s=null),Object(tf_core_esm["tidy"])(function(){if(null==a&&(a=tf_layers_esm_imageDataFormat()),tf_layers_esm_checkDataFormat(a),3!==e.rank&&4!==e.rank)throw new tf_layers_esm_ValueError("conv2dWithBiasActivation expects input to be of rank 3 or 4, but received "+e.rank+".");if(3!==t.rank&&4!==t.rank)throw new tf_layers_esm_ValueError("conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received "+e.rank+".");var l=tf_layers_esm_preprocessConv2DInput(e,a);if("causal"===i)throw new tf_layers_esm_NotImplementedError("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=tf_core_esm["fused"].conv2d({x:l,filter:t,strides:r,pad:"same"===i?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:s}),"channelsFirst"===a&&(l=Object(tf_core_esm["transpose"])(l,[0,3,1,2])),l})}function tf_layers_esm_conv3dWithBias(e,t,n,r,i,a,o){return void 0===r&&(r=[1,1,1]),void 0===i&&(i="valid"),Object(tf_core_esm["tidy"])(function(){if(null==a&&(a=tf_layers_esm_imageDataFormat()),tf_layers_esm_checkDataFormat(a),4!==e.rank&&5!==e.rank)throw new tf_layers_esm_ValueError("conv3dWithBias expects input to be of rank 4 or 5, but received "+e.rank+".");if(4!==t.rank&&5!==t.rank)throw new tf_layers_esm_ValueError("conv3dWithBias expects kernel to be of rank 4 or 5, but received "+e.rank+".");var s=tf_layers_esm_preprocessConv3DInput(e,a);if("causal"===i)throw new tf_layers_esm_NotImplementedError("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return s=Object(tf_core_esm["conv3d"])(s,t,r,"same"===i?"same":"valid","NDHWC",o),null!=n&&(s=tf_layers_esm_biasAdd(s,n)),"channelsFirst"===a&&(s=Object(tf_core_esm["transpose"])(s,[0,4,1,2,3])),s})}tf_core_esm["serialization"].registerClass(tf_layers_esm_Softmax$1);var tf_layers_esm_BaseConv=function(e){function t(n,r){var i=e.call(this,r)||this;if(i.bias=null,i.DEFAULT_KERNEL_INITIALIZER="glorotNormal",i.DEFAULT_BIAS_INITIALIZER="zeros",t.verifyArgs(r),i.rank=n,tf_layers_esm_assertPositiveInteger(i.rank,"rank"),1!==i.rank&&2!==i.rank&&3!==i.rank)throw new tf_layers_esm_NotImplementedError("Convolution layer for rank other than 1, 2, or 3 ("+i.rank+") is not implemented yet.");if(i.kernelSize=tf_layers_esm_normalizeArray(r.kernelSize,n,"kernelSize"),i.strides=tf_layers_esm_normalizeArray(null==r.strides?1:r.strides,n,"strides"),i.padding=null==r.padding?"valid":r.padding,tf_layers_esm_checkPaddingMode(i.padding),i.dataFormat=null==r.dataFormat?"channelsLast":r.dataFormat,tf_layers_esm_checkDataFormat(i.dataFormat),i.activation=tf_layers_esm_getActivation(r.activation),i.useBias=null==r.useBias||r.useBias,i.biasInitializer=tf_layers_esm_getInitializer(r.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.biasConstraint=tf_layers_esm_getConstraint(r.biasConstraint),i.biasRegularizer=tf_layers_esm_getRegularizer(r.biasRegularizer),i.activityRegularizer=tf_layers_esm_getRegularizer(r.activityRegularizer),i.dilationRate=tf_layers_esm_normalizeArray(null==r.dilationRate?1:r.dilationRate,n,"dilationRate"),1===i.rank&&Array.isArray(i.dilationRate)&&1!==i.dilationRate.length)throw new tf_layers_esm_ValueError("dilationRate must be a number or an array of a single number for 1D convolution, but received "+JSON.stringify(i.dilationRate));if(2===i.rank){if("number"==typeof i.dilationRate)i.dilationRate=[i.dilationRate,i.dilationRate];else if(2!==i.dilationRate.length)throw new tf_layers_esm_ValueError("dilationRate must be a number or array of two numbers for 2D convolution, but received "+JSON.stringify(i.dilationRate))}else if(3===i.rank)if("number"==typeof i.dilationRate)i.dilationRate=[i.dilationRate,i.dilationRate,i.dilationRate];else if(3!==i.dilationRate.length)throw new tf_layers_esm_ValueError("dilationRate must be a number or array of three numbers for 3D convolution, but received "+JSON.stringify(i.dilationRate));return i}return tf_layers_esm_extends(t,e),t.verifyArgs=function(e){if(tf_layers_esm_assert("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!tf_layers_esm_checkArrayTypeAndLength(e.kernelSize,"number",1,3))throw new tf_layers_esm_ValueError("BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received "+JSON.stringify(e.kernelSize)+".")},t.prototype.getConfig=function(){var t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:tf_layers_esm_serializeActivation(this.activation),useBias:this.useBias,biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(tf_layers_esm_Layer),tf_layers_esm_Conv=function(e){function t(n,r){var i=e.call(this,n,r)||this;return i.kernel=null,t.verifyArgs(r),i.filters=r.filters,tf_layers_esm_assertPositiveInteger(i.filters,"filters"),i.kernelInitializer=tf_layers_esm_getInitializer(r.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.kernelConstraint=tf_layers_esm_getConstraint(r.kernelConstraint),i.kernelRegularizer=tf_layers_esm_getRegularizer(r.kernelRegularizer),i}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t;e=tf_layers_esm_getExactlyOneShape(e);var n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new tf_layers_esm_ValueError("The channel dimension of the input should be defined. Found "+e[n]);var r=e[n],i=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:(t={},t[n]=r,t)}],this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t;e=tf_layers_esm_getExactlyOneTensor(e);var r=null==n.bias?null:n.bias.read(),i=tf_layers_esm_mapActivationToFusedKernel(n.activation.getClassName());if(null!=i&&2===n.rank)t=tf_layers_esm_conv2dWithBiasActivation(e,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate,i);else{if(1===n.rank)t=tf_layers_esm_conv1dWithBias(e,n.kernel.read(),r,n.strides[0],n.padding,n.dataFormat,n.dilationRate[0]);else if(2===n.rank)t=tf_layers_esm_conv2dWithBiasActivation(e,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate);else{if(3!==n.rank)throw new tf_layers_esm_NotImplementedError("convolutions greater than 3D are not implemented yet.");t=tf_layers_esm_conv3dWithBias(e,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate)}null!=n.activation&&(t=n.activation.apply(t))}return t})},t.prototype.computeOutputShape=function(e){e=tf_layers_esm_getExactlyOneShape(e);for(var t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2),r=0;r<n.length;++r){var i=tf_layers_esm_convOutputLength(n[r],this.kernelSize[r],this.padding,this.strides[r],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[r]);t.push(i)}var a=[e[0]];return"channelsLast"===this.dataFormat?(a=a.concat(t)).push(this.filters):(a.push(this.filters),a=a.concat(t)),a},t.prototype.getConfig=function(){var t={filters:this.filters,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.verifyArgs=function(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new tf_layers_esm_ValueError("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(e.filters))},t}(tf_layers_esm_BaseConv),tf_layers_esm_Conv2D=function(e){function t(n){var r=e.call(this,2,n)||this;return t.verifyArgs(n),r}return tf_layers_esm_extends(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyArgs=function(e){if("number"!=typeof e.kernelSize&&!tf_layers_esm_checkArrayTypeAndLength(e.kernelSize,"number",1,2))throw new tf_layers_esm_ValueError("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv2D",t}(tf_layers_esm_Conv);tf_core_esm["serialization"].registerClass(tf_layers_esm_Conv2D);var tf_layers_esm_Conv3D=function(e){function t(n){var r=e.call(this,3,n)||this;return t.verifyArgs(n),r}return tf_layers_esm_extends(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyArgs=function(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new tf_layers_esm_ValueError("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv3D",t}(tf_layers_esm_Conv);tf_core_esm["serialization"].registerClass(tf_layers_esm_Conv3D);var tf_layers_esm_Conv2DTranspose=function(e){function t(t){var n=e.call(this,t)||this;if(n.inputSpec=[new tf_layers_esm_InputSpec({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new tf_layers_esm_ValueError("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t;if(4!==(e=tf_layers_esm_getExactlyOneShape(e)).length)throw new tf_layers_esm_ValueError("Input should have rank 4; Received input shape: "+JSON.stringify(e));var n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new tf_layers_esm_ValueError("The channel dimension of the inputs should be defined. Found `None`.");var r=e[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 tf_layers_esm_InputSpec({ndim:4,axes:(t={},t[n]=r,t)})],this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_getExactlyOneTensor(e);if(4!==t.shape.length)throw new tf_layers_esm_ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var r,i,a=t.shape,o=a[0];"channelsFirst"===n.dataFormat?(r=2,i=3):(r=1,i=2);var s=a[r],l=a[i],u=n.kernelSize[0],c=n.kernelSize[1],p=n.strides[0],h=n.strides[1],d=[o,tf_layers_esm_deconvLength(s,p,u,n.padding),tf_layers_esm_deconvLength(l,h,c,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(t=Object(tf_core_esm["transpose"])(t,[0,2,3,1]));var f=Object(tf_core_esm["conv2dTranspose"])(t,n.kernel.read(),d,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(f=Object(tf_core_esm["transpose"])(f,[0,3,1,2])),null!=n.bias&&(f=tf_layers_esm_biasAdd(f,n.bias.read(),n.dataFormat)),null!=n.activation&&(f=n.activation.apply(f)),f})},t.prototype.computeOutputShape=function(e){var t,n,r,i=(e=tf_layers_esm_getExactlyOneShape(e)).slice();"channelsFirst"===this.dataFormat?(t=1,n=2,r=3):(t=3,n=1,r=2);var a=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],l=this.strides[1];return i[t]=this.filters,i[n]=tf_layers_esm_deconvLength(i[n],s,a,this.padding),i[r]=tf_layers_esm_deconvLength(i[r],l,o,this.padding),i},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},t.className="Conv2DTranspose",t}(tf_layers_esm_Conv2D);tf_core_esm["serialization"].registerClass(tf_layers_esm_Conv2DTranspose);var tf_layers_esm_SeparableConv=function(e){function t(t,n){var r=e.call(this,t,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new tf_layers_esm_ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new tf_layers_esm_ValueError("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 tf_layers_esm_ValueError("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=tf_layers_esm_getInitializer(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=tf_layers_esm_getRegularizer(n.depthwiseRegularizer),r.depthwiseConstraint=tf_layers_esm_getConstraint(n.depthwiseConstraint),r.pointwiseInitializer=tf_layers_esm_getInitializer(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=tf_layers_esm_getRegularizer(n.pointwiseRegularizer),r.pointwiseConstraint=tf_layers_esm_getConstraint(n.pointwiseConstraint),r}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t;if((e=tf_layers_esm_getExactlyOneShape(e)).length<this.rank+2)throw new tf_layers_esm_ValueError("Inputs to SeparableConv"+this.rank+"D should have rank "+(this.rank+2)+", but received input shape: "+JSON.stringify(e));var n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n]||e[n]<0)throw new tf_layers_esm_ValueError("The channel dimension of the inputs should be defined, but found "+JSON.stringify(e[n]));for(var r=e[n],i=this.kernelSize.concat([r,this.depthMultiplier]),a=[],o=0;o<this.rank;++o)a.push(1);a.push(r*this.depthMultiplier,this.filters);this.depthwiseKernel=this.addWeight("depthwise_kernel",i,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,!0,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.inputSpec=[new tf_layers_esm_InputSpec({ndim:this.rank+2,axes:(t={},t[n]=r,t)})],this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t;if(e=tf_layers_esm_getExactlyOneTensor(e),1===n.rank)throw new tf_layers_esm_NotImplementedError("1D separable convolution is not implemented yet.");return 2===n.rank&&("channelsFirst"===n.dataFormat&&(e=Object(tf_core_esm["transpose"])(e,[0,2,3,1])),t=Object(tf_core_esm["separableConv2d"])(e,n.depthwiseKernel.read(),n.pointwiseKernel.read(),n.strides,n.padding,n.dilationRate,"NHWC")),n.useBias&&(t=tf_layers_esm_biasAdd(t,n.bias.read(),n.dataFormat)),null!=n.activation&&(t=n.activation.apply(t)),"channelsFirst"===n.dataFormat&&(t=Object(tf_core_esm["transpose"])(t,[0,3,1,2])),t})},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=tf_layers_esm_serializeInitializer(this.depthwiseInitializer),t.pointwiseInitializer=tf_layers_esm_serializeInitializer(this.pointwiseInitializer),t.depthwiseRegularizer=tf_layers_esm_serializeRegularizer(this.depthwiseRegularizer),t.pointwiseRegularizer=tf_layers_esm_serializeRegularizer(this.pointwiseRegularizer),t.depthwiseConstraint=tf_layers_esm_serializeConstraint(this.depthwiseConstraint),t.pointwiseConstraint=tf_layers_esm_serializeConstraint(this.pointwiseConstraint),t},t.className="SeparableConv",t}(tf_layers_esm_Conv),tf_layers_esm_SeparableConv2D=function(e){function t(t){return e.call(this,2,t)||this}return tf_layers_esm_extends(t,e),t.className="SeparableConv2D",t}(tf_layers_esm_SeparableConv);tf_core_esm["serialization"].registerClass(tf_layers_esm_SeparableConv2D);var tf_layers_esm_Conv1D=function(e){function t(n){var r=e.call(this,1,n)||this;return t.verifyArgs(n),r.inputSpec=[{ndim:3}],r}return tf_layers_esm_extends(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,delete t.dataFormat,t},t.verifyArgs=function(e){if("number"!=typeof e.kernelSize&&!tf_layers_esm_checkArrayTypeAndLength(e.kernelSize,"number",1,1))throw new tf_layers_esm_ValueError("Conv1D expects config.kernelSize to be number or number[] with length 1, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv1D",t}(tf_layers_esm_Conv);tf_core_esm["serialization"].registerClass(tf_layers_esm_Conv1D);var tf_layers_esm_Cropping2D=function(e){function t(t){var n=e.call(this,t)||this;return"number"==typeof t.cropping?n.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:"number"==typeof t.cropping[0]?n.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:n.cropping=t.cropping,n.dataFormat=void 0===t.dataFormat?"channelsLast":t.dataFormat,n.inputSpec=[{ndim:4}],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return e=tf_layers_esm_getExactlyOneTensor(e),"channelsLast"===n.dataFormat?tf_layers_esm_sliceAlongAxis(tf_layers_esm_sliceAlongAxis(e,n.cropping[0][0],e.shape[1]-n.cropping[0][0]-n.cropping[0][1],2),n.cropping[1][0],e.shape[2]-n.cropping[1][1]-n.cropping[1][0],3):tf_layers_esm_sliceAlongAxis(tf_layers_esm_sliceAlongAxis(e,n.cropping[0][0],e.shape[2]-n.cropping[0][0]-n.cropping[0][1],3),n.cropping[1][0],e.shape[3]-n.cropping[1][1]-n.cropping[1][0],4)})},t.prototype.getConfig=function(){var t={cropping:this.cropping,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Cropping2D",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Cropping2D);var tf_layers_esm_UpSampling2D=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_SIZE=[2,2],n.inputSpec=[{ndim:4}],n.size=null==t.size?n.DEFAULT_SIZE:t.size,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){if("channelsFirst"===this.dataFormat){var t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_getExactlyOneTensor(e),r=t.shape;if("channelsFirst"===n.dataFormat){t=Object(tf_core_esm["transpose"])(t,[0,2,3,1]);var i=n.size[0]*r[2],a=n.size[1]*r[3],o=t.resizeNearestNeighbor([i,a]);return Object(tf_core_esm["transpose"])(o,[0,3,1,2])}i=n.size[0]*r[1],a=n.size[1]*r[2];return t.resizeNearestNeighbor([i,a])})},t.prototype.getConfig=function(){var t={size:this.size,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="UpSampling2D",t}(tf_layers_esm_Layer);function tf_layers_esm_depthwiseConv2d$1(e,t,n,r,i,a){return void 0===n&&(n=[1,1]),void 0===r&&(r="valid"),Object(tf_core_esm["tidy"])(function(){null==i&&(i=tf_layers_esm_imageDataFormat()),tf_layers_esm_checkDataFormat(i);var o=tf_layers_esm_preprocessConv2DInput(e,i);if(4!==e.rank)throw new tf_layers_esm_ValueError("Input for depthwiseConv2d is required to be 4-D, but is instead "+e.rank+"-D");if(4!==t.rank)throw new tf_layers_esm_ValueError("depthwiseKernel is required to be 4-D, but is instead "+t.rank+"-D");return o=Object(tf_core_esm["depthwiseConv2d"])(o,t,n,"same"===r?"same":"valid","NHWC",a),"channelsFirst"===i&&(o=Object(tf_core_esm["transpose"])(o,[0,3,1,2])),o})}tf_core_esm["serialization"].registerClass(tf_layers_esm_UpSampling2D);var tf_layers_esm_DepthwiseConv2D=function(e){function t(t){var n=e.call(this,2,t)||this;return n.depthwiseKernel=null,n.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,n.depthwiseInitializer=tf_layers_esm_getInitializer(t.depthwiseInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.depthwiseConstraint=tf_layers_esm_getConstraint(t.depthwiseConstraint),n.depthwiseRegularizer=tf_layers_esm_getRegularizer(t.depthwiseRegularizer),n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){if((e=tf_layers_esm_getExactlyOneShape(e)).length<4)throw new tf_layers_esm_ValueError("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(e)+".");var t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new tf_layers_esm_ValueError("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+e[t]+").");var n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_depthwiseConv2d$1(e=tf_layers_esm_getExactlyOneTensor(e),n.depthwiseKernel.read(),n.strides,n.padding,n.dataFormat,null);return n.useBias&&(t=tf_layers_esm_biasAdd(t,n.bias.read(),n.dataFormat)),null!=n.activation&&(t=n.activation.apply(t)),t})},t.prototype.computeOutputShape=function(e){e=tf_layers_esm_getExactlyOneShape(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,i=tf_layers_esm_convOutputLength(t,this.kernelSize[0],this.padding,this.strides[0]),a=tf_layers_esm_convOutputLength(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],r,i,a]:[e[0],i,a,r]},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return t.depthMultiplier=this.depthMultiplier,t.depthwiseInitializer=tf_layers_esm_serializeInitializer(this.depthwiseInitializer),t.depthwiseRegularizer=tf_layers_esm_serializeRegularizer(this.depthwiseRegularizer),t.depthwiseConstraint=tf_layers_esm_serializeConstraint(this.depthwiseRegularizer),t},t.className="DepthwiseConv2D",t}(tf_layers_esm_BaseConv);tf_core_esm["serialization"].registerClass(tf_layers_esm_DepthwiseConv2D);var tf_layers_esm_Dropout=function(e){function t(t){var n=e.call(this,t)||this;return n.rate=Math.max(Math.min(t.rate,1),0),n.noiseShape=t.noiseShape,n.seed=t.seed,n.supportsMasking=!0,n}return tf_layers_esm_extends(t,e),t.prototype.getNoiseShape=function(e){if(null==this.noiseShape)return this.noiseShape;for(var t=e.shape,n=[],r=0;r<this.noiseShape.length;++r)n.push(null==this.noiseShape[r]?t[r]:this.noiseShape[r]);return n},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e);if(0<n.rate&&n.rate<1){var i=null!=t.training&&t.training,a=n.getNoiseShape(r);return tf_layers_esm_inTrainPhase(function(){return tf_layers_esm_dropout$1(r,n.rate,a,n.seed)},function(){return r},i)}return e})},t.prototype.getConfig=function(){var t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.prototype.dispose=function(){return e.prototype.dispose.call(this)},t.className="Dropout",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Dropout);var tf_layers_esm_SpatialDropout1D=function(e){function t(t){var n=e.call(this,t)||this;return n.inputSpec=[{ndim:3}],n}return tf_layers_esm_extends(t,e),t.prototype.getNoiseShape=function(e){var t=e.shape;return[t[0],1,t[2]]},t.className="SpatialDropout1D",t}(tf_layers_esm_Dropout);tf_core_esm["serialization"].registerClass(tf_layers_esm_SpatialDropout1D);var tf_layers_esm_Dense=function(e){function t(t){var n=e.call(this,t)||this;if(n.activation=null,n.useBias=!0,n.kernel=null,n.bias=null,n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_BIAS_INITIALIZER="zeros",null==t.batchInputShape&&null==t.inputShape&&null!=t.inputDim){var r=null;null!=t.batchSize&&(r=t.batchSize),n.batchInputShape=[r,t.inputDim]}return n.units=t.units,tf_layers_esm_assertPositiveInteger(n.units,"units"),n.activation=tf_layers_esm_getActivation(t.activation),null!=t.useBias&&(n.useBias=t.useBias),n.kernelInitializer=tf_layers_esm_getInitializer(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.biasInitializer=tf_layers_esm_getInitializer(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelConstraint=tf_layers_esm_getConstraint(t.kernelConstraint),n.biasConstraint=tf_layers_esm_getConstraint(t.biasConstraint),n.kernelRegularizer=tf_layers_esm_getRegularizer(t.kernelRegularizer),n.biasRegularizer=tf_layers_esm_getRegularizer(t.biasRegularizer),n.activityRegularizer=tf_layers_esm_getRegularizer(t.activityRegularizer),n.supportsMasking=!0,n.inputSpec=[{minNDim:2}],n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t,n=(e=tf_layers_esm_getExactlyOneShape(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[n,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:(t={},t[-1]=n,t)}],this.built=!0},t.prototype.computeOutputShape=function(e){var t=(e=tf_layers_esm_getExactlyOneShape(e)).slice();return t[t.length-1]=this.units,t},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r,i=tf_layers_esm_getExactlyOneTensor(e),a=tf_layers_esm_mapActivationToFusedKernel(n.activation.getClassName());return null!=a?r=tf_layers_esm_dot(i,n.kernel.read(),a,n.bias?n.bias.read():null):(r=tf_layers_esm_dot(i,n.kernel.read()),null!=n.bias&&(r=tf_layers_esm_biasAdd(r,n.bias.read())),null!=n.activation&&(r=n.activation.apply(r))),r})},t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Dense",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Dense);var tf_layers_esm_Flatten=function(e){function t(t){var n=this;return t=t||{},(n=e.call(this,t)||this).inputSpec=[{minNDim:3}],n.dataFormat=t.dataFormat,n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){for(var t=0,n=(e=tf_layers_esm_getExactlyOneShape(e)).slice(1);t<n.length;t++){if(null==n[t])throw new tf_layers_esm_ValueError('The shape of the input to "Flatten" is not fully defined (got '+e.slice(1)+'). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.')}return[e[0],tf_layers_esm_arrayProd(e,1)]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e);if("channelsFirst"===n.dataFormat&&r.rank>1){for(var i=[0],a=2;a<r.rank;++a)i.push(a);i.push(1),r=r.transpose(i)}return tf_layers_esm_batchFlatten(r)})},t.prototype.getConfig=function(){var t={};null!=this.dataFormat&&(t.dataFormat=this.dataFormat);var n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Flatten",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Flatten);var tf_layers_esm_Activation$1=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.activation=tf_layers_esm_getActivation(t.activation),n}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e);return n.activation.apply(r)})},t.prototype.getConfig=function(){var t={activation:tf_layers_esm_serializeActivation(this.activation)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Activation",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Activation$1);var tf_layers_esm_RepeatVector=function(e){function t(t){var n=e.call(this,t)||this;return n.n=t.n,n.inputSpec=[{ndim:2}],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return[e[0],this.n,e[1]]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_repeat(e=tf_layers_esm_getExactlyOneTensor(e),n.n)})},t.prototype.getConfig=function(){var t={n:this.n},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="RepeatVector",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_RepeatVector);var tf_layers_esm_Reshape=function(e){function t(t){var n=e.call(this,t)||this;n.targetShape=t.targetShape;for(var r=0;r<n.targetShape.length;++r)n.isUnknown(n.targetShape[r])&&(n.targetShape[r]=null);return n}return tf_layers_esm_extends(t,e),t.prototype.isUnknown=function(e){return e<0||null==e},t.prototype.fixUnknownDimension=function(e,t){for(var n="Total size of new array must be unchanged.",r=t.slice(),i=1,a=null,o=0;o<r.length;++o){var s=r[o];if(this.isUnknown(s)){if(null!==a)throw new tf_layers_esm_ValueError("Can only specifiy one unknown dimension.");a=o}else i*=s}var l=tf_layers_esm_arrayProd(e);if(null!==a){if(0===i||l%i!=0)throw new tf_layers_esm_ValueError(n);r[a]=l/i}else if(l!==i)throw new tf_layers_esm_ValueError(n);return r},t.prototype.computeOutputShape=function(e){for(var t=!1,n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e),i=r.shape,a=i.slice(0,1).concat(n.fixUnknownDimension(i.slice(1),n.targetShape));return r.reshape(a)})},t.prototype.getConfig=function(){var t={targetShape:this.targetShape},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Reshape",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Reshape);var tf_layers_esm_Permute=function(e){function t(t){var n=e.call(this,t)||this;if(null==t.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(t.dims))throw new Error("Permute constructor requires `dims` to be an Array, but received "+t.dims+" instead.");var r=tf_layers_esm_range(1,t.dims.length+1);if(!tf_core_esm["util"].arraysEqual(t.dims.slice().sort(),r))throw new Error("Invalid permutation `dims`: "+JSON.stringify(t.dims)+" `dims` must contain consecutive integers starting from 1.");return n.dims=t.dims,n.dimsIncludingBatch=[0].concat(n.dims),n.inputSpec=[new tf_layers_esm_InputSpec({ndim:n.dims.length+1})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){var t=(e=tf_layers_esm_getExactlyOneShape(e)).slice();return this.dims.forEach(function(n,r){t[r+1]=e[n]}),t},t.prototype.call=function(e,t){return Object(tf_core_esm["transpose"])(tf_layers_esm_getExactlyOneTensor(e),this.dimsIncludingBatch)},t.prototype.getConfig=function(){var t={dims:this.dims},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Permute",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Permute);var tf_layers_esm_Masking=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.supportsMasking=!0,n.maskValue=null!=t?null==t.maskValue?0:t.maskValue:0,n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={maskValue:this.maskValue};return Object.assign(n,t),n},t.prototype.computeMask=function(e,t){var n=tf_layers_esm_getExactlyOneTensor(e);return Object(tf_core_esm["any"])(Object(tf_core_esm["notEqual"])(n,this.maskValue),-1)},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e),i=Object(tf_core_esm["any"])(Object(tf_core_esm["notEqual"])(r,n.maskValue),-1,!0);return r.mul(i.asType(r.dtype))})},t.className="Masking",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Masking);var tf_layers_esm_Embedding=function(e){function t(t){var n=e.call(this,t)||this;if(n.embeddings=null,n.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==t.batchInputShape&&null==t.inputShape){var r=null;null!=t.batchSize&&(r=t.batchSize),null==t.inputLength?n.batchInputShape=[r,null]:n.batchInputShape=[r].concat(tf_layers_esm_toList(t.inputLength))}return n.inputDim=t.inputDim,tf_layers_esm_assertPositiveInteger(n.inputDim,"inputDim"),n.outputDim=t.outputDim,tf_layers_esm_assertPositiveInteger(n.outputDim,"outputDim"),n.embeddingsInitializer=tf_layers_esm_getInitializer(t.embeddingsInitializer||n.DEFAULT_EMBEDDINGS_INITIALIZER),n.embeddingsRegularizer=tf_layers_esm_getRegularizer(t.embeddingsRegularizer),n.activityRegularizer=tf_layers_esm_getRegularizer(t.activityRegularizer),n.embeddingsConstraint=tf_layers_esm_getConstraint(t.embeddingsConstraint),n.maskZero=t.maskZero,n.supportsMasking=t.maskZero,n.inputLength=t.inputLength,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0},t.prototype.warnOnIncompatibleInputShape=function(e){},t.prototype.computeMask=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return n.maskZero?(e=tf_layers_esm_getExactlyOneTensor(e),Object(tf_core_esm["notEqual"])(e,Object(tf_core_esm["zerosLike"])(e))):null})},t.prototype.computeOutputShape=function(e){if(e=tf_layers_esm_getExactlyOneShape(e),null==this.inputLength)return e.concat([this.outputDim]);var t=tf_layers_esm_toList(this.inputLength);if(t.length!==e.length-1)throw new tf_layers_esm_ValueError('"inputLength" is '+this.inputLength+", but received input shape has shape "+e);for(var n=0,r=0;r<t.length;++r){var i=t[r],a=e[r+1];if(null!=i&&null!=a&&i!==a)throw new tf_layers_esm_ValueError('"inputLength" is '+this.inputLength+", but received input shape has shape "+e);null==i&&(t[n]=a),n++}return[e[0]].concat(t,[this.outputDim])},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e);return"int32"!==r.dtype&&(r=tf_layers_esm_cast$1(r,"int32")),tf_layers_esm_gather$1(n.embeddings.read(),r.as1D()).reshape(tf_layers_esm_getExactlyOneShape(n.computeOutputShape(r.shape)))})},t.prototype.getConfig=function(){var t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:tf_layers_esm_serializeInitializer(this.embeddingsInitializer),embeddingsRegularizer:tf_layers_esm_serializeRegularizer(this.embeddingsRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),embeddingsConstraint:tf_layers_esm_serializeConstraint(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Embedding",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_Embedding);var tf_layers_esm_Merge=function(e){function t(t){var n=e.call(this,t||{})||this;return n.supportsMasking=!0,n}return tf_layers_esm_extends(t,e),t.prototype.mergeFunction=function(e){throw new tf_layers_esm_NotImplementedError},t.prototype.computeElementwiseOpOutputShape=function(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;for(var n=e.slice(0,e.length-t.length),r=0;r<t.length;++r){var i=e[e.length-t.length+r],a=t[r];if(null==i||null==a||i<0||a<0)n.push(null);else if(1===i)n.push(a);else if(1===a)n.push(i);else{if(i!==a)throw new tf_layers_esm_ValueError("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(i)}}return n},t.prototype.build=function(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[tf_layers_esm_getExactlyOneShape(e)]),(e=e).length<2)throw new tf_layers_esm_ValueError("A merge layer should be called on an Array of at least 2 inputs. Got "+e.length+" input(s).");for(var t=[],n=0,r=e;n<r.length;n++){null!=(o=r[n])&&null!==o[0]&&t.push(o[0])}if((t=tf_layers_esm_unique(t)).length>1)throw new tf_layers_esm_ValueError("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var i=null==e[0]?null:e[0].slice(1),a=1;a<e.length;++a){var o=null==e[a]?null:e[a].slice(1);i=this.computeElementwiseOpOutputShape(i,o)}var s=e.map(function(e){return e.length});-1===e.indexOf(null)&&1===tf_layers_esm_unique(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){if(e=e,n.reshapeRequired){var t=[],r=e.map(function(e){return e.rank});if(-1===r.indexOf(null)){for(var i=tf_layers_esm_max$1(r),a=0,o=e;a<o.length;a++){for(var s=(h=o[a]).rank,l=0;l<i-s;++l)h=tf_layers_esm_expandDims$1(h,1);t.push(h)}return n.mergeFunction(t)}for(var u=!1,c=0,p=e;c<p.length;c++){var h;if(null==(s=(h=p[c]).rank)){var d=h.shape,f=d[0],g=d.slice(1).concat([f]),m=h.reshape([f].concat(tf_layers_esm_arrayProd(d.slice(1))));m=(m=Object(tf_core_esm["transpose"])(m,[1,0])).reshape(g),t.push(m),u=!0}else if(s>1){var y=tf_layers_esm_range(1,s).concat([0]);t.push(Object(tf_core_esm["transpose"])(h,y)),u=!0}else t.push(h)}var v=n.mergeFunction(t),b=v.rank;if(u)if(null==b){var w=v.shape;g=[f=w[w.length-1]].concat(w.slice(0,w.length-1));v=Object(tf_core_esm["transpose"])(v.reshape([-1,f]),[1,0]).reshape(g)}else if(b>1){y=[b-1].concat(tf_layers_esm_range(0,b-1));v=Object(tf_core_esm["transpose"])(v,y)}return v}return n.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var n=1;n<e.length;++n){var r=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,r)}for(var i=[],a=0,o=e;a<o.length;a++){null!=(r=o[a])&&null!==r[0]&&i.push(r[0])}return t=1===(i=tf_layers_esm_unique(i)).length?i.concat(t):[null].concat(t)},t.prototype.computeMask=function(e,t){return Object(tf_core_esm["tidy"])(function(){if(null==t)return null;if(!Array.isArray(t))throw new tf_layers_esm_ValueError("`mask` should be an Array");if(!Array.isArray(e))throw new tf_layers_esm_ValueError("`inputs` should be an Array");if(t.length!==e.length)throw new tf_layers_esm_ValueError("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths ("+e.length+" vs "+t.length+")");if(t.every(function(e){return null==e}))return null;for(var n=(t=t.map(function(e){return null==e?e:Object(tf_core_esm["expandDims"])(e,0)}))[0],r=1;r<t.length-1;++r)n=Object(tf_core_esm["logicalAnd"])(n,t[r]);return n})},t}(tf_layers_esm_Layer),tf_layers_esm_Add=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.mergeFunction=function(e){return Object(tf_core_esm["tidy"])(function(){for(var t=e[0].clone(),n=1;n<e.length;++n)t=Object(tf_core_esm["add"])(t,e[n]);return t})},t.className="Add",t}(tf_layers_esm_Merge);tf_core_esm["serialization"].registerClass(tf_layers_esm_Add);var tf_layers_esm_Multiply=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.mergeFunction=function(e){return Object(tf_core_esm["tidy"])(function(){for(var t=e[0].clone(),n=1;n<e.length;++n)t=Object(tf_core_esm["mul"])(t,e[n]);return t})},t.className="Multiply",t}(tf_layers_esm_Merge);tf_core_esm["serialization"].registerClass(tf_layers_esm_Multiply);var tf_layers_esm_Average=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.mergeFunction=function(e){return Object(tf_core_esm["tidy"])(function(){for(var t=e[0].clone(),n=1;n<e.length;++n)t=Object(tf_core_esm["add"])(t,e[n]);return Object(tf_core_esm["mul"])(1/e.length,t)})},t.className="Average",t}(tf_layers_esm_Merge);tf_core_esm["serialization"].registerClass(tf_layers_esm_Average);var tf_layers_esm_Maximum=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.mergeFunction=function(e){return Object(tf_core_esm["tidy"])(function(){for(var t=e[0],n=1;n<e.length;++n)t=Object(tf_core_esm["maximum"])(t,e[n]);return t})},t.className="Maximum",t}(tf_layers_esm_Merge);tf_core_esm["serialization"].registerClass(tf_layers_esm_Maximum);var tf_layers_esm_Minimum=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.mergeFunction=function(e){return Object(tf_core_esm["tidy"])(function(){for(var t=e[0],n=1;n<e.length;++n)t=Object(tf_core_esm["minimum"])(t,e[n]);return t})},t.className="Minimum",t}(tf_layers_esm_Merge);tf_core_esm["serialization"].registerClass(tf_layers_esm_Minimum);var tf_layers_esm_Concatenate=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_AXIS=-1,null==t&&(t={}),n.axis=null==t.axis?n.DEFAULT_AXIS:t.axis,n.supportsMasking=!0,n.reshapeRequired=!1,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new tf_layers_esm_ValueError("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var t=!0,n=0,r=e=e;n<r.length;n++){if(null!=(c=r[n])){t=!1;break}}if(!t){for(var i=[],a=0;a<e.length;++a){var o=e[a].slice();o.splice(this.axis,1);for(var s=!1,l=0,u=i;l<u.length;l++){var c=u[l];if(tf_core_esm["util"].arraysEqual(c,o)){s=!0;break}}s||i.push(o)}if(i.length>1)throw new tf_layers_esm_ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},t.prototype.mergeFunction=function(e){var t=this;return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_concatenate(e,t.axis)})},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new tf_layers_esm_ValueError("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,i=0,a=t.slice(1);i<a.length;i++){var o=a[i];if(null==n[r]||null==o[r]){n[r]=null;break}n[r]+=o[r]}return n},t.prototype.computeMask=function(e,t){var n=this;if(null==t)return null;if(!Array.isArray(t))throw new tf_layers_esm_ValueError("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new tf_layers_esm_ValueError("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new tf_layers_esm_ValueError("Mismatch in the length of mask ("+t.length+") and the legnth of inputs ("+e.length+")");return Object(tf_core_esm["tidy"])(function(){var r=!0;if(t.forEach(function(e){null==e||(r=!1)}),r)return null;for(var i=[],a=0;a<e.length;++a)null==t[a]?i.push(Object(tf_core_esm["onesLike"])(e[a]).asType("bool")):t[a].rank<e[a].rank?i.push(Object(tf_core_esm["expandDims"])(t[a],-1)):i.push(t[a]);var o=Object(tf_core_esm["concat"])(i,n.axis);return Object(tf_core_esm["all"])(o,-1,!1)})},t.prototype.getConfig=function(){var t={axis:this.axis},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Concatenate",t}(tf_layers_esm_Merge);function tf_layers_esm_interpretAxis(e,t){for(;e<0;)e+=t;return e}function tf_layers_esm_batchDot(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new tf_layers_esm_NotImplementedError("batchDot is not implemented for tensors of 4D or higher rank yet");if(tf_core_esm["util"].assert(e.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, but got "+e.shape.length}),tf_core_esm["util"].assert(e.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, but got "+t.shape.length}),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new tf_layers_esm_NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.");var r=e.shape.length,i=t.shape.length;null==n&&(n=[r-1,i-2]);var a=n;return Object(tf_core_esm["tidy"])(function(){var n,o;if(r>i){n=r-i;for(var s=[],l=0;l<n;++l)s.push(1);t=t.reshape(t.shape.concat(s))}else if(i>r){n=i-r;for(s=[],l=0;l<n;++l)s.push(1);e=e.reshape(e.shape.concat(s))}else n=0;if(2===e.shape.length&&2===t.shape.length)o=a[0]===a[1]?e.mulStrict(t).sum(a[0]):e.transpose([1,0]).mulStrict(t).sum(a[1]);else{var u=a[0]!==e.shape.length-1,c=a[1]===t.shape.length-1;o=e.matMul(t,u,c)}if(n>0){var p=void 0,h=[];for(l=p=r>i?r+i-3:r-1;l<p+n;++l)h.push(l);o=o.squeeze(h)}return 1===o.shape.length&&(o=o.expandDims(1)),o})}tf_core_esm["serialization"].registerClass(tf_layers_esm_Concatenate);var tf_layers_esm_Dot=function(e){function t(t){var n=e.call(this,t)||this;return n.axes=t.axes,n.normalize=null!=t.normalize&&t.normalize,n.supportsMasking=!0,n.reshapeRequired=!1,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){tf_core_esm["util"].assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var t=e[0],n=e[1];if(t.length>3||n.length>3)throw new tf_layers_esm_NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new tf_layers_esm_ValueError("Dimension incompatibility: "+t[r[0]]+" !== "+n[r[1]])},t.prototype.mergeFunction=function(e){if(2!==e.length)throw new tf_layers_esm_ValueError("A `Dot` layer must be called on exactly 2 inputs, but received "+e.length+" input(s).");var t,n=e[0],r=e[1];return t=Array.isArray(this.axes)?this.axes.map(function(t,n){return tf_layers_esm_interpretAxis(t,e[n].shape.length)}):[tf_layers_esm_interpretAxis(this.axes,n.shape.length),tf_layers_esm_interpretAxis(this.axes,r.shape.length)],this.normalize&&(n=tf_layers_esm_l2Normalize(n,t[0]),r=tf_layers_esm_l2Normalize(r,t[1])),tf_layers_esm_batchDot(n,r,t)},t.prototype.interpretAxes=function(e,t){return Array.isArray(this.axes)?this.axes:[tf_layers_esm_interpretAxis(this.axes,e.length),tf_layers_esm_interpretAxis(this.axes,t.length)]},t.prototype.computeOutputShape=function(e){tf_core_esm["util"].assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new tf_layers_esm_NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);var i=t.concat(n);return 1===i.length&&i.push(1),i},t.prototype.computeMask=function(e,t){return null},t.prototype.getConfig=function(){var t={axes:this.axes,normalize:this.normalize},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Dot",t}(tf_layers_esm_Merge);tf_core_esm["serialization"].registerClass(tf_layers_esm_Dot);var tf_layers_esm_GaussianNoise=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.stddev=t.stddev,n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={stddev:this.stddev};return Object.assign(n,t),n},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e);return tf_layers_esm_inTrainPhase(function(){return tf_layers_esm_randomNormal$1(r.shape,0,n.stddev).add(r)},function(){return r},t.training||!1)})},t.className="GaussianNoise",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_GaussianNoise);var tf_layers_esm_GaussianDropout=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.rate=t.rate,n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,t),n},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t);var r=tf_layers_esm_getExactlyOneTensor(e);if(n.rate>0&&n.rate<1){return tf_layers_esm_inTrainPhase(function(){var e=Math.sqrt(n.rate/(1-n.rate));return r.mul(tf_layers_esm_randomNormal$1(r.shape,1,e))},function(){return r},t.training||!1)}return r})},t.className="GaussianDropout",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_GaussianDropout);var tf_layers_esm_AlphaDropout=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.rate=t.rate,n.noiseShape=t.noiseShape,n}return tf_layers_esm_extends(t,e),t.prototype._getNoiseShape=function(e){return this.noiseShape||tf_layers_esm_getExactlyOneTensor(e).shape},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,t),n},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){if(n.rate<1&&n.rate>0){var r=n._getNoiseShape(e);return tf_layers_esm_inTrainPhase(function(){var t=tf_layers_esm_getExactlyOneTensor(e),i=-1.7580993408473766,a=Object(tf_core_esm["greaterEqual"])(Object(tf_core_esm["randomUniform"])(r),n.rate);a=tf_layers_esm_cast$1(a,"float32");var o=Math.pow((1-n.rate)*(1+n.rate*Math.pow(i,2)),-.5),s=-o*i*n.rate;return t.mul(a).add(a.add(-1).mul(i)).mul(o).add(s)},function(){return tf_layers_esm_getExactlyOneTensor(e)},t.training||!1)}return e})},t.className="AlphaDropout",t}(tf_layers_esm_Layer);function tf_layers_esm_batchNormalization(e,t,n,r,i,a){var o;if(void 0===a&&(a=.001),2===e.rank)o=Object(tf_core_esm["batchNorm2d"])(e,t,n,r,i,a);else if(3===e.rank)o=Object(tf_core_esm["batchNorm3d"])(e,t,n,r,i,a);else{if(4!==e.rank)throw new tf_layers_esm_NotImplementedError("batchNormalization is not implemented for array of rank "+e.rank+" yet");o=Object(tf_core_esm["batchNorm4d"])(e,t,n,r,i,a)}return o}function tf_layers_esm_regularNormalizeBatchInTraining(e,t,n,r,i){return void 0===i&&(i=.001),Object(tf_core_esm["tidy"])(function(){var a=Object(tf_core_esm["moments"])(e,r),o=a.mean,s=a.variance;return[tf_layers_esm_batchNormalization(e,o,s,n,t,i),o,s]})}function tf_layers_esm_broadcastNormalizeBatchInTraining(e,t,n,r,i){return void 0===i&&(i=.001),Object(tf_core_esm["tidy"])(function(){for(var a=Object(tf_core_esm["moments"])(e,r),o=a.mean,s=a.variance,l=[],u=0,c=tf_layers_esm_range(0,e.rank);u<c.length;u++){var p=c[u];-1!==r.indexOf(p)?l.push(1):l.push(e.shape[p])}var h=o.reshape(l),d=s.reshape(l),f=null==t?null:t.reshape(l),g=null==n?null:n.reshape(l);return[tf_layers_esm_batchNormalization(e,h,d,g,f,i),o,s]})}function tf_layers_esm_normalizeBatchInTraining(e,t,n,r,i){return void 0===i&&(i=.001),tf_core_esm["util"].arraysEqual(r.slice().sort(),tf_layers_esm_range(0,e.rank-1))?tf_layers_esm_regularNormalizeBatchInTraining(e,t,n,r,i):tf_layers_esm_broadcastNormalizeBatchInTraining(e,t,n,r,i)}tf_core_esm["serialization"].registerClass(tf_layers_esm_AlphaDropout);var tf_layers_esm_BatchNormalization=function(e){function t(t){var n=this;return null==t&&(t={}),(n=e.call(this,t)||this).supportsMasking=!0,n.axis=null==t.axis?-1:t.axis,n.momentum=null==t.momentum?.99:t.momentum,n.epsilon=null==t.epsilon?.001:t.epsilon,n.center=null==t.center||t.center,n.scale=null==t.scale||t.scale,n.betaInitializer=tf_layers_esm_getInitializer(t.betaInitializer||"zeros"),n.gammaInitializer=tf_layers_esm_getInitializer(t.gammaInitializer||"ones"),n.movingMeanInitializer=tf_layers_esm_getInitializer(t.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=tf_layers_esm_getInitializer(t.movingVarianceInitializer||"ones"),n.betaConstraint=tf_layers_esm_getConstraint(t.betaConstraint),n.gammaConstraint=tf_layers_esm_getConstraint(t.gammaConstraint),n.betaRegularizer=tf_layers_esm_getRegularizer(t.betaRegularizer),n.gammaRegularizer=tf_layers_esm_getRegularizer(t.gammaRegularizer),n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t;e=tf_layers_esm_getExactlyOneShape(e);var n=this.axis>=0?this.axis:this.axis+e.length,r=e[n];if(null==r)throw new tf_layers_esm_ValueError("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new tf_layers_esm_InputSpec({ndim:e.length,axes:(t={},t[n]=r,t)})];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},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var r=null!=t.training&&t.training,i=tf_layers_esm_getExactlyOneTensor(e),a=i.shape,o=a.length,s=tf_layers_esm_range(0,o),l=n.axis>=0?n.axis:n.axis+o;s.splice(l,1);var u=tf_layers_esm_pyListRepeat(1,o);u[l]=a[l];var c=s.slice();c.sort();var p=!tf_core_esm["util"].arraysEqual(c,tf_layers_esm_range(0,o).slice(0,o-1));if(!r)return function(){if(p){var e=n.movingMean.read().reshape(u),t=n.movingVariance.read().reshape(u),r=n.center?n.beta.read().reshape(u):null,a=n.scale?n.gamma.read().reshape(u):null;return tf_layers_esm_batchNormalization(i,e,t,r,a,n.epsilon)}return tf_layers_esm_batchNormalization(i,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=tf_layers_esm_normalizeBatchInTraining(i,n.gamma.read(),n.beta.read(),s,n.epsilon),d=h[0],f=h[1],g=h[2],m=function(e,t,n){Object(tf_core_esm["tidy"])(function(){var r=1-n,i=e.read(),a=i.sub(t).mul(r);e.write(i.sub(a))})};return m(n.movingMean,f,n.momentum),m(n.movingVariance,g,n.momentum),d})},t.prototype.getConfig=function(){var t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:tf_layers_esm_serializeInitializer(this.betaInitializer),gammaInitializer:tf_layers_esm_serializeInitializer(this.gammaInitializer),movingMeanInitializer:tf_layers_esm_serializeInitializer(this.movingMeanInitializer),movingVarianceInitializer:tf_layers_esm_serializeInitializer(this.movingVarianceInitializer),betaRegularizer:tf_layers_esm_serializeRegularizer(this.betaRegularizer),gammaRegularizer:tf_layers_esm_serializeRegularizer(this.gammaRegularizer),betaConstraint:tf_layers_esm_serializeConstraint(this.betaConstraint),gammaConstraint:tf_layers_esm_serializeConstraint(this.gammaConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="BatchNormalization",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_BatchNormalization);var tf_layers_esm_LayerNormalization=function(e){function t(t){var n=this;if(null==t&&(t={}),(n=e.call(this,t)||this).axis=null==t.axis?-1:t.axis,"number"==typeof n.axis){if(!Number.isInteger(n.axis))throw new Error("Expected axis to be an integer, but received "+n.axis)}else{if(!Array.isArray(n.axis))throw new Error("Expected axis to be an integer or an array of integers, but received "+JSON.stringify(n.axis));for(var r=0,i=n.axis;r<i.length;r++){var a=i[r];if(!Number.isInteger(a))throw new Error("Expected axis to be an array of integers, but received "+JSON.stringify(n.axis))}}return n.epsilon=null==t.epsilon?.001:t.epsilon,n.center=null==t.center||t.center,n.scale=null==t.scale||t.scale,n.betaInitializer=tf_layers_esm_getInitializer(t.betaInitializer||"zeros"),n.gammaInitializer=tf_layers_esm_getInitializer(t.gammaInitializer||"ones"),n.betaRegularizer=tf_layers_esm_getRegularizer(t.betaRegularizer),n.gammaRegularizer=tf_layers_esm_getRegularizer(t.gammaRegularizer),n.supportsMasking=!0,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t=(e=tf_layers_esm_getExactlyOneShape(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(var n=0;n<this.axis.length;++n)this.axis[n]<0&&(this.axis[n]+=t);for(var r=0,i=this.axis;r<i.length;r++){var a=i[r];if(a<0||a>=t)throw new Error("Invalid axis: "+a)}if(this.axis.length!==tf_layers_esm_unique(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var o=this.axis.map(function(t){return e[t]});this.scale?this.gamma=this.addWeight("gamma",o,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",o,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0},t.prototype.call=function(e,t){var n=this,r=tf_layers_esm_getExactlyOneTensor(e),i=r.shape,a=i.length;return Object(tf_core_esm["tidy"])(function(){for(var e=Object(tf_core_esm["moments"])(r,n.axis,!0),t=e.mean,o=e.variance,s=tf_layers_esm_pyListRepeat(1,a),l=0,u=n.axis;l<u.length;l++){var c=u[l];s[c]=i[c]}for(var p=function(e){return null!=e&&e.shape.length!==a&&n.axis!==[a-1]?e.reshape(s):e},h=p(n.gamma.read()),d=p(n.beta.read()),f=[],g=[],m=0;m<a;++m)-1!==n.axis.indexOf(m)?(f.push(i[m]),g.push(1)):(f.push(1),g.push(i[m]));return t=t.tile(f),o=o.tile(f),h=h.tile(g),d=d.tile(g),tf_layers_esm_batchNormalization(r,t,o,d,h,n.epsilon)})},t.prototype.getConfig=function(){var t={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:tf_layers_esm_serializeInitializer(this.betaInitializer),gammaInitializer:tf_layers_esm_serializeInitializer(this.gammaInitializer),betaRegularizer:tf_layers_esm_serializeRegularizer(this.betaRegularizer),gammaRegularizer:tf_layers_esm_serializeRegularizer(this.gammaRegularizer)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="LayerNormalization",t}(tf_layers_esm_Layer);function tf_layers_esm_spatial2dPadding(e,t,n){return Object(tf_core_esm["tidy"])(function(){if(4!==e.rank)throw new tf_layers_esm_ValueError("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new tf_layers_esm_ValueError("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n=tf_layers_esm_imageDataFormat()),"channelsLast"!==n&&"channelsFirst"!==n)throw new tf_layers_esm_ValueError("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],Object(tf_core_esm["pad"])(e,r)})}tf_core_esm["serialization"].registerClass(tf_layers_esm_LayerNormalization);var tf_layers_esm_ZeroPadding2D=function(e){function t(t){var n=this;if(null==t&&(t={}),(n=e.call(this,t)||this).dataFormat=null==t.dataFormat?tf_layers_esm_imageDataFormat():t.dataFormat,null==t.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)n.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new tf_layers_esm_ValueError("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+t.padding.length+" array.");var r=void 0,i=void 0;if("number"==typeof t.padding[0])r=[t.padding[0],t.padding[0]],i=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new tf_layers_esm_ValueError("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+t.padding[0].length+" array.");if(r=t.padding[0],2!==t.padding[1].length)throw new tf_layers_esm_ValueError("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+t.padding[1].length+" array.");i=t.padding[1]}n.padding=[r,i]}return n.inputSpec=[new tf_layers_esm_InputSpec({ndim:4})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){var t,n;return e=tf_layers_esm_getExactlyOneShape(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_spatial2dPadding(tf_layers_esm_getExactlyOneTensor(e),n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ZeroPadding2D",t}(tf_layers_esm_Layer);function tf_layers_esm_pool2d(e,t,n,r,i,a){return Object(tf_core_esm["tidy"])(function(){var o;tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPoolMode(a),tf_layers_esm_checkPaddingMode(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==i&&(i=tf_layers_esm_imageDataFormat()),null==a&&(a="max"),e=tf_layers_esm_preprocessConv2DInput(e,i);var s="same"===r?"same":"valid";return o="max"===a?Object(tf_core_esm["maxPool"])(e,t,n,s):Object(tf_core_esm["avgPool"])(e,t,n,s),"channelsFirst"===i&&(o=Object(tf_core_esm["transpose"])(o,[0,3,1,2])),o})}function tf_layers_esm_pool3d(e,t,n,r,i,a){return Object(tf_core_esm["tidy"])(function(){var o;tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPoolMode(a),tf_layers_esm_checkPaddingMode(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==i&&(i=tf_layers_esm_imageDataFormat()),null==a&&(a="max"),e=tf_layers_esm_preprocessConv3DInput(e,i);var s="same"===r?"same":"valid";return o="max"===a?Object(tf_core_esm["maxPool3d"])(e,t,n,s):Object(tf_core_esm["avgPool3d"])(e,t,n,s),"channelsFirst"===i&&(o=Object(tf_core_esm["transpose"])(o,[0,4,1,2,3])),o})}tf_core_esm["serialization"].registerClass(tf_layers_esm_ZeroPadding2D);var tf_layers_esm_Pooling1D=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=2),n=e.call(this,t)||this,"number"==typeof t.poolSize)n.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new tf_layers_esm_ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));n.poolSize=t.poolSize}if(tf_layers_esm_assertPositiveInteger(n.poolSize,"poolSize"),null==t.strides)n.strides=n.poolSize;else if("number"==typeof t.strides)n.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new tf_layers_esm_ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));n.strides=t.strides}return tf_layers_esm_assertPositiveInteger(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,tf_layers_esm_checkPaddingMode(n.padding),n.inputSpec=[new tf_layers_esm_InputSpec({ndim:3})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){var t=tf_layers_esm_convOutputLength((e=tf_layers_esm_getExactlyOneShape(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){n.invokeCallHook(e,t),e=tf_layers_esm_expandDims$1(tf_layers_esm_getExactlyOneTensor(e),2);var r=n.poolingFunction(tf_layers_esm_getExactlyOneTensor(e),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return Object(tf_core_esm["squeeze"])(r,[2])})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(tf_layers_esm_Layer),tf_layers_esm_MaxPooling1D=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPaddingMode(r),tf_layers_esm_pool2d(e,t,n,r,i,"max")},t.className="MaxPooling1D",t}(tf_layers_esm_Pooling1D);tf_core_esm["serialization"].registerClass(tf_layers_esm_MaxPooling1D);var tf_layers_esm_AveragePooling1D=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPaddingMode(r),tf_layers_esm_pool2d(e,t,n,r,i,"avg")},t.className="AveragePooling1D",t}(tf_layers_esm_Pooling1D);tf_core_esm["serialization"].registerClass(tf_layers_esm_AveragePooling1D);var tf_layers_esm_Pooling2D=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new tf_layers_esm_ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");n.strides=t.strides}else n.strides=[t.strides,t.strides];return tf_layers_esm_assertPositiveInteger(n.poolSize,"poolSize"),tf_layers_esm_assertPositiveInteger(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,tf_layers_esm_checkDataFormat(n.dataFormat),tf_layers_esm_checkPaddingMode(n.padding),n.inputSpec=[new tf_layers_esm_InputSpec({ndim:4})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){e=tf_layers_esm_getExactlyOneShape(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=tf_layers_esm_convOutputLength(t,this.poolSize[0],this.padding,this.strides[0]),n=tf_layers_esm_convOutputLength(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return n.invokeCallHook(e,t),n.poolingFunction(tf_layers_esm_getExactlyOneTensor(e),n.poolSize,n.strides,n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(tf_layers_esm_Layer),tf_layers_esm_MaxPooling2D=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPaddingMode(r),tf_layers_esm_pool2d(e,t,n,r,i,"max")},t.className="MaxPooling2D",t}(tf_layers_esm_Pooling2D);tf_core_esm["serialization"].registerClass(tf_layers_esm_MaxPooling2D);var tf_layers_esm_AveragePooling2D=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPaddingMode(r),tf_layers_esm_pool2d(e,t,n,r,i,"avg")},t.className="AveragePooling2D",t}(tf_layers_esm_Pooling2D);tf_core_esm["serialization"].registerClass(tf_layers_esm_AveragePooling2D);var tf_layers_esm_Pooling3D=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(3!==t.strides.length)throw new tf_layers_esm_ValueError("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+t.strides.length+".");n.strides=t.strides}else n.strides=[t.strides,t.strides,t.strides];return tf_layers_esm_assertPositiveInteger(n.poolSize,"poolSize"),tf_layers_esm_assertPositiveInteger(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,tf_layers_esm_checkDataFormat(n.dataFormat),tf_layers_esm_checkPaddingMode(n.padding),n.inputSpec=[new tf_layers_esm_InputSpec({ndim:5})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){e=tf_layers_esm_getExactlyOneShape(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[4]:e[3];return t=tf_layers_esm_convOutputLength(t,this.poolSize[0],this.padding,this.strides[0]),n=tf_layers_esm_convOutputLength(n,this.poolSize[1],this.padding,this.strides[1]),r=tf_layers_esm_convOutputLength(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return n.invokeCallHook(e,t),n.poolingFunction(tf_layers_esm_getExactlyOneTensor(e),n.poolSize,n.strides,n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(tf_layers_esm_Layer),tf_layers_esm_MaxPooling3D=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPaddingMode(r),tf_layers_esm_pool3d(e,t,n,r,i,"max")},t.className="MaxPooling3D",t}(tf_layers_esm_Pooling3D);tf_core_esm["serialization"].registerClass(tf_layers_esm_MaxPooling3D);var tf_layers_esm_AveragePooling3D=function(e){function t(t){return e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return tf_layers_esm_checkDataFormat(i),tf_layers_esm_checkPaddingMode(r),tf_layers_esm_pool3d(e,t,n,r,i,"avg")},t.className="AveragePooling3D",t}(tf_layers_esm_Pooling3D);tf_core_esm["serialization"].registerClass(tf_layers_esm_AveragePooling3D);var tf_layers_esm_GlobalPooling1D=function(e){function t(t){var n=e.call(this,t)||this;return n.inputSpec=[new tf_layers_esm_InputSpec({ndim:3})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,t){throw new tf_layers_esm_NotImplementedError},t}(tf_layers_esm_Layer),tf_layers_esm_GlobalAveragePooling1D=function(e){function t(t){return e.call(this,t||{})||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_getExactlyOneTensor(e);return Object(tf_core_esm["mean"])(t,1)})},t.className="GlobalAveragePooling1D",t}(tf_layers_esm_GlobalPooling1D);tf_core_esm["serialization"].registerClass(tf_layers_esm_GlobalAveragePooling1D);var tf_layers_esm_GlobalMaxPooling1D=function(e){function t(t){return e.call(this,t||{})||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_getExactlyOneTensor(e);return Object(tf_core_esm["max"])(t,1)})},t.className="GlobalMaxPooling1D",t}(tf_layers_esm_GlobalPooling1D);tf_core_esm["serialization"].registerClass(tf_layers_esm_GlobalMaxPooling1D);var tf_layers_esm_GlobalPooling2D=function(e){function t(t){var n=e.call(this,t)||this;return n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,tf_layers_esm_checkDataFormat(n.dataFormat),n.inputSpec=[new tf_layers_esm_InputSpec({ndim:4})],n}return tf_layers_esm_extends(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,t){throw new tf_layers_esm_NotImplementedError},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(tf_layers_esm_Layer),tf_layers_esm_GlobalAveragePooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_getExactlyOneTensor(e);return"channelsLast"===n.dataFormat?Object(tf_core_esm["mean"])(t,[1,2]):Object(tf_core_esm["mean"])(t,[2,3])})},t.className="GlobalAveragePooling2D",t}(tf_layers_esm_GlobalPooling2D);tf_core_esm["serialization"].registerClass(tf_layers_esm_GlobalAveragePooling2D);var tf_layers_esm_GlobalMaxPooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var t=tf_layers_esm_getExactlyOneTensor(e);return"channelsLast"===n.dataFormat?Object(tf_core_esm["max"])(t,[1,2]):Object(tf_core_esm["max"])(t,[2,3])})},t.className="GlobalMaxPooling2D",t}(tf_layers_esm_GlobalPooling2D);function tf_layers_esm_standardizeArgs(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new tf_layers_esm_ValueError("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function i(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=i(t),constants:n=i(n)}}function tf_layers_esm_rnn(e,t,n,r,i,a,o,s){return void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===s&&(s=!1),Object(tf_core_esm["tidy"])(function(){var l=t.shape.length;if(l<3)throw new tf_layers_esm_ValueError("Input should be at least 3D, but is "+l+"D.");var u=[1,0].concat(tf_layers_esm_range(2,l));if(t=Object(tf_core_esm["transpose"])(t,u),null!=a)throw new tf_layers_esm_NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=i&&((i=i.asType("bool").asType("float32")).rank===l-1&&(i=Object(tf_core_esm["expandDims"])(i,-1)),i=Object(tf_core_esm["transpose"])(i,u)),r&&(t=Object(tf_core_esm["reverse"])(t,0),null!=i&&(i=Object(tf_core_esm["reverse"])(i,0)));var c,p,h=[],d=n,f=t.shape[0],g=Object(tf_core_esm["unstack"])(t);null!=i&&(p=Object(tf_core_esm["unstack"])(i));for(var m,y=function(t){var n=g[t],r=Object(tf_core_esm["tidy"])(function(){return e(n,d)});if(null==i)c=r[0],d=r[1];else{var a=Object(tf_core_esm["tidy"])(function(){var e=p[t],n=Object(tf_core_esm["onesLike"])(e).sub(e);return{output:r[0].mul(e).addStrict(d[0].mul(n)),newStates:d.map(function(t,i){return r[1][i].mul(e).addStrict(t.mul(n))})}});c=a.output,d=a.newStates}s&&h.push(c)},v=0;v<f;++v)y(v);if(s){m=Object(tf_core_esm["stack"])(h,1)}return[c,m,d]})}tf_core_esm["serialization"].registerClass(tf_layers_esm_GlobalMaxPooling2D);var tf_layers_esm_RNN=function(e){function t(t){var n,r=e.call(this,t)||this;if(null==t.cell)throw new tf_layers_esm_ValueError("cell property is missing for the constructor of RNN.");if(null==(n=Array.isArray(t.cell)?new tf_layers_esm_StackedRNNCells({cells:t.cell}):t.cell).stateSize)throw new tf_layers_esm_ValueError("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell=n,r.returnSequences=null!=t.returnSequences&&t.returnSequences,r.returnState=null!=t.returnState&&t.returnState,r.goBackwards=null!=t.goBackwards&&t.goBackwards,r._stateful=null!=t.stateful&&t.stateful,r.unroll=null!=t.unroll&&t.unroll,r.supportsMasking=!0,r.inputSpec=[new tf_layers_esm_InputSpec({ndim:3})],r.stateSpec=null,r.states_=null,r.numConstants=null,r.keptStates=[],r}return tf_layers_esm_extends(t,e),t.prototype.getStates=function(){return null==this.states_?tf_layers_esm_range(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(function(e){return null}):this.states_},t.prototype.setStates=function(e){this.states_=e},t.prototype.computeOutputShape=function(e){tf_layers_esm_isArrayOfShapes(e)&&(e=e[0]),e=e;var t=this.cell.stateSize;Array.isArray(t)||(t=[t]);var n,r=t[0];if(n=this.returnSequences?[e[0],e[1],r]:[e[0],r],this.returnState){for(var i=[],a=0,o=t;a<o.length;a++){var s=o[a];i.push([e[0],s])}return[n].concat(i)}return n},t.prototype.computeMask=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){Array.isArray(t)&&(t=t[0]);var e=n.returnSequences?t:null;if(n.returnState){var r=n.states.map(function(e){return null});return[e].concat(r)}return e})},Object.defineProperty(t.prototype,"states",{get:function(){if(null==this.states_){for(var e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[],n=0;n<e;++n)t.push(null);return t}return this.states_},set:function(e){this.states_=e},enumerable:!0,configurable:!0}),t.prototype.build=function(e){if(null!=this.numConstants)throw new tf_layers_esm_NotImplementedError("Constants support is not implemented in RNN yet.");tf_layers_esm_isArrayOfShapes(e)&&(e=e[0]),e=e;var t=this.stateful?e[0]:null,n=e[e.length-1];this.inputSpec[0]=new tf_layers_esm_InputSpec({shape:[t,null,n]});var r,i=[e[0]].concat(e.slice(2));if(this.cell.build(i),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!tf_core_esm["util"].arraysEqual(this.stateSpec.map(function(e){return e.shape[e.shape.length-1]}),r))throw new tf_layers_esm_ValueError("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec="+this.stateSpec+"; However cell.stateSize is "+this.cell.stateSize)}else this.stateSpec=r.map(function(e){return new tf_layers_esm_InputSpec({shape:[null,e]})});this.stateful&&this.resetStates()},t.prototype.resetStates=function(e,t){var n=this;void 0===t&&(t=!1),Object(tf_core_esm["tidy"])(function(){if(!n.stateful)throw new tf_layers_esm_AttributeError("Cannot call resetStates() on an RNN Layer that is not stateful.");var r=n.inputSpec[0].shape[0];if(null==r)throw new tf_layers_esm_ValueError("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==n.states_)Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map(function(e){return Object(tf_core_esm["zeros"])([r,e])}):n.states_=[Object(tf_core_esm["zeros"])([r,n.cell.stateSize])];else if(null==e)Object(tf_core_esm["dispose"])(n.states_),null!=n.keptStates&&(Object(tf_core_esm["dispose"])(n.keptStates),n.keptStates=[]),Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map(function(e){return Object(tf_core_esm["zeros"])([r,e])}):n.states_[0]=Object(tf_core_esm["zeros"])([r,n.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==n.states_.length)throw new tf_layers_esm_ValueError("Layer "+n.name+" expects "+n.states_.length+" state(s), but it received "+e.length+" state value(s). Input received: "+e);!0===t?n.keptStates.push(n.states_.slice()):Object(tf_core_esm["dispose"])(n.states_);for(var i=0;i<n.states_.length;++i){var a=e[i],o=Array.isArray(n.cell.stateSize)?n.cell.stateSize[i]:n.cell.stateSize,s=[r,o];if(!tf_core_esm["util"].arraysEqual(a.shape,s))throw new tf_layers_esm_ValueError("State "+i+" is incompatible with layer "+n.name+": expected shape="+s+", received shape="+a.shape);n.states_[i]=a}}n.states_=n.states_.map(function(e){return Object(tf_core_esm["keep"])(e.clone())})})},t.prototype.apply=function(t,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=tf_layers_esm_standardizeArgs(t,r,i,this.numConstants);t=a.inputs,r=a.initialState,i=a.constants;var o=[],s=[];if(null!=r){n.initialState=r,o=o.concat(r),this.stateSpec=[];for(var l=0,u=r;l<u.length;l++){var c=u[l];this.stateSpec.push(new tf_layers_esm_InputSpec({shape:c.shape}))}s=s.concat(this.stateSpec)}if(null!=i&&(n.constants=i,o=o.concat(i),this.numConstants=i.length),o[0]instanceof tf_layers_esm_SymbolicTensor){var p=[t].concat(o),h=this.inputSpec.concat(s),d=this.inputSpec;this.inputSpec=h;var f=e.prototype.apply.call(this,p,n);return this.inputSpec=d,f}return e.prototype.apply.call(this,t,n)},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;e=tf_layers_esm_getExactlyOneTensor(e),null==a&&(a=n.stateful?n.states_:n.getInitialState(e));var o=Array.isArray(n.cell.stateSize)?n.cell.stateSize.length:1;if(a.length!==o)throw new tf_layers_esm_ValueError("RNN Layer has "+o+" state(s) but was passed "+a.length+" initial state(s).");n.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var s={training:i},l=tf_layers_esm_rnn(function(e,t){var r=n.cell.call([e].concat(t),s);return[r[0],r.slice(1)]},e,a,n.goBackwards,r,null,n.unroll,n.returnSequences),u=l[0],c=l[1],p=l[2];n.stateful&&n.resetStates(p,i);var h=n.returnSequences?c:u;return n.returnState?[h].concat(p):h})},t.prototype.getInitialState=function(e){var t=this;return Object(tf_core_esm["tidy"])(function(){var n=Object(tf_core_esm["zeros"])(e.shape);return n=tf_layers_esm_expandDims$1(n=Object(tf_core_esm["sum"])(n,[1,2])),Array.isArray(t.cell.stateSize)?t.cell.stateSize.map(function(e){return e>1?tf_layers_esm_tile$1(n,[1,e]):n}):t.cell.stateSize>1?[tf_layers_esm_tile$1(n,[1,t.cell.stateSize])]:[n]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.setFastWeightInitDuringBuild=function(t){e.prototype.setFastWeightInitDuringBuild.call(this,t),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(t)},t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var n=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:n};var r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.fromConfig=function(e,t,n){void 0===n&&(n={});var r=tf_layers_esm_deserialize(t.cell,n);return new e(Object.assign(t,{cell:r}))},t.className="RNN",t}(tf_layers_esm_Layer);tf_core_esm["serialization"].registerClass(tf_layers_esm_RNN);var tf_layers_esm_RNNCell=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t}(tf_layers_esm_Layer),tf_layers_esm_SimpleRNNCell=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,tf_layers_esm_assertPositiveInteger(n.units,"units"),n.activation=tf_layers_esm_getActivation(null==t.activation?n.DEFAULT_ACTIVATION:t.activation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=tf_layers_esm_getInitializer(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=tf_layers_esm_getInitializer(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=tf_layers_esm_getInitializer(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=tf_layers_esm_getRegularizer(t.kernelRegularizer),n.recurrentRegularizer=tf_layers_esm_getRegularizer(t.recurrentRegularizer),n.biasRegularizer=tf_layers_esm_getRegularizer(t.biasRegularizer),n.kernelConstraint=tf_layers_esm_getConstraint(t.kernelConstraint),n.recurrentConstraint=tf_layers_esm_getConstraint(t.recurrentConstraint),n.biasConstraint=tf_layers_esm_getConstraint(t.biasConstraint),n.dropout=tf_layers_esm_min$1([1,tf_layers_esm_max$1([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=tf_layers_esm_min$1([1,tf_layers_esm_max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){e=tf_layers_esm_getExactlyOneShape(e),this.kernel=this.addWeight("kernel",[e[e.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},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){if(2!==(e=e).length)throw new tf_layers_esm_ValueError("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var r=e[1];e=e[0];var i,a=null!=t.training&&t.training;0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=tf_layers_esm_generateDropoutMask(function(){return Object(tf_core_esm["onesLike"])(e)},n.dropout,a)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=tf_layers_esm_generateDropoutMask(function(){return Object(tf_core_esm["onesLike"])(r)},n.recurrentDropout,a));var o=n.dropoutMask,s=n.recurrentDropoutMask;i=tf_layers_esm_dot(null!=o?Object(tf_core_esm["mul"])(e,o):e,n.kernel.read()),null!=n.bias&&(i=tf_layers_esm_biasAdd(i,n.bias.read())),null!=s&&(r=Object(tf_core_esm["mul"])(r,s));var l=Object(tf_core_esm["add"])(i,tf_layers_esm_dot(r,n.recurrentKernel.read()));return null!=n.activation&&(l=n.activation.apply(l)),[l,l]})},t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),recurrentInitializer:tf_layers_esm_serializeInitializer(this.recurrentInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:tf_layers_esm_serializeRegularizer(this.recurrentRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),recurrentConstraint:tf_layers_esm_serializeConstraint(this.recurrentConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="SimpleRNNCell",t}(tf_layers_esm_RNNCell);tf_core_esm["serialization"].registerClass(tf_layers_esm_SimpleRNNCell);var tf_layers_esm_SimpleRNN=function(e){function t(t){return t.cell=new tf_layers_esm_SimpleRNNCell(t),e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(t,n){var r=this;return Object(tf_core_esm["tidy"])(function(){null!=r.cell.dropoutMask&&(Object(tf_core_esm["dispose"])(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Object(tf_core_esm["dispose"])(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,a=null==n?null:n.training,o=null==n?null:n.initialState;return e.prototype.call.call(r,t,{mask:i,training:a,initialState:o})})},Object.defineProperty(t.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),recurrentInitializer:tf_layers_esm_serializeInitializer(this.recurrentInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:tf_layers_esm_serializeRegularizer(this.recurrentRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),recurrentConstraint:tf_layers_esm_serializeConstraint(this.recurrentConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t},t.fromConfig=function(e,t){return new e(t)},t.className="SimpleRNN",t}(tf_layers_esm_RNN);tf_core_esm["serialization"].registerClass(tf_layers_esm_SimpleRNN);var tf_layers_esm_GRUCell=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,tf_layers_esm_assertPositiveInteger(n.units,"units"),n.activation=tf_layers_esm_getActivation(void 0===t.activation?n.DEFAULT_ACTIVATION:t.activation),n.recurrentActivation=tf_layers_esm_getActivation(void 0===t.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=tf_layers_esm_getInitializer(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=tf_layers_esm_getInitializer(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=tf_layers_esm_getInitializer(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=tf_layers_esm_getRegularizer(t.kernelRegularizer),n.recurrentRegularizer=tf_layers_esm_getRegularizer(t.recurrentRegularizer),n.biasRegularizer=tf_layers_esm_getRegularizer(t.biasRegularizer),n.kernelConstraint=tf_layers_esm_getConstraint(t.kernelConstraint),n.recurrentConstraint=tf_layers_esm_getConstraint(t.recurrentConstraint),n.biasConstraint=tf_layers_esm_getConstraint(t.biasConstraint),n.dropout=tf_layers_esm_min$1([1,tf_layers_esm_max$1([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=tf_layers_esm_min$1([1,tf_layers_esm_max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.implementation=t.implementation,n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t=(e=tf_layers_esm_getExactlyOneShape(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){if(2!==(e=e).length)throw new tf_layers_esm_ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got "+e.length+".");var r=null!=t.training&&t.training,i=e[1];e=e[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=tf_layers_esm_generateDropoutMask(function(){return Object(tf_core_esm["onesLike"])(e)},n.dropout,r,3)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=tf_layers_esm_generateDropoutMask(function(){return Object(tf_core_esm["onesLike"])(i)},n.recurrentDropout,r,3));var a,o,s,l=n.dropoutMask,u=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(e=Object(tf_core_esm["mul"])(e,l[0]));var c=tf_layers_esm_dot(e,n.kernel.read());n.useBias&&(c=tf_layers_esm_biasAdd(c,n.bias.read())),0<n.recurrentDropout&&n.recurrentDropout<1&&(i=Object(tf_core_esm["mul"])(i,u[0]));var p=n.recurrentKernel.read(),h=Object(tf_core_esm["split"])(p,[2*n.units,n.units],p.rank-1),d=h[0],f=h[1],g=tf_layers_esm_dot(i,d),m=Object(tf_core_esm["split"])(c,3,c.rank-1),y=m[0],v=m[1],b=m[2],w=Object(tf_core_esm["split"])(g,2,g.rank-1),z=w[0],S=w[1];a=n.recurrentActivation.apply(Object(tf_core_esm["add"])(y,z)),o=n.recurrentActivation.apply(Object(tf_core_esm["add"])(v,S));var A=tf_layers_esm_dot(Object(tf_core_esm["mul"])(o,i),f);s=n.activation.apply(Object(tf_core_esm["add"])(b,A));var _=Object(tf_core_esm["add"])(Object(tf_core_esm["mul"])(a,i),Object(tf_core_esm["mul"])(Object(tf_core_esm["add"])(1,Object(tf_core_esm["neg"])(a)),s));return[_,_]})},t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),recurrentActivation:tf_layers_esm_serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),recurrentInitializer:tf_layers_esm_serializeInitializer(this.recurrentInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:tf_layers_esm_serializeRegularizer(this.recurrentRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),recurrentConstraint:tf_layers_esm_serializeConstraint(this.recurrentConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="GRUCell",t}(tf_layers_esm_RNNCell);tf_core_esm["serialization"].registerClass(tf_layers_esm_GRUCell);var tf_layers_esm_GRU=function(e){function t(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new tf_layers_esm_GRUCell(t),e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(t,n){var r=this;return Object(tf_core_esm["tidy"])(function(){null!=r.cell.dropoutMask&&(Object(tf_core_esm["dispose"])(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Object(tf_core_esm["dispose"])(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,a=null==n?null:n.training,o=null==n?null:n.initialState;return e.prototype.call.call(r,t,{mask:i,training:a,initialState:o})})},Object.defineProperty(t.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),recurrentActivation:tf_layers_esm_serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),recurrentInitializer:tf_layers_esm_serializeInitializer(this.recurrentInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:tf_layers_esm_serializeRegularizer(this.recurrentRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),recurrentConstraint:tf_layers_esm_serializeConstraint(this.recurrentConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t},t.fromConfig=function(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)},t.className="GRU",t}(tf_layers_esm_RNN);tf_core_esm["serialization"].registerClass(tf_layers_esm_GRU);var tf_layers_esm_LSTMCell=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,tf_layers_esm_assertPositiveInteger(n.units,"units"),n.activation=tf_layers_esm_getActivation(void 0===t.activation?n.DEFAULT_ACTIVATION:t.activation),n.recurrentActivation=tf_layers_esm_getActivation(void 0===t.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=tf_layers_esm_getInitializer(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=tf_layers_esm_getInitializer(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=tf_layers_esm_getInitializer(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.unitForgetBias=t.unitForgetBias,n.kernelRegularizer=tf_layers_esm_getRegularizer(t.kernelRegularizer),n.recurrentRegularizer=tf_layers_esm_getRegularizer(t.recurrentRegularizer),n.biasRegularizer=tf_layers_esm_getRegularizer(t.biasRegularizer),n.kernelConstraint=tf_layers_esm_getConstraint(t.kernelConstraint),n.recurrentConstraint=tf_layers_esm_getConstraint(t.recurrentConstraint),n.biasConstraint=tf_layers_esm_getConstraint(t.biasConstraint),n.dropout=tf_layers_esm_min$1([1,tf_layers_esm_max$1([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=tf_layers_esm_min$1([1,tf_layers_esm_max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.implementation=t.implementation,n.stateSize=[n.units,n.units],n.dropoutMask=null,n.recurrentDropoutMask=null,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){var t,n,r=(e=tf_layers_esm_getExactlyOneShape(e))[e.length-1];if(this.kernel=this.addWeight("kernel",[r,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var i=this.biasInitializer,a=this.units;n=new((t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return tf_layers_esm_extends(t,e),t.prototype.apply=function(e,t){var n=i.apply([a]),r=(new tf_layers_esm_Ones).apply([a]),o=i.apply([2*a]);return tf_layers_esm_concatAlongFirstAxis(tf_layers_esm_concatAlongFirstAxis(n,r),o)},t}(tf_layers_esm_Initializer)).className="CustomInit",t)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var r=null!=t.training&&t.training;if(3!==(e=e).length)throw new tf_layers_esm_ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got "+e.length+".");var i=e[1],a=e[2];e=e[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=tf_layers_esm_generateDropoutMask(function(){return Object(tf_core_esm["onesLike"])(e)},n.dropout,r,4)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=tf_layers_esm_generateDropoutMask(function(){return Object(tf_core_esm["onesLike"])(i)},n.recurrentDropout,r,4));var o,s,l,u,c=n.dropoutMask,p=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(e=Object(tf_core_esm["mul"])(e,c[0]));var h=tf_layers_esm_dot(e,n.kernel.read());0<n.recurrentDropout&&n.recurrentDropout<1&&(i=Object(tf_core_esm["mul"])(i,p[0])),h=Object(tf_core_esm["add"])(h,tf_layers_esm_dot(i,n.recurrentKernel.read())),n.useBias&&(h=tf_layers_esm_biasAdd(h,n.bias.read()));var d=Object(tf_core_esm["split"])(h,4,h.rank-1),f=d[0],g=d[1],m=d[2],y=d[3];o=n.recurrentActivation.apply(f),s=n.recurrentActivation.apply(g),l=Object(tf_core_esm["add"])(Object(tf_core_esm["mul"])(s,a),Object(tf_core_esm["mul"])(o,n.activation.apply(m))),u=n.recurrentActivation.apply(y);var v=Object(tf_core_esm["mul"])(u,n.activation.apply(l));return[v,v,l]})},t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),recurrentActivation:tf_layers_esm_serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),recurrentInitializer:tf_layers_esm_serializeInitializer(this.recurrentInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:tf_layers_esm_serializeRegularizer(this.recurrentRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),recurrentConstraint:tf_layers_esm_serializeConstraint(this.recurrentConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="LSTMCell",t}(tf_layers_esm_RNNCell);tf_core_esm["serialization"].registerClass(tf_layers_esm_LSTMCell);var tf_layers_esm_LSTM=function(e){function t(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new tf_layers_esm_LSTMCell(t),e.call(this,t)||this}return tf_layers_esm_extends(t,e),t.prototype.call=function(t,n){var r=this;return Object(tf_core_esm["tidy"])(function(){null!=r.cell.dropoutMask&&(Object(tf_core_esm["dispose"])(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Object(tf_core_esm["dispose"])(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,a=null==n?null:n.training,o=null==n?null:n.initialState;return e.prototype.call.call(r,t,{mask:i,training:a,initialState:o})})},Object.defineProperty(t.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:tf_layers_esm_serializeActivation(this.activation),recurrentActivation:tf_layers_esm_serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:tf_layers_esm_serializeInitializer(this.kernelInitializer),recurrentInitializer:tf_layers_esm_serializeInitializer(this.recurrentInitializer),biasInitializer:tf_layers_esm_serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:tf_layers_esm_serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:tf_layers_esm_serializeRegularizer(this.recurrentRegularizer),biasRegularizer:tf_layers_esm_serializeRegularizer(this.biasRegularizer),activityRegularizer:tf_layers_esm_serializeRegularizer(this.activityRegularizer),kernelConstraint:tf_layers_esm_serializeConstraint(this.kernelConstraint),recurrentConstraint:tf_layers_esm_serializeConstraint(this.recurrentConstraint),biasConstraint:tf_layers_esm_serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t},t.fromConfig=function(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)},t.className="LSTM",t}(tf_layers_esm_RNN);tf_core_esm["serialization"].registerClass(tf_layers_esm_LSTM);var tf_layers_esm_StackedRNNCells=function(e){function t(t){var n=e.call(this,t)||this;return n.cells=t.cells,n}return tf_layers_esm_extends(t,e),Object.defineProperty(t.prototype,"stateSize",{get:function(){for(var e=[],t=0,n=this.cells.slice().reverse();t<n.length;t++){var r=n[t];Array.isArray(r.stateSize)?e.push.apply(e,r.stateSize):e.push(r.stateSize)}return e},enumerable:!0,configurable:!0}),t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){for(var r=(e=e).slice(1),i=[],a=0,o=n.cells.slice().reverse();a<o.length;a++){var s=o[a];Array.isArray(s.stateSize)?i.push(r.splice(0,s.stateSize.length)):i.push(r.splice(0,1))}i.reverse();for(var l,u=[],c=0;c<n.cells.length;++c){s=n.cells[c];r=i[c],l=0===c?[e[0]].concat(r):[l[0]].concat(r),l=s.call(l,t),u.push(l.slice(1))}r=[];for(var p=0,h=u.slice().reverse();p<h.length;p++){var d=h[p];r.push.apply(r,d)}return[l[0]].concat(r)})},t.prototype.build=function(e){var t;tf_layers_esm_isArrayOfShapes(e)&&(e=e[0]),e=e,this.cells.forEach(function(n,r){tf_layers_esm_nameScope("RNNCell_"+r,function(){n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]})}),this.built=!0},t.prototype.getConfig=function(){for(var t=[],n=0,r=this.cells;n<r.length;n++){var i=r[n];t.push({className:i.getClassName(),config:i.getConfig()})}var a={cells:t},o=e.prototype.getConfig.call(this);return Object.assign(a,o),a},t.fromConfig=function(e,t,n){void 0===n&&(n={});for(var r=[],i=0,a=t.cells;i<a.length;i++){var o=a[i];r.push(tf_layers_esm_deserialize(o,n))}return new e({cells:r})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){if(!this.trainable)return[];for(var e=[],t=0,n=this.cells;t<n.length;t++){var r=n[t];e.push.apply(e,r.trainableWeights)}return e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){for(var e=[],t=0,n=this.cells;t<n.length;t++){var r=n[t];e.push.apply(e,r.nonTrainableWeights)}if(!this.trainable){for(var i=[],a=0,o=this.cells;a<o.length;a++){r=o[a];i.push.apply(i,r.trainableWeights)}return i.concat(e)}return e},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){for(var e=[],t=0,n=this.cells;t<n.length;t++){var r=n[t];e.push.apply(e,r.weights)}return tf_layers_esm_batchGetValue(e)},t.prototype.setWeights=function(e){for(var t=[],n=0,r=this.cells;n<r.length;n++)for(var i=r[n],a=i.weights.length,o=e.splice(a),s=0;s<i.weights.length;++s)t.push([i.weights[s],o[s]]);tf_layers_esm_batchSetValue(t)},t.className="StackedRNNCells",t}(tf_layers_esm_RNNCell);function tf_layers_esm_generateDropoutMask(e,t,n,r){function i(){return tf_layers_esm_dropout$1(e(),t)}if(void 0===n&&(n=null),void 0===r&&(r=1),r>1){for(var a=[],o=0;o<r;o++)a.push(tf_layers_esm_inTrainPhase(i,e,n));return a.map(function(e){return Object(tf_core_esm["keep"])(e.clone())})}return Object(tf_core_esm["keep"])(tf_layers_esm_inTrainPhase(i,e,n).clone())}tf_core_esm["serialization"].registerClass(tf_layers_esm_StackedRNNCells);var tf_layers_esm_Wrapper=function(e){function t(t){var n=e.call(this,t)||this;return n.layer=t.layer,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(e){this.built=!0},Object.defineProperty(t.prototype,"trainable",{get:function(){return null!=this.layer&&this.layer.trainable},set:function(e){null!=this.layer&&(this.layer.trainable=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.layer.getWeights()},t.prototype.setWeights=function(e){this.layer.setWeights(e)},t.prototype.getConfig=function(){var t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.prototype.setFastWeightInitDuringBuild=function(t){e.prototype.setFastWeightInitDuringBuild.call(this,t),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(t)},t.fromConfig=function(e,t,n){void 0===n&&(n={});var r=tf_layers_esm_deserialize(t.layer,n);delete t.layer;var i={layer:r};return Object.assign(i,t),new e(i)},t}(tf_layers_esm_Layer),tf_layers_esm_TimeDistributed=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n}return tf_layers_esm_extends(t,e),t.prototype.build=function(t){if((t=tf_layers_esm_getExactlyOneShape(t)).length<3)throw new tf_layers_esm_ValueError("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var n=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),e.prototype.build.call(this,t)},t.prototype.computeOutputShape=function(e){var t=[(e=tf_layers_esm_getExactlyOneShape(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){return tf_layers_esm_rnn(function(e,r){return[tf_layers_esm_getExactlyOneTensor(n.layer.call(e,t)),[]]},e=tf_layers_esm_getExactlyOneTensor(e),[],!1,null,null,!1,!0)[1]})},t.className="TimeDistributed",t}(tf_layers_esm_Wrapper);function tf_layers_esm_checkBidirectionalMergeMode(e){tf_layers_esm_checkStringTypeUnionValue(tf_layers_esm_VALID_BIDIRECTIONAL_MERGE_MODES,"BidirectionalMergeMode",e)}tf_core_esm["serialization"].registerClass(tf_layers_esm_TimeDistributed);var tf_layers_esm_DEFAULT_BIDIRECTIONAL_MERGE_MODE="concat",tf_layers_esm_Bidirectional=function(e){function t(t){var n=e.call(this,t)||this,r=t.layer.getConfig(),i={};i.className=t.layer.getClassName(),i.config=r,n.forwardLayer=tf_layers_esm_deserialize(i),r.goBackwards=!0!==r.goBackwards;var a={};if(a.className=t.layer.getClassName(),a.config=r,n.backwardLayer=tf_layers_esm_deserialize(a),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===t.mergeMode?tf_layers_esm_DEFAULT_BIDIRECTIONAL_MERGE_MODE:t.mergeMode,tf_layers_esm_checkBidirectionalMergeMode(n.mergeMode),t.weights)throw new tf_layers_esm_NotImplementedError("weights support is not implemented for Bidirectional layer yet.");return n._stateful=t.layer.stateful,n.returnSequences=t.layer.returnSequences,n.returnState=t.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=t.layer.inputSpec,n.numConstants=null,n}return tf_layers_esm_extends(t,e),Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))},t.prototype.computeOutputShape=function(e){var t,n,r,i=this.forwardLayer.computeOutputShape(e);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(r=i.slice(1),t=i[0]):t=i[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):tf_layers_esm_singletonOrArray(n)},t.prototype.apply=function(t,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=tf_layers_esm_standardizeArgs(t,r,i,this.numConstants);if(t=a.inputs,r=a.initialState,i=a.constants,Array.isArray(t)&&(r=t.slice(1),t=t[0]),(null==r||0===r.length)&&null==i)return e.prototype.apply.call(this,t,n);var o=[],s=[];if(null!=r){var l=r.length;if(l%2>0)throw new tf_layers_esm_ValueError("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,o.push.apply(o,r);var u=r.map(function(e){return new tf_layers_esm_InputSpec({shape:e.shape})});this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),s.push.apply(s,u)}if(null!=i)throw new tf_layers_esm_NotImplementedError("Support for constants in Bidirectional layers is not implemented yet.");for(var c=o[0]instanceof tf_layers_esm_SymbolicTensor,p=0,h=o;p<h.length;p++){if(h[p]instanceof tf_layers_esm_SymbolicTensor!==c)throw new tf_layers_esm_ValueError("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors")}if(c){var d=[t].concat(o),f=this.inputSpec.concat(s),g=this.inputSpec;this.inputSpec=f;var m=e.prototype.apply.call(this,d,n);return this.inputSpec=g,m}return e.prototype.apply.call(this,t,n)},t.prototype.call=function(e,t){var n=this;return Object(tf_core_esm["tidy"])(function(){var r,i,a,o,s=t.initialState;if(null==s)r=n.forwardLayer.call(e,t),i=n.backwardLayer.call(e,t);else{var l=s.slice(0,s.length/2),u=s.slice(s.length/2);r=n.forwardLayer.call(e,Object.assign(t,{initialState:l})),i=n.backwardLayer.call(e,Object.assign(t,{initialState:u}))}return n.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(i.slice(1))),r=r[0],i=i[0]),n.returnSequences&&(i=Object(tf_core_esm["reverse"])(i,1)),"concat"===n.mergeMode?o=tf_layers_esm_concatenate([r,i]):"sum"===n.mergeMode?o=Object(tf_core_esm["add"])(r,i):"ave"===n.mergeMode?o=Object(tf_core_esm["mul"])(.5,Object(tf_core_esm["add"])(r,i)):"mul"===n.mergeMode?o=Object(tf_core_esm["mul"])(r,i):null==n.mergeMode&&(o=[r,i]),n.returnState?null==n.mergeMode?o.concat(a):[o].concat(a):o})},t.prototype.resetStates=function(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},t.prototype.build=function(e){var t=this;tf_layers_esm_nameScope(this.forwardLayer.name,function(){t.forwardLayer.build(e)}),tf_layers_esm_nameScope(this.backwardLayer.name,function(){t.backwardLayer.build(e)}),this.built=!0},t.prototype.computeMask=function(e,t){var n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){var r=this.forwardLayer.states.map(function(e){return null});return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}return n},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)},enumerable:!0,configurable:!0}),t.prototype.setFastWeightInitDuringBuild=function(t){e.prototype.setFastWeightInitDuringBuild.call(this,t),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(t),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(t)},t.prototype.getConfig=function(){var t={mergeMode:this.mergeMode},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.fromConfig=function(e,t){var n=tf_layers_esm_deserialize(t.layer);if(delete t.layer,null!=t.numConstants)throw new tf_layers_esm_NotImplementedError("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r=t;return r.layer=n,new e(r)},t.className="Bidirectional",t}(tf_layers_esm_Wrapper);function tf_layers_esm_inputLayer(e){return new tf_layers_esm_InputLayer(e)}function tf_layers_esm_elu$2(e){return new tf_layers_esm_ELU(e)}function tf_layers_esm_reLU(e){return new tf_layers_esm_ReLU(e)}function tf_layers_esm_leakyReLU(e){return new tf_layers_esm_LeakyReLU(e)}function tf_layers_esm_prelu$1(e){return new tf_layers_esm_PReLU(e)}function tf_layers_esm_softmax$1(e){return new tf_layers_esm_Softmax$1(e)}function tf_layers_esm_thresholdedReLU(e){return new tf_layers_esm_ThresholdedReLU(e)}function tf_layers_esm_conv1d$2(e){return new tf_layers_esm_Conv1D(e)}function tf_layers_esm_conv2d$1(e){return new tf_layers_esm_Conv2D(e)}function tf_layers_esm_conv2dTranspose$1(e){return new tf_layers_esm_Conv2DTranspose(e)}function tf_layers_esm_conv3d$2(e){return new tf_layers_esm_Conv3D(e)}function tf_layers_esm_separableConv2d$1(e){return new tf_layers_esm_SeparableConv2D(e)}function tf_layers_esm_cropping2D(e){return new tf_layers_esm_Cropping2D(e)}function tf_layers_esm_upSampling2d(e){return new tf_layers_esm_UpSampling2D(e)}function tf_layers_esm_depthwiseConv2d$2(e){return new tf_layers_esm_DepthwiseConv2D(e)}function tf_layers_esm_activation(e){return new tf_layers_esm_Activation$1(e)}function tf_layers_esm_dense(e){return new tf_layers_esm_Dense(e)}function tf_layers_esm_dropout$2(e){return new tf_layers_esm_Dropout(e)}function tf_layers_esm_spatialDropout1d(e){return new tf_layers_esm_SpatialDropout1D(e)}function tf_layers_esm_flatten$1(e){return new tf_layers_esm_Flatten(e)}function tf_layers_esm_repeatVector(e){return new tf_layers_esm_RepeatVector(e)}function tf_layers_esm_reshape(e){return new tf_layers_esm_Reshape(e)}function tf_layers_esm_permute(e){return new tf_layers_esm_Permute(e)}function tf_layers_esm_embedding(e){return new tf_layers_esm_Embedding(e)}function tf_layers_esm_add$2(e){return new tf_layers_esm_Add(e)}function tf_layers_esm_average$1(e){return new tf_layers_esm_Average(e)}function tf_layers_esm_concatenate$2(e){return new tf_layers_esm_Concatenate(e)}function tf_layers_esm_maximum$2(e){return new tf_layers_esm_Maximum(e)}function tf_layers_esm_minimum$2(e){return new tf_layers_esm_Minimum(e)}function tf_layers_esm_multiply$1(e){return new tf_layers_esm_Multiply(e)}function tf_layers_esm_dot$1(e){return new tf_layers_esm_Dot(e)}function tf_layers_esm_batchNormalization$1(e){return new tf_layers_esm_BatchNormalization(e)}function tf_layers_esm_layerNormalization(e){return new tf_layers_esm_LayerNormalization(e)}function tf_layers_esm_zeroPadding2d(e){return new tf_layers_esm_ZeroPadding2D(e)}function tf_layers_esm_averagePooling1d(e){return new tf_layers_esm_AveragePooling1D(e)}function tf_layers_esm_avgPool1d(e){return tf_layers_esm_averagePooling1d(e)}function tf_layers_esm_avgPooling1d(e){return tf_layers_esm_averagePooling1d(e)}function tf_layers_esm_averagePooling2d(e){return new tf_layers_esm_AveragePooling2D(e)}function tf_layers_esm_avgPool2d(e){return tf_layers_esm_averagePooling2d(e)}function tf_layers_esm_avgPooling2d(e){return tf_layers_esm_averagePooling2d(e)}function tf_layers_esm_averagePooling3d(e){return new tf_layers_esm_AveragePooling3D(e)}function tf_layers_esm_avgPool3d$1(e){return tf_layers_esm_averagePooling3d(e)}function tf_layers_esm_avgPooling3d(e){return tf_layers_esm_averagePooling3d(e)}function tf_layers_esm_globalAveragePooling1d(e){return new tf_layers_esm_GlobalAveragePooling1D(e)}function tf_layers_esm_globalAveragePooling2d(e){return new tf_layers_esm_GlobalAveragePooling2D(e)}function tf_layers_esm_globalMaxPooling1d(e){return new tf_layers_esm_GlobalMaxPooling1D(e)}function tf_layers_esm_globalMaxPooling2d(e){return new tf_layers_esm_GlobalMaxPooling2D(e)}function tf_layers_esm_maxPooling1d(e){return new tf_layers_esm_MaxPooling1D(e)}function tf_layers_esm_maxPooling2d(e){return new tf_layers_esm_MaxPooling2D(e)}function tf_layers_esm_maxPooling3d(e){return new tf_layers_esm_MaxPooling3D(e)}function tf_layers_esm_gru(e){return new tf_layers_esm_GRU(e)}function tf_layers_esm_gruCell(e){return new tf_layers_esm_GRUCell(e)}function tf_layers_esm_lstm(e){return new tf_layers_esm_LSTM(e)}function tf_layers_esm_lstmCell(e){return new tf_layers_esm_LSTMCell(e)}function tf_layers_esm_simpleRNN(e){return new tf_layers_esm_SimpleRNN(e)}function tf_layers_esm_simpleRNNCell(e){return new tf_layers_esm_SimpleRNNCell(e)}function tf_layers_esm_rnn$1(e){return new tf_layers_esm_RNN(e)}function tf_layers_esm_stackedRNNCells(e){return new tf_layers_esm_StackedRNNCells(e)}function tf_layers_esm_bidirectional(e){return new tf_layers_esm_Bidirectional(e)}function tf_layers_esm_timeDistributed(e){return new tf_layers_esm_TimeDistributed(e)}tf_core_esm["serialization"].registerClass(tf_layers_esm_Bidirectional);var tf_layers_esm_globalMaxPool1d=tf_layers_esm_globalMaxPooling1d,tf_layers_esm_globalMaxPool2d=tf_layers_esm_globalMaxPooling2d,tf_layers_esm_maxPool1d=tf_layers_esm_maxPooling1d,tf_layers_esm_maxPool2d=tf_layers_esm_maxPooling2d;function tf_layers_esm_gaussianNoise(e){return new tf_layers_esm_GaussianNoise(e)}function tf_layers_esm_gaussianDropout(e){return new tf_layers_esm_GaussianDropout(e)}function tf_layers_esm_alphaDropout(e){return new tf_layers_esm_AlphaDropout(e)}function tf_layers_esm_masking(e){return new tf_layers_esm_Masking(e)}var tf_layers_esm_exports_layers=Object.freeze({inputLayer:tf_layers_esm_inputLayer,elu:tf_layers_esm_elu$2,reLU:tf_layers_esm_reLU,leakyReLU:tf_layers_esm_leakyReLU,prelu:tf_layers_esm_prelu$1,softmax:tf_layers_esm_softmax$1,thresholdedReLU:tf_layers_esm_thresholdedReLU,conv1d:tf_layers_esm_conv1d$2,conv2d:tf_layers_esm_conv2d$1,conv2dTranspose:tf_layers_esm_conv2dTranspose$1,conv3d:tf_layers_esm_conv3d$2,separableConv2d:tf_layers_esm_separableConv2d$1,cropping2D:tf_layers_esm_cropping2D,upSampling2d:tf_layers_esm_upSampling2d,depthwiseConv2d:tf_layers_esm_depthwiseConv2d$2,activation:tf_layers_esm_activation,dense:tf_layers_esm_dense,dropout:tf_layers_esm_dropout$2,spatialDropout1d:tf_layers_esm_spatialDropout1d,flatten:tf_layers_esm_flatten$1,repeatVector:tf_layers_esm_repeatVector,reshape:tf_layers_esm_reshape,permute:tf_layers_esm_permute,embedding:tf_layers_esm_embedding,add:tf_layers_esm_add$2,average:tf_layers_esm_average$1,concatenate:tf_layers_esm_concatenate$2,maximum:tf_layers_esm_maximum$2,minimum:tf_layers_esm_minimum$2,multiply:tf_layers_esm_multiply$1,dot:tf_layers_esm_dot$1,batchNormalization:tf_layers_esm_batchNormalization$1,layerNormalization:tf_layers_esm_layerNormalization,zeroPadding2d:tf_layers_esm_zeroPadding2d,averagePooling1d:tf_layers_esm_averagePooling1d,avgPool1d:tf_layers_esm_avgPool1d,avgPooling1d:tf_layers_esm_avgPooling1d,averagePooling2d:tf_layers_esm_averagePooling2d,avgPool2d:tf_layers_esm_avgPool2d,avgPooling2d:tf_layers_esm_avgPooling2d,averagePooling3d:tf_layers_esm_averagePooling3d,avgPool3d:tf_layers_esm_avgPool3d$1,avgPooling3d:tf_layers_esm_avgPooling3d,globalAveragePooling1d:tf_layers_esm_globalAveragePooling1d,globalAveragePooling2d:tf_layers_esm_globalAveragePooling2d,globalMaxPooling1d:tf_layers_esm_globalMaxPooling1d,globalMaxPooling2d:tf_layers_esm_globalMaxPooling2d,maxPooling1d:tf_layers_esm_maxPooling1d,maxPooling2d:tf_layers_esm_maxPooling2d,maxPooling3d:tf_layers_esm_maxPooling3d,gru:tf_layers_esm_gru,gruCell:tf_layers_esm_gruCell,lstm:tf_layers_esm_lstm,lstmCell:tf_layers_esm_lstmCell,simpleRNN:tf_layers_esm_simpleRNN,simpleRNNCell:tf_layers_esm_simpleRNNCell,rnn:tf_layers_esm_rnn$1,stackedRNNCells:tf_layers_esm_stackedRNNCells,bidirectional:tf_layers_esm_bidirectional,timeDistributed:tf_layers_esm_timeDistributed,globalMaxPool1d:tf_layers_esm_globalMaxPool1d,globalMaxPool2d:tf_layers_esm_globalMaxPool2d,maxPool1d:tf_layers_esm_maxPool1d,maxPool2d:tf_layers_esm_maxPool2d,Layer:tf_layers_esm_Layer,RNN:tf_layers_esm_RNN,RNNCell:tf_layers_esm_RNNCell,input:tf_layers_esm_input,gaussianNoise:tf_layers_esm_gaussianNoise,gaussianDropout:tf_layers_esm_gaussianDropout,alphaDropout:tf_layers_esm_alphaDropout,masking:tf_layers_esm_masking});function tf_layers_esm_binaryAccuracy$1(e,t){return tf_layers_esm_binaryAccuracy(e,t)}function tf_layers_esm_binaryCrossentropy$2(e,t){return tf_layers_esm_binaryCrossentropy$1(e,t)}function tf_layers_esm_sparseCategoricalAccuracy$1(e,t){return tf_layers_esm_sparseCategoricalAccuracy(e,t)}function tf_layers_esm_categoricalAccuracy$1(e,t){return tf_layers_esm_categoricalAccuracy(e,t)}function tf_layers_esm_categoricalCrossentropy$2(e,t){return tf_layers_esm_categoricalCrossentropy$1(e,t)}function tf_layers_esm_precision$1(e,t){return tf_layers_esm_precision(e,t)}function tf_layers_esm_recall$1(e,t){return tf_layers_esm_recall(e,t)}function tf_layers_esm_cosineProximity$1(e,t){return tf_layers_esm_cosineProximity(e,t)}function tf_layers_esm_meanAbsoluteError$1(e,t){return tf_layers_esm_meanAbsoluteError(e,t)}function tf_layers_esm_meanAbsolutePercentageError$1(e,t){return tf_layers_esm_meanAbsolutePercentageError(e,t)}function tf_layers_esm_MAPE$2(e,t){return tf_layers_esm_meanAbsolutePercentageError(e,t)}function tf_layers_esm_mape$2(e,t){return tf_layers_esm_meanAbsolutePercentageError(e,t)}function tf_layers_esm_meanSquaredError$1(e,t){return tf_layers_esm_meanSquaredError(e,t)}function tf_layers_esm_MSE$2(e,t){return tf_layers_esm_meanSquaredError(e,t)}function tf_layers_esm_mse$2(e,t){return tf_layers_esm_meanSquaredError(e,t)}var tf_layers_esm_exports_metrics=Object.freeze({binaryAccuracy:tf_layers_esm_binaryAccuracy$1,binaryCrossentropy:tf_layers_esm_binaryCrossentropy$2,sparseCategoricalAccuracy:tf_layers_esm_sparseCategoricalAccuracy$1,categoricalAccuracy:tf_layers_esm_categoricalAccuracy$1,categoricalCrossentropy:tf_layers_esm_categoricalCrossentropy$2,precision:tf_layers_esm_precision$1,recall:tf_layers_esm_recall$1,cosineProximity:tf_layers_esm_cosineProximity$1,meanAbsoluteError:tf_layers_esm_meanAbsoluteError$1,meanAbsolutePercentageError:tf_layers_esm_meanAbsolutePercentageError$1,MAPE:tf_layers_esm_MAPE$2,mape:tf_layers_esm_mape$2,meanSquaredError:tf_layers_esm_meanSquaredError$1,MSE:tf_layers_esm_MSE$2,mse:tf_layers_esm_mse$2}),tf_layers_esm_exports_models=Object.freeze({modelFromJSON:tf_layers_esm_modelFromJSON});function tf_layers_esm_l1l2(e){return new tf_layers_esm_L1L2(e)}function tf_layers_esm_l1$1(e){return tf_layers_esm_l1(e)}function tf_layers_esm_l2$1(e){return tf_layers_esm_l2(e)}var tf_layers_esm_exports_regularizers=Object.freeze({l1l2:tf_layers_esm_l1l2,l1:tf_layers_esm_l1$1,l2:tf_layers_esm_l2$1}),tf_layers_esm_Callback=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.model=null,t}return tf_layers_esm_extends(t,e),t.prototype.setModel=function(e){if(!(e instanceof tf_layers_esm_LayersModel))throw new Error("model must be a LayersModel, not some other Container");this.model=e},t}(tf_layers_esm_BaseCallback);function tf_layers_esm_less(e,t){return e<t}function tf_layers_esm_greater$1(e,t){return e>t}var tf_layers_esm_EarlyStopping=function(e){function t(t){var n=e.call(this)||this;if(null==t&&(t={}),t.restoreBestWeights)throw new tf_layers_esm_NotImplementedError("restoreBestWeights = True is not implemented in EarlyStopping yet.");return n.monitor=t.monitor||"val_loss",n.minDelta=Math.abs(t.minDelta||0),n.patience=t.patience||0,n.verbose=t.verbose||0,n.mode=t.mode||"auto",n.baseline=t.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=tf_layers_esm_less:"max"===n.mode?n.monitorFunc=tf_layers_esm_greater$1:-1!==n.monitor.indexOf("acc")?n.monitorFunc=tf_layers_esm_greater$1:n.monitorFunc=tf_layers_esm_less,n.monitorFunc===tf_layers_esm_less&&(n.minDelta*=-1),n}return tf_layers_esm_extends(t,e),t.prototype.onTrainBegin=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===tf_layers_esm_less?1/0:-1/0,[2]})})},t.prototype.onEpochEnd=function(e,t){return tf_layers_esm_awaiter(this,void 0,void 0,function(){var n;return tf_layers_esm_generator(this,function(r){switch(r.label){case 0:return[4,tf_layers_esm_resolveScalarsInLogs(t)];case 1:return r.sent(),null==(n=this.getMonitorValue(t))?[2]:(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)),[2])}})})},t.prototype.onTrainEnd=function(e){return tf_layers_esm_awaiter(this,void 0,void 0,function(){return tf_layers_esm_generator(this,function(e){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},t.prototype.getMonitorValue=function(e){null==e&&(e={});var t=e[this.monitor];return null==t&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. Available metrics are: "+Object.keys(e)),t},t}(tf_layers_esm_Callback);function tf_layers_esm_earlyStopping(e){return new tf_layers_esm_EarlyStopping(e)}var tf_layers_esm_callbacks={earlyStopping:tf_layers_esm_earlyStopping};
//# sourceMappingURL=tf-layers.esm.js.map
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-converter/dist/tf-converter.esm.js
var tf_converter_esm = __webpack_require__(20);
// EXTERNAL MODULE: ./node_modules/@tensorflow/tfjs-data/dist/tf-data.esm.js
var tf_data_esm = __webpack_require__(137);
// CONCATENATED MODULE: ./node_modules/@tensorflow/tfjs/dist/tf.esm.js
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return tf_esm_version$1; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "AdadeltaOptimizer", function() { return tf_core_esm["AdadeltaOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "AdagradOptimizer", function() { return tf_core_esm["AdagradOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "AdamOptimizer", function() { return tf_core_esm["AdamOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "AdamaxOptimizer", function() { return tf_core_esm["AdamaxOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Add", function() { return tf_core_esm["Add"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "AddN", function() { return tf_core_esm["AddN"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "BroadcastTo", function() { return tf_core_esm["BroadcastTo"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DataStorage", function() { return tf_core_esm["DataStorage"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Div", function() { return tf_core_esm["Div"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ENV", function() { return tf_core_esm["ENV"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Environment", function() { return tf_core_esm["Environment"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FromPixels", function() { return tf_core_esm["FromPixels"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FusedBatchNorm", function() { return tf_core_esm["FusedBatchNorm"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Identity", function() { return tf_core_esm["Identity"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "KernelBackend", function() { return tf_core_esm["KernelBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "MaxPoolWithArgmax", function() { return tf_core_esm["MaxPoolWithArgmax"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "MomentumOptimizer", function() { return tf_core_esm["MomentumOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "NonMaxSuppressionV5", function() { return tf_core_esm["NonMaxSuppressionV5"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "OneHot", function() { return tf_core_esm["OneHot"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Optimizer", function() { return tf_core_esm["Optimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "PadV2", function() { return tf_core_esm["PadV2"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "RMSPropOptimizer", function() { return tf_core_esm["RMSPropOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Rank", function() { return tf_core_esm["Rank"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Reduction", function() { return tf_core_esm["Reduction"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "SGDOptimizer", function() { return tf_core_esm["SGDOptimizer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Square", function() { return tf_core_esm["Square"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "SquaredDifference", function() { return tf_core_esm["SquaredDifference"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Tensor", function() { return tf_core_esm["Tensor"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "TensorBuffer", function() { return tf_core_esm["TensorBuffer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Tile", function() { return tf_core_esm["Tile"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Transpose", function() { return tf_core_esm["Transpose"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Variable", function() { return tf_core_esm["Variable"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "abs", function() { return tf_core_esm["abs"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "acos", function() { return tf_core_esm["acos"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "acosh", function() { return tf_core_esm["acosh"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "add", function() { return tf_core_esm["add"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "addN", function() { return tf_core_esm["addN"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "addStrict", function() { return tf_core_esm["addStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "all", function() { return tf_core_esm["all"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "any", function() { return tf_core_esm["any"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "argMax", function() { return tf_core_esm["argMax"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "argMin", function() { return tf_core_esm["argMin"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "asin", function() { return tf_core_esm["asin"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "asinh", function() { return tf_core_esm["asinh"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "atan", function() { return tf_core_esm["atan"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "atan2", function() { return tf_core_esm["atan2"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "atanh", function() { return tf_core_esm["atanh"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "avgPool", function() { return tf_core_esm["avgPool"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "avgPool3d", function() { return tf_core_esm["avgPool3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "backend", function() { return tf_core_esm["backend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "backend_util", function() { return tf_core_esm["backend_util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "basicLSTMCell", function() { return tf_core_esm["basicLSTMCell"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNorm", function() { return tf_core_esm["batchNorm"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNorm2d", function() { return tf_core_esm["batchNorm2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNorm3d", function() { return tf_core_esm["batchNorm3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNorm4d", function() { return tf_core_esm["batchNorm4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNormalization", function() { return tf_core_esm["batchNormalization"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNormalization2d", function() { return tf_core_esm["batchNormalization2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNormalization3d", function() { return tf_core_esm["batchNormalization3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchNormalization4d", function() { return tf_core_esm["batchNormalization4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "batchToSpaceND", function() { return tf_core_esm["batchToSpaceND"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "booleanMaskAsync", function() { return tf_core_esm["booleanMaskAsync"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "broadcastTo", function() { return tf_core_esm["broadcastTo"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "browser", function() { return tf_core_esm["browser"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "buffer", function() { return tf_core_esm["buffer"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "cast", function() { return tf_core_esm["cast"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ceil", function() { return tf_core_esm["ceil"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "clipByValue", function() { return tf_core_esm["clipByValue"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "clone", function() { return tf_core_esm["clone"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "complex", function() { return tf_core_esm["complex"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "concat", function() { return tf_core_esm["concat"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "concat1d", function() { return tf_core_esm["concat1d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "concat2d", function() { return tf_core_esm["concat2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "concat3d", function() { return tf_core_esm["concat3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "concat4d", function() { return tf_core_esm["concat4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "conv1d", function() { return tf_core_esm["conv1d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "conv2d", function() { return tf_core_esm["conv2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "conv2dTranspose", function() { return tf_core_esm["conv2dTranspose"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "conv3d", function() { return tf_core_esm["conv3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "conv3dTranspose", function() { return tf_core_esm["conv3dTranspose"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "cos", function() { return tf_core_esm["cos"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "cosh", function() { return tf_core_esm["cosh"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "cumsum", function() { return tf_core_esm["cumsum"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "customGrad", function() { return tf_core_esm["customGrad"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "deprecationWarn", function() { return tf_core_esm["deprecationWarn"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "depthToSpace", function() { return tf_core_esm["depthToSpace"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "depthwiseConv2d", function() { return tf_core_esm["depthwiseConv2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "diag", function() { return tf_core_esm["diag"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "disableDeprecationWarnings", function() { return tf_core_esm["disableDeprecationWarnings"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "dispose", function() { return tf_core_esm["dispose"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "disposeVariables", function() { return tf_core_esm["disposeVariables"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "div", function() { return tf_core_esm["div"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "divNoNan", function() { return tf_core_esm["divNoNan"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "divStrict", function() { return tf_core_esm["divStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "dot", function() { return tf_core_esm["dot"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "dropout", function() { return tf_core_esm["dropout"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "elu", function() { return tf_core_esm["elu"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "enableDebugMode", function() { return tf_core_esm["enableDebugMode"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "enableProdMode", function() { return tf_core_esm["enableProdMode"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "engine", function() { return tf_core_esm["engine"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "env", function() { return tf_core_esm["env"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "equal", function() { return tf_core_esm["equal"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "equalStrict", function() { return tf_core_esm["equalStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "erf", function() { return tf_core_esm["erf"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "exp", function() { return tf_core_esm["exp"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "expandDims", function() { return tf_core_esm["expandDims"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "expm1", function() { return tf_core_esm["expm1"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "eye", function() { return tf_core_esm["eye"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fft", function() { return tf_core_esm["fft"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fill", function() { return tf_core_esm["fill"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "findBackend", function() { return tf_core_esm["findBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "findBackendFactory", function() { return tf_core_esm["findBackendFactory"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "floor", function() { return tf_core_esm["floor"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "floorDiv", function() { return tf_core_esm["floorDiv"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "frame", function() { return tf_core_esm["frame"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fused", function() { return tf_core_esm["fused"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "gather", function() { return tf_core_esm["gather"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "gatherND", function() { return tf_core_esm["gatherND"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "gather_util", function() { return tf_core_esm["gather_util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "getBackend", function() { return tf_core_esm["getBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "getGradient", function() { return tf_core_esm["getGradient"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "getKernel", function() { return tf_core_esm["getKernel"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "getKernelsForBackend", function() { return tf_core_esm["getKernelsForBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "grad", function() { return tf_core_esm["grad"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "grads", function() { return tf_core_esm["grads"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "greater", function() { return tf_core_esm["greater"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "greaterEqual", function() { return tf_core_esm["greaterEqual"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "greaterEqualStrict", function() { return tf_core_esm["greaterEqualStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "greaterStrict", function() { return tf_core_esm["greaterStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "hammingWindow", function() { return tf_core_esm["hammingWindow"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "hannWindow", function() { return tf_core_esm["hannWindow"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ifft", function() { return tf_core_esm["ifft"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "imag", function() { return tf_core_esm["imag"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "image", function() { return tf_core_esm["image"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "inTopKAsync", function() { return tf_core_esm["inTopKAsync"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "io", function() { return tf_core_esm["io"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "irfft", function() { return tf_core_esm["irfft"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isFinite", function() { return tf_core_esm["isFinite"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isInf", function() { return tf_core_esm["isInf"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isNaN", function() { return tf_core_esm["isNaN"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "keep", function() { return tf_core_esm["keep"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "leakyRelu", function() { return tf_core_esm["leakyRelu"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "less", function() { return tf_core_esm["less"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "lessEqual", function() { return tf_core_esm["lessEqual"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "lessEqualStrict", function() { return tf_core_esm["lessEqualStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "lessStrict", function() { return tf_core_esm["lessStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "linalg", function() { return tf_core_esm["linalg"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "linspace", function() { return tf_core_esm["linspace"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "localResponseNormalization", function() { return tf_core_esm["localResponseNormalization"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "log", function() { return tf_core_esm["log"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "log1p", function() { return tf_core_esm["log1p"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logSigmoid", function() { return tf_core_esm["logSigmoid"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logSoftmax", function() { return tf_core_esm["logSoftmax"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logSumExp", function() { return tf_core_esm["logSumExp"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logicalAnd", function() { return tf_core_esm["logicalAnd"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logicalNot", function() { return tf_core_esm["logicalNot"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logicalOr", function() { return tf_core_esm["logicalOr"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "logicalXor", function() { return tf_core_esm["logicalXor"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "losses", function() { return tf_core_esm["losses"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "matMul", function() { return tf_core_esm["matMul"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "math", function() { return tf_core_esm["math"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "max", function() { return tf_core_esm["max"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "maxPool", function() { return tf_core_esm["maxPool"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "maxPool3d", function() { return tf_core_esm["maxPool3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "maxPoolWithArgmax", function() { return tf_core_esm["maxPoolWithArgmax"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "maximum", function() { return tf_core_esm["maximum"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "maximumStrict", function() { return tf_core_esm["maximumStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "mean", function() { return tf_core_esm["mean"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "memory", function() { return tf_core_esm["memory"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "min", function() { return tf_core_esm["min"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "minimum", function() { return tf_core_esm["minimum"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "minimumStrict", function() { return tf_core_esm["minimumStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "mod", function() { return tf_core_esm["mod"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "modStrict", function() { return tf_core_esm["modStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "moments", function() { return tf_core_esm["moments"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "movingAverage", function() { return tf_core_esm["movingAverage"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "mul", function() { return tf_core_esm["mul"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "mulStrict", function() { return tf_core_esm["mulStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "multiRNNCell", function() { return tf_core_esm["multiRNNCell"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "multinomial", function() { return tf_core_esm["multinomial"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "neg", function() { return tf_core_esm["neg"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "nextFrame", function() { return tf_core_esm["nextFrame"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "norm", function() { return tf_core_esm["norm"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "notEqual", function() { return tf_core_esm["notEqual"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "notEqualStrict", function() { return tf_core_esm["notEqualStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "oneHot", function() { return tf_core_esm["oneHot"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ones", function() { return tf_core_esm["ones"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "onesLike", function() { return tf_core_esm["onesLike"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "op", function() { return tf_core_esm["op"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "outerProduct", function() { return tf_core_esm["outerProduct"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pad", function() { return tf_core_esm["pad"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pad1d", function() { return tf_core_esm["pad1d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pad2d", function() { return tf_core_esm["pad2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pad3d", function() { return tf_core_esm["pad3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pad4d", function() { return tf_core_esm["pad4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pool", function() { return tf_core_esm["pool"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "pow", function() { return tf_core_esm["pow"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "powStrict", function() { return tf_core_esm["powStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "prelu", function() { return tf_core_esm["prelu"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "print", function() { return tf_core_esm["print"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "prod", function() { return tf_core_esm["prod"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "profile", function() { return tf_core_esm["profile"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "rand", function() { return tf_core_esm["rand"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "randomGamma", function() { return tf_core_esm["randomGamma"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "randomNormal", function() { return tf_core_esm["randomNormal"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "randomUniform", function() { return tf_core_esm["randomUniform"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "range", function() { return tf_core_esm["range"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ready", function() { return tf_core_esm["ready"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "real", function() { return tf_core_esm["real"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reciprocal", function() { return tf_core_esm["reciprocal"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "registerBackend", function() { return tf_core_esm["registerBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "registerGradient", function() { return tf_core_esm["registerGradient"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "registerKernel", function() { return tf_core_esm["registerKernel"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "relu", function() { return tf_core_esm["relu"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "relu6", function() { return tf_core_esm["relu6"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "removeBackend", function() { return tf_core_esm["removeBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reshape", function() { return tf_core_esm["reshape"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reverse", function() { return tf_core_esm["reverse"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reverse1d", function() { return tf_core_esm["reverse1d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reverse2d", function() { return tf_core_esm["reverse2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reverse3d", function() { return tf_core_esm["reverse3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "reverse4d", function() { return tf_core_esm["reverse4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "rfft", function() { return tf_core_esm["rfft"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "round", function() { return tf_core_esm["round"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "rsqrt", function() { return tf_core_esm["rsqrt"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "scalar", function() { return tf_core_esm["scalar"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "scatterND", function() { return tf_core_esm["scatterND"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "scatter_util", function() { return tf_core_esm["scatter_util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "selu", function() { return tf_core_esm["selu"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "separableConv2d", function() { return tf_core_esm["separableConv2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "serialization", function() { return tf_core_esm["serialization"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "setBackend", function() { return tf_core_esm["setBackend"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "setPlatform", function() { return tf_core_esm["setPlatform"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "setdiff1dAsync", function() { return tf_core_esm["setdiff1dAsync"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sigmoid", function() { return tf_core_esm["sigmoid"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sign", function() { return tf_core_esm["sign"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "signal", function() { return tf_core_esm["signal"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sin", function() { return tf_core_esm["sin"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sinh", function() { return tf_core_esm["sinh"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "slice", function() { return tf_core_esm["slice"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "slice1d", function() { return tf_core_esm["slice1d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "slice2d", function() { return tf_core_esm["slice2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "slice3d", function() { return tf_core_esm["slice3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "slice4d", function() { return tf_core_esm["slice4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "slice_util", function() { return tf_core_esm["slice_util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "softmax", function() { return tf_core_esm["softmax"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "softplus", function() { return tf_core_esm["softplus"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "spaceToBatchND", function() { return tf_core_esm["spaceToBatchND"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sparseToDense", function() { return tf_core_esm["sparseToDense"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "spectral", function() { return tf_core_esm["spectral"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "split", function() { return tf_core_esm["split"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sqrt", function() { return tf_core_esm["sqrt"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "square", function() { return tf_core_esm["square"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "squaredDifference", function() { return tf_core_esm["squaredDifference"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "squaredDifferenceStrict", function() { return tf_core_esm["squaredDifferenceStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "squeeze", function() { return tf_core_esm["squeeze"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "stack", function() { return tf_core_esm["stack"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "step", function() { return tf_core_esm["step"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "stft", function() { return tf_core_esm["stft"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "stridedSlice", function() { return tf_core_esm["stridedSlice"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sub", function() { return tf_core_esm["sub"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "subStrict", function() { return tf_core_esm["subStrict"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sum", function() { return tf_core_esm["sum"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sumOutType", function() { return tf_core_esm["sumOutType"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tan", function() { return tf_core_esm["tan"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tanh", function() { return tf_core_esm["tanh"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor", function() { return tf_core_esm["tensor"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor1d", function() { return tf_core_esm["tensor1d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor2d", function() { return tf_core_esm["tensor2d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor3d", function() { return tf_core_esm["tensor3d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor4d", function() { return tf_core_esm["tensor4d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor5d", function() { return tf_core_esm["tensor5d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor6d", function() { return tf_core_esm["tensor6d"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tensor_util", function() { return tf_core_esm["tensor_util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "test_util", function() { return tf_core_esm["test_util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tidy", function() { return tf_core_esm["tidy"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tile", function() { return tf_core_esm["tile"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "time", function() { return tf_core_esm["time"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "topk", function() { return tf_core_esm["topk"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "train", function() { return tf_core_esm["train"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "transpose", function() { return tf_core_esm["transpose"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "truncatedNormal", function() { return tf_core_esm["truncatedNormal"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "unregisterGradient", function() { return tf_core_esm["unregisterGradient"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "unregisterKernel", function() { return tf_core_esm["unregisterKernel"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "unsortedSegmentSum", function() { return tf_core_esm["unsortedSegmentSum"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "unstack", function() { return tf_core_esm["unstack"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "util", function() { return tf_core_esm["util"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "valueAndGrad", function() { return tf_core_esm["valueAndGrad"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "valueAndGrads", function() { return tf_core_esm["valueAndGrads"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "variable", function() { return tf_core_esm["variable"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "variableGrads", function() { return tf_core_esm["variableGrads"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "version_core", function() { return tf_core_esm["version_core"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "webgl", function() { return tf_core_esm["webgl"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "where", function() { return tf_core_esm["where"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "whereAsync", function() { return tf_core_esm["whereAsync"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "zeros", function() { return tf_core_esm["zeros"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "zerosLike", function() { return tf_core_esm["zerosLike"]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "constraints", function() { return tf_layers_esm_exports_constraints; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "initializers", function() { return tf_layers_esm_exports_initializers; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "layers", function() { return tf_layers_esm_exports_layers; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "metrics", function() { return tf_layers_esm_exports_metrics; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "models", function() { return tf_layers_esm_exports_models; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "regularizers", function() { return tf_layers_esm_exports_regularizers; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "CallbackList", function() { return tf_layers_esm_CallbackList; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "CustomCallback", function() { return tf_layers_esm_CustomCallback; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "History", function() { return tf_layers_esm_History; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Callback", function() { return tf_layers_esm_Callback; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "callbacks", function() { return tf_layers_esm_callbacks; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "EarlyStopping", function() { return tf_layers_esm_EarlyStopping; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "InputSpec", function() { return tf_layers_esm_InputSpec; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "SymbolicTensor", function() { return tf_layers_esm_SymbolicTensor; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "LayersModel", function() { return tf_layers_esm_LayersModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "input", function() { return tf_layers_esm_input; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadLayersModel", function() { return tf_layers_esm_loadLayersModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "model", function() { return tf_layers_esm_model; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "registerCallbackConstructor", function() { return tf_layers_esm_registerCallbackConstructor; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sequential", function() { return tf_layers_esm_sequential; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "RNN", function() { return tf_layers_esm_RNN; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Sequential", function() { return tf_layers_esm_Sequential; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "LayerVariable", function() { return tf_layers_esm_LayerVariable; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "version_layers", function() { return tf_layers_esm_version; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "GraphModel", function() { return tf_converter_esm["a" /* GraphModel */]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadGraphModel", function() { return tf_converter_esm["c" /* loadGraphModel */]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "deregisterOp", function() { return tf_converter_esm["b" /* deregisterOp */]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "registerOp", function() { return tf_converter_esm["d" /* registerOp */]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "version_converter", function() { return tf_converter_esm["e" /* version_converter */]; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "data", function() { return tf_data_esm; });
// @tensorflow/tfjs Copyright 2020 Google
var tf_esm_version="1.7.2",tf_esm_version$1={"tfjs-core":tf_core_esm["version_core"],"tfjs-data":tf_data_esm["version_data"],"tfjs-layers":tf_layers_esm_version,"tfjs-converter":tf_converter_esm["e" /* version_converter */],tfjs:tf_esm_version};
//# sourceMappingURL=tf.esm.js.map
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var core = __webpack_require__(44);
var hide = __webpack_require__(31);
var redefine = __webpack_require__(30);
var ctx = __webpack_require__(43);
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE];
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});
var key, own, out, exp;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if (target) redefine(target, key, out, type & $export.U);
// export
if (exports[key] != out) hide(exports, key, exp);
if (IS_PROTO && expProto[key] != out) expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new _promise2.default(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return _promise2.default.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
}
return step("next");
});
};
};
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(427);
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _defineProperty = __webpack_require__(222);
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
/***/ }),
/* 11 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/* 12 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _iterator = __webpack_require__(410);
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = __webpack_require__(408);
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = callCallback;
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
function callCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(undefined, result);
return result;
}).catch(function (error) {
callback(error);
return error;
});
}
return promise;
}
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(114)('wks');
var uid = __webpack_require__(78);
var Symbol = __webpack_require__(11).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(41);
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/* 18 */
/***/ (function(module, exports) {
var core = module.exports = { version: '2.6.11' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(12)(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GraphModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadGraphModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deregisterOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return registerOp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return version; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 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 DataType,SaverDef,__assign=function(){return(__assign=Object.assign||function(e){for(var t,a=1,r=arguments.length;a<r;a++)for(var n in t=arguments[a])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)};function __awaiter(e,t,a,r){return new(a||(a=Promise))(function(n,s){function o(e){try{u(r.next(e))}catch(e){s(e)}}function p(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){e.done?n(e.value):new a(function(t){t(e.value)}).then(o,p)}u((r=r.apply(e,t||[])).next())})}function __generator(e,t){var a,r,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:p(0),throw:p(1),return:p(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function p(s){return function(p){return function(s){if(a)throw new TypeError("Generator is already executing.");for(;o;)try{if(a=1,r&&(n=2&s[0]?r.return:s[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,s[1])).done)return n;switch(r=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(n=(n=o.trys).length>0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){o.label=s[1];break}if(6===s[0]&&o.label<n[1]){o.label=n[1],n=s;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(s);break}n[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{a=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,p])}}}!function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(DataType||(DataType={})),function(e){!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(SaverDef||(SaverDef={}));var CUSTOM_OPS={};function registerOp(e,t){var a={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};CUSTOM_OPS[e]=a}function getRegisteredOp(e){return CUSTOM_OPS[e]}function deregisterOp(e){delete CUSTOM_OPS[e]}function getParamValue(e,t,a,r){var n=t.inputParams[e];if(n&&void 0!==n.inputIndexStart){var s=n.inputIndexStart,o=0===n.inputIndexEnd?void 0:void 0===n.inputIndexEnd?s+1:n.inputIndexEnd;if("tensor"===n.type)return getTensor(t.inputNames[n.inputIndexStart],a,r);if("tensors"===n.type)return t.inputNames.slice(s,o).map(function(e){return getTensor(e,a,r)});var p=Array.prototype.slice.call(getTensor(t.inputNames.slice(s)[0],a,r).dataSync());return"number"===n.type?p[0]:p}var u=t.attrParams[e];return u&&u.value}function getTensor(e,t,a){var r=parseNodeName(e),n=r[0],s=r[1],o=a.currentContextIds.find(function(e){return!!t[getNodeNameWithContextId(n,e)]});return void 0!==o?t[getNodeNameWithContextId(n,o)][s]:void 0}function getTensorsForCurrentContenxt(e,t,a){return t[getNodeNameWithContextId(e,a.currentContextId)]}function getNodeNameAndIndex(e,t){var a=parseNodeName(e),r=a[0],n=a[1];return[getNodeNameWithContextId(r,t&&t.currentContextId),n]}function getNodeNameWithContextId(e,t){return t?e+"-"+t:e}function parseNodeName(e){var t=e.lastIndexOf(":");return-1===t?[e,0]:[e.substring(0,t),Number(e.substring(t+1))]}function split$1(e,t){for(var a=[],r=0;r<e.length;r+=t)a.push(e.slice(r,r+t));return a}var json=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],arithmetic=Object.freeze({json:json}),json$1=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],basicMath=Object.freeze({json:json$1}),json$2=[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"}]}],control=Object.freeze({json:json$2}),json$3=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]}],convolution=Object.freeze({json:json$3}),json$4=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],creation=Object.freeze({json:json$4}),json$5=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],dynamic=Object.freeze({json:json$5}),json$6=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}],evaluation=Object.freeze({json:json$6}),json$7=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],graph=Object.freeze({json:json$7}),json$8=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}],image$1=Object.freeze({json:json$8}),json$9=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],logical=Object.freeze({json:json$9}),json$10=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],matrices=Object.freeze({json:json$10}),json$11=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],normalization=Object.freeze({json:json$11}),json$12=[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]}],reduction=Object.freeze({json:json$12}),json$13=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],sliceJoin=Object.freeze({json:json$13}),json$14=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],spectral=Object.freeze({json:json$14}),json$15=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]}],transformation=Object.freeze({json:json$15}),OperationMapper=function(){function e(){var e=[arithmetic,basicMath,control,convolution,creation,dynamic,evaluation,logical,image$1,graph,matrices,normalization,reduction,sliceJoin,spectral,transformation],t=[].concat.apply([],e.map(function(e){return e.json}));this.opMappers=t.reduce(function(e,t){return e[t.tfOpName]=t,e},{})}return Object.defineProperty(e,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),e.prototype.transformGraph=function(e,t){var a=this;void 0===t&&(t={});var r=[],n=[],s=e.node.reduce(function(e,t){return e[t.name]=a.mapNode(t),t.op.startsWith("Placeholder")&&r.push(e[t.name]),"Const"===t.op&&n.push(e[t.name]),e},{}),o=[],p=[],u={},i={};null!=t&&(u=this.mapSignatureEntries(t.inputs),i=this.mapSignatureEntries(t.outputs));var m=Object.keys(s);return m.forEach(function(e){var t=s[e];t.inputNames.forEach(function(e){var a=getNodeNameAndIndex(e)[0];t.inputs.push(s[a]),s[a].children.push(t)})}),0===Object.keys(i).length?m.forEach(function(e){var t=s[e];0===t.children.length&&p.push(t)}):Object.keys(i).forEach(function(e){var t=getNodeNameAndIndex(e)[0],a=s[t];null!=a&&(a.signatureKey=i[e],p.push(a))}),Object.keys(u).length>0?Object.keys(u).forEach(function(e){var t=getNodeNameAndIndex(e)[0],a=s[t];a&&(a.signatureKey=u[e],o.push(a))}):o=r,{nodes:s,inputs:o,outputs:p,weights:n,placeholders:r,signature:t}},e.prototype.mapSignatureEntries=function(e){return Object.keys(e||{}).reduce(function(t,a){return t[e[a].name]=a,t},{})},e.prototype.mapNode=function(e){var t=getRegisteredOp(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});var a={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(function(e){return e.startsWith("^")?e.substr(1):e}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return null!=t.inputs&&(a.inputParams=t.inputs.reduce(function(e,t){return e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e},{})),null!=t.attrs&&(a.attrParams=t.attrs.reduce(function(t,a){var r=a.type,n=void 0;switch(a.type){case"string":void 0===(n=getStringParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getStringParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":void 0===(n=getStringArrayParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getStringArrayParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":void 0===(n=getNumberParam(e.attr,a.tfName,a.defaultValue||0))&&a.tfDeprecatedName&&(n=getNumberParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":void 0===(n=getNumericArrayParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getNumericArrayParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":void 0===(n=getBoolParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getBoolParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":void 0===(n=getBoolArrayParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getBoolArrayParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":void 0===(n=getTensorShapeParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getTensorShapeParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":void 0===(n=getTensorShapeArrayParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getTensorShapeArrayParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":void 0===(n=getDtypeParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getDtypeParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":void 0===(n=getDtypeArrayParam(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=getDtypeArrayParam(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+a.type+" for op: "+e.op)}return t[a.name]={value:n,type:r},t},{})),a},e}();function decodeBase64(e){var t=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function parseStringParam(e,t){var a=Array.isArray(e)?String.fromCharCode.apply(null,e):decodeBase64(e);return t?a:a.toLowerCase()}function getStringParam(e,t,a,r){void 0===r&&(r=!1);var n=e[t];return null!=n?parseStringParam(n.s,r):a}function getBoolParam(e,t,a){var r=e[t];return r?r.b:a}function getNumberParam(e,t,a){var r=e[t]||{},n=null!=r.i?r.i:null!=r.f?r.f:a;return"number"==typeof n?n:parseInt(n,10)}function parseDtypeParam(e){switch("string"==typeof e&&(e=DataType[e]),e){case DataType.DT_FLOAT:return"float32";case DataType.DT_INT32:case DataType.DT_INT64:case DataType.DT_INT8:case DataType.DT_UINT8:return"int32";case DataType.DT_BOOL:return"bool";case DataType.DT_DOUBLE:return"float32";case DataType.DT_STRING:return"string";default:return null}}function getDtypeParam(e,t,a){var r=e[t];return r&&r.type?parseDtypeParam(r.type):a}function getDtypeArrayParam(e,t,a){var r=e[t];return r&&r.list&&r.list.type?r.list.type.map(function(e){return parseDtypeParam(e)}):a}function parseTensorShapeParam(e){if(!e.unknownRank)return null!=e.dim?e.dim.map(function(e){return"number"==typeof e.size?e.size:parseInt(e.size,10)}):[]}function getTensorShapeParam(e,t,a){var r=e[t];return r&&r.shape?parseTensorShapeParam(r.shape):a}function getNumericArrayParam(e,t,a){var r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(function(e){return"number"==typeof e?e:parseInt(e,10)}):a}function getStringArrayParam(e,t,a,r){void 0===r&&(r=!1);var n=e[t];return n&&n.list&&n.list.s?n.list.s.map(function(e){return parseStringParam(e,r)}):a}function getTensorShapeArrayParam(e,t,a){var r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(function(e){return parseTensorShapeParam(e)}):a}function getBoolArrayParam(e,t,a){var r=e[t];return r&&r.list&&r.list.b?r.list.b:a}var NodeValueImpl=function(){function e(e,t,a){var r=this;this.node=e,this.tensorMap=t,this.context=a,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(function(e){return r.getInput(e)}),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(function(e,t){return e[t]=r.getAttr(t),e},{}))}return e.prototype.getInput=function(e){return getTensor(e,this.tensorMap,this.context)},e.prototype.getAttr=function(e,t){var a=this.node.rawAttrs[e];if(null!=a.tensor)return getTensor(e,this.tensorMap,this.context);if(null!=a.i||null!=a.f)return getNumberParam(this.node.rawAttrs,e,t);if(null!=a.s)return getStringParam(this.node.rawAttrs,e,t);if(null!=a.b)return getBoolParam(this.node.rawAttrs,e,t);if(null!=a.shape)return getTensorShapeParam(this.node.rawAttrs,e,t);if(null!=a.type)return getDtypeParam(this.node.rawAttrs,e,t);if(null!=a.list){if(null!=a.list.i||null!=a.list.f)return getNumericArrayParam(this.node.rawAttrs,e,t);if(null!=a.list.s)return getStringArrayParam(this.node.rawAttrs,e,t);if(null!=a.list.shape)return getTensorShapeArrayParam(this.node.rawAttrs,e,t);if(null!=a.list.b)return getBoolArrayParam(this.node.rawAttrs,e,t);if(null!=a.list.type)return getDtypeArrayParam(this.node.rawAttrs,e,t)}return t},e}(),executeOp=function(e,t,a){switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"AddN":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["addN"])(getParamValue("tensors",e,t,a))];case"FloorMod":case"Mod":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mod"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Mul":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"RealDiv":case"Div":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"DivNoNan":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["divNoNan"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"FloorDiv":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["floorDiv"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Sub":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Minimum":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["minimum"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Maximum":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["maximum"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Pow":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["pow"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"SquaredDifference":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["squaredDifference"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$1=function(e,t,a){switch(e.op){case"Abs":case"ComplexAbs":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["abs"])(getParamValue("x",e,t,a))];case"Acos":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["acos"])(getParamValue("x",e,t,a))];case"Acosh":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["acosh"])(getParamValue("x",e,t,a))];case"Asin":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["asin"])(getParamValue("x",e,t,a))];case"Asinh":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["asinh"])(getParamValue("x",e,t,a))];case"Atan":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["atan"])(getParamValue("x",e,t,a))];case"Atan2":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["atan2"])(getParamValue("x",e,t,a),getParamValue("y",e,t,a))];case"Atanh":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["atanh"])(getParamValue("x",e,t,a))];case"Ceil":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["ceil"])(getParamValue("x",e,t,a))];case"Complex":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["complex"])(getParamValue("real",e,t,a),getParamValue("imag",e,t,a))];case"Cos":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["cos"])(getParamValue("x",e,t,a))];case"Cosh":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["cosh"])(getParamValue("x",e,t,a))];case"Elu":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["elu"])(getParamValue("x",e,t,a))];case"Erf":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["erf"])(getParamValue("x",e,t,a))];case"Exp":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["exp"])(getParamValue("x",e,t,a))];case"Expm1":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["expm1"])(getParamValue("x",e,t,a))];case"Floor":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["floor"])(getParamValue("x",e,t,a))];case"Log":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["log"])(getParamValue("x",e,t,a))];case"Log1p":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["log1p"])(getParamValue("x",e,t,a))];case"Imag":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["imag"])(getParamValue("x",e,t,a))];case"Neg":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["neg"])(getParamValue("x",e,t,a))];case"Reciprocal":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["reciprocal"])(getParamValue("x",e,t,a))];case"Real":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["real"])(getParamValue("x",e,t,a))];case"Relu":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["relu"])(getParamValue("x",e,t,a))];case"Round":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["round"])(getParamValue("x",e,t,a))];case"Selu":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["selu"])(getParamValue("x",e,t,a))];case"Sigmoid":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sigmoid"])(getParamValue("x",e,t,a))];case"Sin":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sin"])(getParamValue("x",e,t,a))];case"Sign":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sign"])(getParamValue("x",e,t,a))];case"Sinh":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sinh"])(getParamValue("x",e,t,a))];case"Softplus":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["softplus"])(getParamValue("x",e,t,a))];case"Sqrt":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sqrt"])(getParamValue("x",e,t,a))];case"Square":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["square"])(getParamValue("x",e,t,a))];case"Tanh":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tanh"])(getParamValue("x",e,t,a))];case"Tan":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tan"])(getParamValue("x",e,t,a))];case"Relu6":case"ClipByValue":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["clipByValue"])(getParamValue("x",e,t,a),getParamValue("clipValueMin",e,t,a),getParamValue("clipValueMax",e,t,a))];case"Rsqrt":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["rsqrt"])(getTensor(e.inputNames[0],t,a))];case"Prod":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["prod"])(getParamValue("x",e,t,a),getParamValue("axes",e,t,a))];case"LeakyRelu":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["leakyRelu"])(getParamValue("x",e,t,a),getParamValue("alpha",e,t,a))];case"Prelu":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["prelu"])(getParamValue("x",e,t,a),getParamValue("alpha",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},TensorArray=function(){function e(t,a,r,n,s,o,p){this.name=t,this.dtype=a,this.maxSize=r,this.elementShape=n,this.identicalElementShapes=s,this.dynamicSize=o,this.clearAfterRead=p,this.tensors=[],this.closed_=!1,this.id=e.nextId++}return Object.defineProperty(e.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),e.prototype.clearAndClose=function(){this.tensors.forEach(function(e){return e.tensor.dispose()}),this.tensors=[],this.closed_=!0},e.prototype.size=function(){return this.tensors.length},e.prototype.read=function(e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||e>=this.tensors.length)throw new Error("Tried to read from index "+e+", but array size is: "+this.tensors.length);var t=this.tensors[e];if(t.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+e+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor},e.prototype.readMany=function(e){var t=this;return e.map(function(e){return t.read(e)})},e.prototype.write=function(e,t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error("Tried to write to index "+e+", but array is not resizeable and size is: "+this.maxSize);var a=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+",\n because the value dtype is "+t.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,t.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+e+"."),a&&a.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been read.");if(a&&a.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been written.");a.tensor=t,a.written=!0,this.tensors[e]=a},e.prototype.writeMany=function(e,t){var a=this;if(e.length!==t.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+e.length+" is not the same as tensors size: "+t.length+".");e.forEach(function(e,r){return a.write(e,t[r])})},e.prototype.gather=function(e,t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+t);if(!e){e=[];for(var a=0;a<this.size();a++)e.push(a)}if(0===e.length)return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor"])([],[0].concat(this.elementShape));var r=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["stack"])(r,0)},e.prototype.concat=function(e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+e);if(0===this.size())return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor"])([],[0].concat(this.elementShape));for(var t=[],a=0;a<this.size();a++)t.push(a);var r=this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+r[0].shape+")"),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])(r,0)},e.prototype.scatter=function(e,t){if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);if(e.length!==t.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+e.length+" vs. "+t.shape[0]);var a=Math.max.apply(Math,e);if(!this.dynamicSize&&a>=this.maxSize)throw new Error("Max index must be < array size ("+a+" vs. "+this.maxSize+")");this.writeMany(e,Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["unstack"])(t,0))},e.prototype.split=function(e,t){var a=this;if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);var r=0,n=e.map(function(e){return r+=e});if(r!==t.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: "+t.shape);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+e.length+"), and the TensorArray is not marked as dynamically resizeable");var s=0===r?0:t.size/r,o=[];Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){t=t.reshape([1,r,s]);for(var p=0;p<e.length;++p){var u=[0,0===p?0:n[p-1],0],i=[1,e[p],s];o[p]=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(t,u,i).reshape(a.elementShape)}return o});for(var p=[],u=0;u<e.length;u++)p[u]=u;this.writeMany(p,o)},e.prototype.assertShapesMatchAllowUndefinedSize=function(e,t,a){void 0===a&&(a=""),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(this.shapesEqualAllowUndefinedSize(e,t),function(){return a+" Shapes "+e+" and "+t+" must match"})},e.prototype.shapesEqualAllowUndefinedSize=function(e,t){if(e.length!==t.length)return!1;for(var a=0;a<e.length;a++)if(-1!==e[a]&&-1!==t[a]&&e[a]!==t[a])return!1;return!0},e.nextId=0,e}(),_this=void 0,executeOp$2=function(e,t,a){return __awaiter(_this,void 0,void 0,function(){var r,n,s,o,p,u,i,m,l,c,d,y,f,g,h,N,x,V,b,P,T,v,O,S,_,w,A,D,E,I,M,C,k,z,F;return __generator(this,function(j){switch(j.label){case 0:switch(e.op){case"LoopCond":return[3,1];case"Switch":return[3,2];case"Merge":return[3,4];case"Enter":return[3,5];case"Exit":return[3,6];case"NextIteration":return[3,7];case"TensorArrayV3":return[3,8];case"TensorArrayWriteV3":return[3,9];case"TensorArrayReadV3":return[3,10];case"TensorArrayGatherV3":return[3,11];case"TensorArrayScatterV3":return[3,12];case"TensorArrayConcatV3":return[3,13];case"TensorArraySplitV3":return[3,14];case"TensorArraySizeV3":return[3,15];case"TensorArrayCloseV3":return[3,16]}return[3,17];case 1:return[2,[getParamValue("pred",e,t,a).clone()]];case 2:return r=getParamValue("pred",e,t,a),n=getParamValue("data",e,t,a),[4,r.data()];case 3:return[2,j.sent()[0]?[void 0,n.clone()]:[n.clone(),void 0]];case 4:return[2,(s=e.inputNames.find(function(e){return void 0!==getTensor(e,t,a)}))?[getTensor(s,t,a).clone()]:void 0];case 5:return o=getParamValue("frameName",e,t,a),p=getParamValue("tensor",e,t,a),a.enterFrame(o),[2,[p.clone()]];case 6:return u=getParamValue("tensor",e,t,a),a.exitFrame(),[2,[u.clone()]];case 7:return i=getParamValue("tensor",e,t,a),a.nextIteration(),[2,[i.clone()]];case 8:return m=getParamValue("size",e,t,a),l=getParamValue("dtype",e,t,a),c=getParamValue("elementShape",e,t,a),d=getParamValue("dynamicSize",e,t,a),y=getParamValue("clearAfterRead",e,t,a),f=getParamValue("identicalElementShapes",e,t,a),g=getParamValue("name",e,t,a),h=new TensorArray(g,l,m,c,f,d,y),a.addTensorArray(h),[2,[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(h.id),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1)]];case 9:return N=getParamValue("tensorArrayId",e,t,a),x=getParamValue("index",e,t,a),V=getParamValue("tensor",e,t,a),a.getTensorArray(N).write(x,V),[2,[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1)]];case 10:return b=getParamValue("tensorArrayId",e,t,a),P=getParamValue("index",e,t,a),[2,[a.getTensorArray(b).read(P)]];case 11:return T=getParamValue("tensorArrayId",e,t,a),v=getParamValue("indices",e,t,a),O=getParamValue("dtype",e,t,a),[2,[a.getTensorArray(T).gather(v,O)]];case 12:return S=getParamValue("tensorArrayId",e,t,a),_=getParamValue("indices",e,t,a),w=getParamValue("tensor",e,t,a),a.getTensorArray(S).scatter(_,w),[2,[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1)]];case 13:return A=getParamValue("tensorArrayId",e,t,a),D=a.getTensorArray(A),E=getParamValue("dtype",e,t,a),[2,[D.concat(E)]];case 14:return I=getParamValue("tensorArrayId",e,t,a),M=getParamValue("tensor",e,t,a),C=getParamValue("lengths",e,t,a),a.getTensorArray(I).split(C,M),[2,[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1)]];case 15:return k=getParamValue("tensorArrayId",e,t,a),z=a.getTensorArray(k),[2,[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(z.size(),"int32")]];case 16:return F=getParamValue("tensorArrayId",e,t,a),a.getTensorArray(F).clearAndClose(),[2,[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(0)]];case 17:throw TypeError("Node type "+e.op+" is not implemented")}})})},executeOp$3=function(e,t,a){switch(e.op){case"Conv1D":var r=getParamValue("stride",e,t,a),n=getParamValue("pad",e,t,a),s=getParamValue("dataFormat",e,t,a).toUpperCase(),o=getParamValue("dilation",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["conv1d"])(getParamValue("x",e,t,a),getParamValue("filter",e,t,a),r,n,s,o)];case"Conv2D":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),s=getParamValue("dataFormat",e,t,a).toUpperCase();var p=getParamValue("dilations",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["conv2d"])(getParamValue("x",e,t,a),getParamValue("filter",e,t,a),[r[1],r[2]],n,s,[p[1],p[2]])];case"_FusedConv2D":case"FusedDepthwiseConv2dNative":var u=getParamValue("fusedOps",e,t,a),i=u[0],m=u[1],l="biasadd"===i,c="prelu"===m,d="fusedbatchnorm"===i,y=getParamValue("numArgs",e,t,a);if(l){if(c&&2!==y)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!c&&1!==y)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(d)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),s=getParamValue("dataFormat",e,t,a).toUpperCase(),p=getParamValue("dilations",e,t,a);var f=getParamValue("args",e,t,a),g=f[0],h=f[1];return[("_FusedConv2D"===e.op?_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["fused"].conv2d:_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["fused"].depthwiseConv2d)({x:getParamValue("x",e,t,a),filter:getParamValue("filter",e,t,a),strides:[r[1],r[2]],pad:n,dataFormat:s,dilations:[p[1],p[2]],bias:g,activation:m,preluActivationWeights:h})];case"Conv2DBackpropInput":case"Conv2dTranspose":var N=getParamValue("outputShape",e,t,a);r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["conv2dTranspose"])(getParamValue("x",e,t,a),getParamValue("filter",e,t,a),N,[r[1],r[2]],n)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),p=getParamValue("dilations",e,t,a),s=getParamValue("dataFormat",e,t,a).toUpperCase();return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["depthwiseConv2d"])(getParamValue("input",e,t,a),getParamValue("filter",e,t,a),[r[1],r[2]],n,s,[p[1],p[2]])];case"Conv3D":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),s=getParamValue("dataFormat",e,t,a).toUpperCase(),p=getParamValue("dilations",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["conv3d"])(getParamValue("x",e,t,a),getParamValue("filter",e,t,a),[r[1],r[2],r[3]],n,s,[p[1],p[2],p[3]])];case"AvgPool":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a);var x=getParamValue("kernelSize",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["avgPool"])(getParamValue("x",e,t,a),[x[1],x[2]],[r[1],r[2]],n)];case"MaxPool":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),x=getParamValue("kernelSize",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["maxPool"])(getParamValue("x",e,t,a),[x[1],x[2]],[r[1],r[2]],n)];case"MaxPoolWithArgmax":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),x=getParamValue("kernelSize",e,t,a);var V=getParamValue("includeBatchInIndex",e,t,a),b=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["maxPoolWithArgmax"])(getParamValue("x",e,t,a),[x[1],x[2]],[r[1],r[2]],n,V);return[b.result,b.indexes];case"AvgPool3D":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),x=getParamValue("kernelSize",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["avgPool3d"])(getParamValue("x",e,t,a),[x[1],x[2],x[3]],[r[1],r[2],r[3]],n)];case"MaxPool3D":r=getParamValue("strides",e,t,a),n=getParamValue("pad",e,t,a),x=getParamValue("kernelSize",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["maxPool3d"])(getParamValue("x",e,t,a),[x[1],x[2],x[3]],[r[1],r[2],r[3]],n)];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$4=function(e,t,a){switch(e.op){case"Fill":var r=getParamValue("shape",e,t,a),n=getParamValue("dtype",e,t,a),s=getParamValue("value",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["fill"])(r,s,n)];case"LinSpace":var o=getParamValue("start",e,t,a),p=getParamValue("stop",e,t,a),u=getParamValue("num",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["linspace"])(o,p,u)];case"Multinomial":var i=getParamValue("logits",e,t,a),m=getParamValue("numSamples",e,t,a),l=getParamValue("seed",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["multinomial"])(i,m,l)];case"OneHot":var c=getParamValue("indices",e,t,a),d=getParamValue("depth",e,t,a),y=getParamValue("onValue",e,t,a),f=getParamValue("offValue",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["oneHot"])(c,d,y,f)];case"Ones":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["ones"])(getParamValue("shape",e,t,a),getParamValue("dtype",e,t,a))];case"OnesLike":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["onesLike"])(getParamValue("x",e,t,a))];case"RandomUniform":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["randomUniform"])(getParamValue("shape",e,t,a),getParamValue("minval",e,t,a),getParamValue("maxval",e,t,a),getParamValue("dtype",e,t,a))];case"Range":o=getParamValue("start",e,t,a);var g=getParamValue("stop",e,t,a),h=getParamValue("step",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["range"])(o,g,h,getParamValue("dtype",e,t,a))];case"TruncatedNormal":r=getParamValue("shape",e,t,a);var N=getParamValue("mean",e,t,a),x=getParamValue("stdDev",e,t,a);l=getParamValue("seed",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["truncatedNormal"])(r,N,x,getParamValue("dtype",e,t,a),l)];case"Zeros":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["zeros"])(getParamValue("shape",e,t,a),getParamValue("dtype",e,t,a))];case"ZerosLike":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["zerosLike"])(getParamValue("x",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},_this$1=void 0,executeOp$5=function(e,t,a){return __awaiter(_this$1,void 0,void 0,function(){var r,n,s,o,p,u,i,m;return __generator(this,function(l){switch(l.label){case 0:switch(e.op){case"NonMaxSuppressionV5":case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,5];case"ListDiff":return[3,7]}return[3,8];case 1:return r=getParamValue("boxes",e,t,a),n=getParamValue("scores",e,t,a),s=getParamValue("maxOutputSize",e,t,a),o=getParamValue("iouThreshold",e,t,a),p=getParamValue("scoreThreshold",e,t,a),"NonMaxSuppressionV5"!==e.op?[3,3]:(u=getParamValue("softNmsSigma",e,t,a),[4,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].nonMaxSuppressionWithScoreAsync(r,n,s,o,p,u)]);case 2:return[2,[(m=l.sent()).selectedIndices,m.selectedScores]];case 3:return[4,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].nonMaxSuppressionAsync(r,n,s,o,p)];case 4:return[2,[l.sent()]];case 5:return i=getParamValue("condition",e,t,a).asType("bool"),[4,Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["whereAsync"])(i)];case 6:return m=[l.sent()],i.dispose(),[2,m];case 7:return[2,Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["setdiff1dAsync"])(getParamValue("x",e,t,a),getParamValue("y",e,t,a))];case 8:throw TypeError("Node type "+e.op+" is not implemented")}})})},executeOp$6=function(e,t,a){switch(e.op){case"TopKV2":var r=getParamValue("x",e,t,a),n=getParamValue("k",e,t,a),s=getParamValue("sorted",e,t,a),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["topk"])(r,n,s);return[o.values,o.indices];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$7=function(e,t,a){switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":var r=getParamValue("default",e,t,a);return[getTensor(e.name,t,a)||r];case"Placeholder":return[getTensor(e.name,t,a)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[getParamValue("x",e,t,a).clone()];case"IdentityN":return getParamValue("x",e,t,a).map(function(e){return e.clone()});case"Snapshot":return[getParamValue("x",e,t,a).clone()];case"Shape":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])(getParamValue("x",e,t,a).shape,"int32")];case"ShapeN":return getParamValue("x",e,t,a).map(function(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])(e.shape)});case"Size":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(getParamValue("x",e,t,a).size,"int32")];case"Rank":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(getParamValue("x",e,t,a).rank,"int32")];case"NoOp":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1)];case"Print":var n=getParamValue("x",e,t,a),s=getParamValue("data",e,t,a),o=getParamValue("message",e,t,a),p=getParamValue("summarize",e,t,a);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(var u=0;u<s.length;u++)console.log(Array.prototype.slice.call(s[u].dataSync()).slice(0,p));return[n];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$8=function(e,t,a){switch(e.op){case"ResizeBilinear":var r=getParamValue("images",e,t,a),n=getParamValue("size",e,t,a),s=getParamValue("alignCorners",e,t,a);return[_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].resizeBilinear(r,[n[0],n[1]],s)];case"ResizeNearestNeighbor":r=getParamValue("images",e,t,a),n=getParamValue("size",e,t,a),s=getParamValue("alignCorners",e,t,a);return[_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].resizeNearestNeighbor(r,[n[0],n[1]],s)];case"CropAndResize":var o=getParamValue("image",e,t,a),p=getParamValue("boxes",e,t,a),u=getParamValue("boxInd",e,t,a),i=getParamValue("cropSize",e,t,a),m=getParamValue("method",e,t,a),l=getParamValue("extrapolationValue",e,t,a);return[_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].cropAndResize(o,p,u,i,m,l)];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$9=function(e,t,a){switch(e.op){case"Equal":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["equal"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"NotEqual":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["notEqual"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Greater":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["greater"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"GreaterEqual":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["greaterEqual"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Less":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["less"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"LessEqual":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["lessEqual"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"LogicalAnd":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["logicalAnd"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"LogicalNot":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["logicalNot"])(getParamValue("a",e,t,a))];case"LogicalOr":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["logicalOr"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a))];case"Select":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["where"])(getParamValue("condition",e,t,a),getParamValue("a",e,t,a),getParamValue("b",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$10=function(e,t,a){switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["matMul"])(getParamValue("a",e,t,a),getParamValue("b",e,t,a),getParamValue("transposeA",e,t,a),getParamValue("transposeB",e,t,a))];case"Transpose":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["transpose"])(getParamValue("x",e,t,a),getParamValue("perm",e,t,a))];case"_FusedMatMul":var r=getParamValue("fusedOps",e,t,a),n=r[0],s=r[1],o="biasadd"===n,p="prelu"===s,u=getParamValue("numArgs",e,t,a);if(o){if(p&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!p&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}var i=getParamValue("args",e,t,a),m=i[0],l=i[1];return[_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["fused"].matMul({a:getParamValue("a",e,t,a),b:getParamValue("b",e,t,a),transposeA:getParamValue("transposeA",e,t,a),transposeB:getParamValue("transposeB",e,t,a),bias:m,activation:s,preluActivationWeights:l})];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$11=function(e,t,a){switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["batchNorm"])(getParamValue("x",e,t,a),getParamValue("mean",e,t,a),getParamValue("variance",e,t,a),getParamValue("offset",e,t,a),getParamValue("scale",e,t,a),getParamValue("epsilon",e,t,a))];case"LRN":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["localResponseNormalization"])(getParamValue("x",e,t,a),getParamValue("radius",e,t,a),getParamValue("bias",e,t,a),getParamValue("alpha",e,t,a),getParamValue("beta",e,t,a))];case"Softmax":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["softmax"])(getParamValue("x",e,t,a))];case"LogSoftmax":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["logSoftmax"])(getParamValue("x",e,t,a))];case"SparseToDense":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sparseToDense"])(getParamValue("sparseIndices",e,t,a),getParamValue("outputShape",e,t,a),getParamValue("sparseValues",e,t,a),getParamValue("defaultValue",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$12=function(e,t,a){switch(e.op){case"Max":var r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["max"])(getParamValue("x",e,t,a),r,n)];case"Mean":r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mean"])(getParamValue("x",e,t,a),r,n)];case"Min":r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["min"])(getParamValue("x",e,t,a),r,n)];case"Sum":r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sum"])(getParamValue("x",e,t,a),r,n)];case"All":r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["all"])(getParamValue("x",e,t,a),r,n)];case"Any":r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["any"])(getParamValue("x",e,t,a),r,n)];case"ArgMax":r=getParamValue("axis",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["argMax"])(getParamValue("x",e,t,a),r)];case"ArgMin":r=getParamValue("axis",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["argMin"])(getParamValue("x",e,t,a),r)];case"Prod":r=getParamValue("axis",e,t,a),n=getParamValue("keepDims",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["prod"])(getParamValue("x",e,t,a),r,n)];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$13=function(e,t,a){switch(e.op){case"ConcatV2":case"Concat":var r=getParamValue("n",e,t,a),n=getParamValue("axis",e,t,a),s=getParamValue("tensors",e,t,a);return s=s.slice(0,r),[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])(s,n)];case"GatherV2":case"Gather":n=getParamValue("axis",e,t,a);var o=getParamValue("x",e,t,a),p=getParamValue("indices",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["gather"])(o,p.asType("int32"),n)];case"ReverseV2":case"Reverse":n=getParamValue("axis",e,t,a),o=getParamValue("x",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["reverse"])(o,n)];case"Slice":var u=getParamValue("begin",e,t,a),i=getParamValue("size",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(getParamValue("x",e,t,a),u,i)];case"StridedSlice":u=getParamValue("begin",e,t,a);var m=getParamValue("end",e,t,a),l=getParamValue("strides",e,t,a),c=getParamValue("beginMask",e,t,a),d=getParamValue("endMask",e,t,a),y=getParamValue("ellipsisMask",e,t,a),f=getParamValue("newAxisMask",e,t,a),g=getParamValue("shrinkAxisMask",e,t,a),h=getParamValue("x",e,t,a);if(1===u.length&&h.shape.length>1)for(var N=1;N<h.shape.length;N++)u.push(0),m.push(h.shape[N]),l.push(l[0]);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["stridedSlice"])(h,u,m,l,c,d,y,f,g)];case"Pack":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r=getParamValue("axis",e,t,a),n=getParamValue("tensors",e,t,a),s=n[0].shape,o=n[0].squeeze().shape,p=n.map(function(e){var t=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].arraysEqual(e.shape,s);if(!t&&!_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].arraysEqual(e.squeeze().shape,o))throw new Error("the input tensors shape does not match");return t?e:e.reshape(s)});return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["stack"])(p,r)]});case"Unpack":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r=getParamValue("axis",e,t,a),n=getParamValue("tensor",e,t,a);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["unstack"])(n,r)});case"Tile":var x=getParamValue("reps",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tile"])(getParamValue("x",e,t,a),x)];case"Split":case"SplitV":n=getParamValue("axis",e,t,a);var V=getParamValue("numOrSizeSplits",e,t,a);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["split"])(getParamValue("x",e,t,a),V,n);case"ScatterNd":p=getParamValue("indices",e,t,a);var b=getParamValue("values",e,t,a),P=getParamValue("shape",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scatterND"])(p,b,P)];case"GatherNd":var T=getParamValue("x",e,t,a);p=getParamValue("indices",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["gatherND"])(T,p)];case"SparseToDense":p=getParamValue("sparseIndices",e,t,a),P=getParamValue("outputShape",e,t,a);var v=getParamValue("sparseValues",e,t,a),O=getParamValue("defaultValue",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sparseToDense"])(p,v,P,v.dtype===O.dtype?O:O.asType(v.dtype))];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$14=function(e,t,a){switch(e.op){case"FFT":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["fft"])(getParamValue("x",e,t,a))];case"IFFT":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["ifft"])(getParamValue("x",e,t,a))];case"RFFT":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["rfft"])(getParamValue("x",e,t,a))];case"IRFFT":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["irfft"])(getParamValue("x",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},executeOp$15=function(e,t,a){switch(e.op){case"Cast":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["cast"])(getParamValue("x",e,t,a),getParamValue("dtype",e,t,a))];case"ExpandDims":var r=getParamValue("axis",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["expandDims"])(getParamValue("x",e,t,a),r)];case"Squeeze":r=getParamValue("axis",e,t,a);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["squeeze"])(getParamValue("x",e,t,a),r)];case"Reshape":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["reshape"])(getParamValue("x",e,t,a),getParamValue("shape",e,t,a))];case"PadV2":case"Pad":return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["pad"])(getParamValue("x",e,t,a),split$1(getParamValue("padding",e,t,a),2),getParamValue("constantValue",e,t,a))];case"SpaceToBatchND":var n=getParamValue("blockShape",e,t,a),s=split$1(getParamValue("paddings",e,t,a),2);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["spaceToBatchND"])(getParamValue("x",e,t,a),n,s)];case"BatchToSpaceND":n=getParamValue("blockShape",e,t,a);var o=split$1(getParamValue("crops",e,t,a),2);return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["batchToSpaceND"])(getParamValue("x",e,t,a),n,o)];case"DepthToSpace":var p=getParamValue("blockSize",e,t,a),u=getParamValue("dataFormat",e,t,a).toUpperCase();return[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["depthToSpace"])(getParamValue("x",e,t,a),p,u)];default:throw TypeError("Node type "+e.op+" is not implemented")}};function executeOp$16(e,t,a){var r=function(e,t,a){switch(e.category){case"arithmetic":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp(e,t,a)});case"basic_math":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$1(e,t,a)});case"control":return executeOp$2(e,t,a);case"convolution":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$3(e,t,a)});case"creation":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$4(e,t,a)});case"dynamic":return executeOp$5(e,t,a);case"evaluation":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$6(e,t,a)});case"image":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$8(e,t,a)});case"graph":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$7(e,t,a)});case"logical":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$9(e,t,a)});case"matrices":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$10(e,t,a)});case"normalization":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$11(e,t,a)});case"reduction":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$12(e,t,a)});case"slice_join":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$13(e,t,a)});case"spectral":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$14(e,t,a)});case"transformation":return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return executeOp$15(e,t,a)});case"custom":var r=getRegisteredOp(e.op);if(r&&r.customExecutor)return r.customExecutor(new NodeValueImpl(e,t,a));throw TypeError("Custom op "+e.op+" is not registered.");default:throw TypeError("Unknown op '"+e.op+"'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()")}}(e,t,a);return r instanceof Promise?r.then(function(e){return[].concat(e)}):[].concat(r)}var ExecutionContext=function(){function e(e,t){this.weightMap=e,this.tensorArrayMap=t,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return e.prototype.newFrame=function(e,t){return{id:e,frameName:t,iterationId:0}},Object.defineProperty(e.prototype,"currentContext",{get:function(){return this.contexts},set:function(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),e.prototype.generateCurrentContextIds=function(){for(var e=[],t=0;t<this.contexts.length-1;t++){var a=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(a))}e.push(""),this._currentContextIds=e},e.prototype.contextIdforContexts=function(e){return e?e.map(function(e){return 0===e.id&&0===e.iterationId?"":e.frameName+"-"+e.iterationId}).join("/"):""},e.prototype.enterFrame=function(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},e.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},e.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 e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},e.prototype.getWeight=function(e){return this.weightMap[e]},e.prototype.addTensorArray=function(e){this.tensorArrayMap[e.id]=e},e.prototype.getTensorArray=function(e){return this.tensorArrayMap[e]},e}();function getExecutionSubgraph(e,t,a){for(var r=new Set,n=[],s=null,o=null,p=new Set,u=Object.keys(e).map(function(e){return parseNodeName(e)[0]}),i=t.slice();i.length>0;){var m=i.pop();(isControlFlow(m)||isDynamicShape(m))&&null==s&&(o=(s=m).children.map(function(e){return e.name}).filter(function(e){return r.has(e)})),r.add(m.name),null==a[m.name]&&(-1===u.indexOf(m.name)&&(0!==m.inputs.length?m.inputs.forEach(function(e){p.has(e.name)||(p.add(e.name),i.push(e))}):n.push(m.name)))}return{inputs:e,outputs:t,usedNodes:r,missingInputs:n,dynamicNode:s,syncInputs:o}}function getNodesInTopologicalOrder(e,t,a){var r=a.usedNodes,n=a.inputs,s=[];Object.keys(n).map(function(e){return parseNodeName(e)[0]}).map(function(t){return e.nodes[t]}).forEach(function(e){r.has(e.name)&&s.push(e)}),e.weights.forEach(function(e){r.has(e.name)&&s.push(e)});for(var o=new Set,p=[];s.length>0;){var u=s.pop();o.add(u.name),t[u.name]||p.push(u),u.children.forEach(function(e){!o.has(e.name)&&r.has(e.name)&&e.inputs.every(function(e){return o.has(e.name)})&&s.push(e)})}return p}var CONTROL_FLOW_OPS=["Switch","Merge","Enter","Exit","NextIteration"],DYNAMIC_SHAPE_OPS=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function isControlFlow(e){return CONTROL_FLOW_OPS.indexOf(e.op)>=0}function isDynamicShape(e){return DYNAMIC_SHAPE_OPS.indexOf(e.op)>=0}var GraphExecutor=function(){function e(e){this.graph=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._outputs=e.outputs,this._inputs=e.inputs,this._signature=e.signature}return Object.defineProperty(e.prototype,"weightMap",{get:function(){return this._weightMap},set:function(e){var t=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id})});this.weightIds=[].concat.apply([],t),this._weightMap=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this._inputs.map(function(e){return{name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs.map(function(e){return{name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this._inputs.map(function(e){return e.signatureKey||e.name})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this._outputs.map(function(e){return e.signatureKey||e.name})},enumerable:!0,configurable:!0}),e.prototype.getCompilationKey=function(e,t){var a=e.map(function(e){return e.name}).sort(),r=t.map(function(e){return e.name}).sort();return a.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},e.prototype.compile=function(e,t){var a=getExecutionSubgraph(e,t,this.weightMap),r=a.missingInputs,n=a.dynamicNode,s=a.syncInputs;if(null!=n)throw new Error("This execution contains the node '"+n.name+"', which has the dynamic op '"+n.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+s+"]");if(r.length>0){var o=t.map(function(e){return e.name}),p=Object.keys(e);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs ["+p+"]. Missing the following inputs: ["+r+"]")}return getNodesInTopologicalOrder(this.graph,this.weightMap,a)},e.prototype.execute=function(e,t){var a=this;e=this.mapInputs(e);var r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);var n=r.map(function(e){return a.graph.nodes[parseNodeName(e)[0]]}),s=t.map(function(e){return a.graph.nodes[parseNodeName(e)[0]]}),o=this.getCompilationKey(n,s),p=this.compiledMap.get(o);null==p&&(p=this.compile(e,s),this.compiledMap.set(o,p));var u={};return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r=new ExecutionContext(a._weightMap,u),n=__assign({},a.weightMap);Object.keys(e).forEach(function(t){var a=parseNodeName(t),r=a[0],s=[];s[a[1]]=e[t],n[r]=s});for(var s=a.getFrozenTensorIds(n),o={},i=0;i<p.length;i++){var m=p[i];if(!n[m.name]){var l=executeOp$16(m,n,r);if(l instanceof Promise)throw new Error("The execution of the op '"+m.op+"' returned a promise. Please use model.executeAsync() instead.");n[m.name]=l,a.checkTensorForDisposal(m.name,m,n,r,s,t,o)}}return t.map(function(e){return getTensor(e,n,r)})})},e.prototype.getFrozenTensorIds=function(e){var t=[].concat.apply([],Object.keys(e).map(function(t){return e[t]}).map(function(e){return e.map(function(e){return e.id})}));return new Set(t)},e.prototype.checkTensorForDisposal=function(e,t,a,r,n,s,o){"control"!==t.category&&-1===s.indexOf(e)&&(a[e].forEach(function(e){null!=e&&(o[e.id]=(o[e.id]||0)+t.children.length)}),t.inputs.forEach(function(e){if("control"!==e.category){var t=getTensorsForCurrentContenxt(e.name,a,r);null!=t&&t.forEach(function(e){if(e&&!n.has(e.id)){var t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}})}}))},e.prototype.executeAsync=function(e,t){return __awaiter(this,void 0,void 0,function(){var a,r,n,s,o,p,u=this;return __generator(this,function(i){switch(i.label){case 0:return e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t),a={},r=new ExecutionContext(this._weightMap,a),[4,this.executeWithControlFlow(e,r,t)];case 1:return n=i.sent(),s=t.map(function(e){return getTensor(e,n,r)}),o=new Set(s.map(function(e){return e.id})),p=new Set(Object.keys(e).map(function(t){return e[t].id})),Object.keys(n).forEach(function(e){n[e].forEach(function(e){!e||e.isDisposed||o.has(e.id)||p.has(e.id)||-1!==u.weightIds.indexOf(e.id)||e.dispose()})}),[2,s]}})})},e.prototype.executeWithControlFlow=function(e,t,a){return __awaiter(this,void 0,void 0,function(){var r,n,s,o,p,u,i,m,l,c,d,y,f,g,h,N,x=this;return __generator(this,function(V){switch(V.label){case 0:r=Object.keys(e),n=r.map(function(e){return x.graph.nodes[parseNodeName(e)[0]]}),s=a.map(function(e){return x.graph.nodes[parseNodeName(e)[0]]}),o=getExecutionSubgraph(e,s,this.weightMap),p=o.usedNodes,u=o.missingInputs,i=o.dynamicNode,m=o.syncInputs,l=n.concat(this.graph.weights).map(function(e){return{node:e,contexts:t.currentContext}}),c=__assign({},this.weightMap),Object.keys(e).forEach(function(t){var a=parseNodeName(t),r=a[0],n=[];n[a[1]]=e[t],c[r]=n}),d={},y=this.getFrozenTensorIds(c),f={},V.label=1;case 1:return l.length>0?(g=this.processStack(n,l,t,c,f,y,a,d,p),[4,Promise.all(g)]):[3,3];case 2:return V.sent(),[3,1];case 3:if(null==i&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(h=s.filter(function(e){return!isControlFlow(e)&&!getTensor(e.name,c,t)}).map(function(e){return e.name})).length>0)throw N="",null!=i&&(N="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+m+"]"),new Error("Cannot compute the outputs ["+h+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+u+"]. "+N);return[2,c]}})})},e.prototype.processStack=function(e,t,a,r,n,s,o,p,u){for(var i=this,m=[],l=function(){var l=t.pop();a.currentContext=l.contexts;var d="";if("Enter"===l.node.op&&getParamValue("isConstant",l.node,r,a)&&(d=getNodeNameAndIndex(l.node.name,a)[0]),-1===e.indexOf(l.node)){var y=executeOp$16(l.node,r,a);d||(d=getNodeNameAndIndex(l.node.name,a)[0]);var f=a.currentContext;y instanceof Promise?m.push(y.then(function(e){return r[d]=e,a.currentContext=f,i.checkTensorForDisposal(d,l.node,r,a,s,o,p),i.processChildNodes(l.node,t,a,r,n,u),e})):(r[d]=y,c.checkTensorForDisposal(d,l.node,r,a,s,o,p),c.processChildNodes(l.node,t,a,r,n,u))}else c.processChildNodes(l.node,t,a,r,n,u)},c=this;t.length>0;)l();return m},e.prototype.processChildNodes=function(e,t,a,r,n,s){e.children.forEach(function(e){var o=getNodeNameAndIndex(e.name,a)[0];!n[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(function(e){return!!getTensor(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})):e.inputNames.every(function(e){return!!getTensor(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})))})},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose()})})},e.prototype.checkInputShapeAndType=function(e){var t=this;Object.keys(e).forEach(function(a){var r=e[a],n=parseNodeName(a)[0],s=t.graph.nodes[n];if(s.attrParams.shape&&s.attrParams.shape.value){var o=s.attrParams.shape.value,p=o.length===r.shape.length&&r.shape.every(function(e,t){return-1===o[t]||o[t]===e});_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(p,function(){return"The shape of dict['"+s.name+"'] provided in model.execute(dict) must be ["+o+"], but was ["+r.shape+"]"})}s.attrParams.dtype&&s.attrParams.dtype.value&&_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r.dtype===s.attrParams.dtype.value,function(){return"The dtype of dict['"+s.name+"'] provided in model.execute(dict) must be "+s.attrParams.dtype.value+", but was "+r.dtype})})},e.prototype.mapInputs=function(e){var t={};for(var a in e){if(null!=this._signature&&null!=this._signature.inputs&&null!=this._signature.inputs[a])t[this._signature.inputs[a].name]=e[a];else t[a]=e[a]}return t},e.prototype.checkInputs=function(e){var t=this,a=Object.keys(e).filter(function(e){var a=parseNodeName(e)[0];return null==t.graph.nodes[a]});if(a.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+a+"] that are not part of graph")},e.prototype.mapOutputs=function(e){var t=this;return e.map(function(e){return null!=t._signature&&null!=t._signature.outputs&&null!=t._signature.outputs[e]?t._signature.outputs[e].name:e},{})},e.prototype.checkOutputs=function(e){var t=this;e.forEach(function(e){var a=parseNodeName(e)[0];if(!t.graph.nodes[a])throw new Error("The output '"+e+"' is not found in the graph")})},e}(),TFHUB_SEARCH_PARAM="?tfjs-format=file",DEFAULT_MODEL_NAME="model.json",GraphModel=function(){function e(e,t){void 0===t&&(t={}),this.modelUrl=e,this.loadOptions=t,this.version="n/a",null==t&&(this.loadOptions={})}return Object.defineProperty(e.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),e.prototype.findIOHandler=function(){var e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].browserHTTPRequest(e,this.loadOptions);else{var t=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].getLoadHandlers(e,this.loadOptions.onProgress);if(0===t.length)t.push(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error("Found more than one ("+t.length+") load handlers for URL '"+[e]+"'");this.handler=t[0]}},e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e,t,a,r;return __generator(this,function(n){switch(n.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 e=this,[4,this.handler.load()];case 1:return e.artifacts=n.sent(),t=this.artifacts.modelTopology,a={},null!=this.artifacts.userDefinedMetadata&&(a=this.artifacts.userDefinedMetadata.signature),this.version=t.versions.producer+"."+t.versions.minConsumer,r=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs),this.executor=new GraphExecutor(OperationMapper.Instance.transformGraph(t,a)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),[2,!0]}})})},e.prototype.save=function(e,t){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(a){if("string"==typeof e){if(0===(t=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["io"].getSaveHandlers(e)).length)throw new Error("Cannot find any save handlers for URL '"+e+"'");if(t.length>1)throw new Error("Found more than one ("+t.length+") save handlers for URL '"+e+"'");e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[2,e.save(this.artifacts)]})})},e.prototype.predict=function(e,t){return this.execute(e,this.outputNodes)},e.prototype.normalizeInputs=function(e){if(!(e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]||Array.isArray(e)))return e;if((e=Array.isArray(e)?e:[e]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+e.length+" input tensors.");return this.inputNodes.reduce(function(t,a,r){return t[a]=e[r],t},{})},e.prototype.normalizeOutputs=function(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]},e.prototype.execute=function(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);var a=this.executor.execute(e,t);return a.length>1?a:a[0]},e.prototype.executeAsync=function(e,t){return __awaiter(this,void 0,void 0,function(){var a;return __generator(this,function(r){switch(r.label){case 0:return e=this.normalizeInputs(e),t=this.normalizeOutputs(t),[4,this.executor.executeAsync(e,t)];case 1:return[2,(a=r.sent()).length>1?a:a[0]]}})})},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,a){return t[a]=[e[a]],t},{})},e.prototype.dispose=function(){this.executor.dispose()},e}();function loadGraphModel(e,t){return void 0===t&&(t={}),__awaiter(this,void 0,void 0,function(){var a;return __generator(this,function(r){switch(r.label){case 0:if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==t&&(t={}),t.fromTFHub&&null==e.load&&(e.endsWith("/")||(e+="/"),e=""+e+DEFAULT_MODEL_NAME+TFHUB_SEARCH_PARAM),[4,(a=new GraphModel(e,t)).load()];case 1:return r.sent(),[2,a]}})})}var version="1.7.2";
//# sourceMappingURL=tf-converter.esm.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(86).Buffer))
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(6);
var IE8_DOM_DEFINE = __webpack_require__(282);
var toPrimitive = __webpack_require__(52);
var dP = Object.defineProperty;
exports.f = __webpack_require__(19) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(51);
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(26);
var core = __webpack_require__(18);
var ctx = __webpack_require__(56);
var hide = __webpack_require__(60);
var has = __webpack_require__(67);
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
var key, own, out;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if (own && has(exports, key)) continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function (C) {
var F = function (a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0: return new C();
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if (IS_PROTO) {
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(425), __esModule: true };
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var store = __webpack_require__(159)('wks');
var uid = __webpack_require__(121);
var Symbol = __webpack_require__(26).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ }),
/* 26 */
/***/ (function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/***/ }),
/* 27 */
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(218);
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var fails = __webpack_require__(12);
var defined = __webpack_require__(51);
var quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function (string, tag, attribute, value) {
var S = String(defined(string));
var p1 = '<' + tag;
if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function (NAME, exec) {
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function () {
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var hide = __webpack_require__(31);
var has = __webpack_require__(36);
var SRC = __webpack_require__(78)('src');
var $toString = __webpack_require__(689);
var TO_STRING = 'toString';
var TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(44).inspectSource = function (it) {
return $toString.call(it);
};
(module.exports = function (O, key, val, safe) {
var isFunction = typeof val == 'function';
if (isFunction) has(val, 'name') || hide(val, 'name', key);
if (O[key] === val) return;
if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if (O === global) {
O[key] = val;
} else if (!safe) {
delete O[key];
hide(O, key, val);
} else if (O[key]) {
O[key] = val;
} else {
hide(O, key, val);
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString() {
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(21);
var createDesc = __webpack_require__(79);
module.exports = __webpack_require__(19) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(68)(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(36);
var toObject = __webpack_require__(22);
var IE_PROTO = __webpack_require__(190)('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(112);
var createDesc = __webpack_require__(79);
var toIObject = __webpack_require__(35);
var toPrimitive = __webpack_require__(52);
var has = __webpack_require__(36);
var IE8_DOM_DEFINE = __webpack_require__(282);
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(19) ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(113);
var defined = __webpack_require__(51);
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/* 36 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = __webpack_require__(237);
const visor_1 = __webpack_require__(236);
function getDrawArea(drawable) {
if (drawable instanceof HTMLElement) {
return drawable;
}
else if (types_1.isSurface(drawable)) {
return drawable.drawArea;
}
else if (types_1.isSurfaceInfo(drawable)) {
const surface = visor_1.visor().surface({ name: drawable.name, tab: drawable.tab, styles: drawable.styles });
return surface.drawArea;
}
else {
throw new Error('Not a drawable');
}
}
exports.getDrawArea = getDrawArea;
function shallowEquals(
// tslint:disable-next-line:no-any
a, b) {
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
if (aProps.length !== bProps.length) {
return false;
}
for (let i = 0; i < aProps.length; i++) {
const prop = aProps[i];
if (a[prop] !== b[prop]) {
return false;
}
}
return true;
}
exports.shallowEquals = shallowEquals;
function nextFrame() {
return __awaiter(this, void 0, void 0, function* () {
yield new Promise(r => requestAnimationFrame(r));
});
}
exports.nextFrame = nextFrame;
//# sourceMappingURL=render_utils.js.map
/***/ }),
/* 38 */
/***/ (function(module, exports) {
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(48);
var IE8_DOM_DEFINE = __webpack_require__(246);
var toPrimitive = __webpack_require__(164);
var dP = Object.defineProperty;
exports.f = __webpack_require__(32) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var fails = __webpack_require__(12);
module.exports = function (method, arg) {
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call
arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null);
});
};
/***/ }),
/* 41 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 42 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(27);
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 44 */
/***/ (function(module, exports) {
var core = module.exports = { version: '2.6.11' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatDecimal.js
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
/* harmony default export */ var formatDecimal = (function(x, p) {
if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
var i, coefficient = x.slice(0, i);
// The string returned by toExponential either has the form \d\.\d+e[-+]\d+
// (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
return [
coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
+x.slice(i + 1)
];
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/exponent.js
/* harmony default export */ var src_exponent = (function(x) {
return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatGroup.js
/* harmony default export */ var formatGroup = (function(grouping, thousands) {
return function(value, width) {
var i = value.length,
t = [],
j = 0,
g = grouping[0],
length = 0;
while (i > 0 && g > 0) {
if (length + g + 1 > width) g = Math.max(1, width - length);
t.push(value.substring(i -= g, i + g));
if ((length += g + 1) > width) break;
g = grouping[j = (j + 1) % grouping.length];
}
return t.reverse().join(thousands);
};
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ var formatNumerals = (function(numerals) {
return function(value) {
return value.replace(/[0-9]/g, function(i) {
return numerals[+i];
});
};
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
return new FormatSpecifier(specifier);
}
formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
function FormatSpecifier(specifier) {
if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
var match;
this.fill = match[1] || " ";
this.align = match[2] || ">";
this.sign = match[3] || "-";
this.symbol = match[4] || "";
this.zero = !!match[5];
this.width = match[6] && +match[6];
this.comma = !!match[7];
this.precision = match[8] && +match[8].slice(1);
this.trim = !!match[9];
this.type = match[10] || "";
}
FormatSpecifier.prototype.toString = function() {
return this.fill
+ this.align
+ this.sign
+ this.symbol
+ (this.zero ? "0" : "")
+ (this.width == null ? "" : Math.max(1, this.width | 0))
+ (this.comma ? "," : "")
+ (this.precision == null ? "" : "." + Math.max(0, this.precision | 0))
+ (this.trim ? "~" : "")
+ this.type;
};
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ var formatTrim = (function(s) {
out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (s[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) i0 = i; i1 = i; break;
default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break;
}
}
return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatPrefixAuto.js
var formatPrefixAuto_prefixExponent;
/* harmony default export */ var formatPrefixAuto = (function(x, p) {
var d = formatDecimal(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1],
i = exponent - (formatPrefixAuto_prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
n = coefficient.length;
return i === n ? coefficient
: i > n ? coefficient + new Array(i - n + 1).join("0")
: i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
: "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatRounded.js
/* harmony default export */ var formatRounded = (function(x, p) {
var d = formatDecimal(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1];
return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
: coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
: coefficient + new Array(exponent - coefficient.length + 2).join("0");
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTypes.js
/* harmony default export */ var formatTypes = ({
"%": function(x, p) { return (x * 100).toFixed(p); },
"b": function(x) { return Math.round(x).toString(2); },
"c": function(x) { return x + ""; },
"d": function(x) { return Math.round(x).toString(10); },
"e": function(x, p) { return x.toExponential(p); },
"f": function(x, p) { return x.toFixed(p); },
"g": function(x, p) { return x.toPrecision(p); },
"o": function(x) { return Math.round(x).toString(8); },
"p": function(x, p) { return formatRounded(x * 100, p); },
"r": formatRounded,
"s": formatPrefixAuto,
"X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
"x": function(x) { return Math.round(x).toString(16); }
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/identity.js
/* harmony default export */ var identity = (function(x) {
return x;
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/locale.js
var locale_prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
/* harmony default export */ var src_locale = (function(locale) {
var group = locale.grouping && locale.thousands ? formatGroup(locale.grouping, locale.thousands) : identity,
currency = locale.currency,
decimal = locale.decimal,
numerals = locale.numerals ? formatNumerals(locale.numerals) : identity,
percent = locale.percent || "%";
function newFormat(specifier) {
specifier = formatSpecifier(specifier);
var fill = specifier.fill,
align = specifier.align,
sign = specifier.sign,
symbol = specifier.symbol,
zero = specifier.zero,
width = specifier.width,
comma = specifier.comma,
precision = specifier.precision,
trim = specifier.trim,
type = specifier.type;
// The "n" type is an alias for ",g".
if (type === "n") comma = true, type = "g";
// The "" type, and any invalid type, is an alias for ".12~g".
else if (!formatTypes[type]) precision == null && (precision = 12), trim = true, type = "g";
// If zero fill is specified, padding goes after sign and before digits.
if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
// Compute the prefix and suffix.
// For SI-prefix, the suffix is lazily computed.
var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? percent : "";
// What format function should we use?
// Is this an integer type?
// Can this type generate exponential notation?
var formatType = formatTypes[type],
maybeSuffix = /[defgprs%]/.test(type);
// Set the default precision if not specified,
// or clamp the specified precision to the supported range.
// For significant precision, it must be in [1, 21].
// For fixed precision, it must be in [0, 20].
precision = precision == null ? 6
: /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
: Math.max(0, Math.min(20, precision));
function format(value) {
var valuePrefix = prefix,
valueSuffix = suffix,
i, n, c;
if (type === "c") {
valueSuffix = formatType(value) + valueSuffix;
value = "";
} else {
value = +value;
// Perform the initial formatting.
var valueNegative = value < 0;
value = formatType(Math.abs(value), precision);
// Trim insignificant zeros.
if (trim) value = formatTrim(value);
// If a negative value rounds to zero during formatting, treat as positive.
if (valueNegative && +value === 0) valueNegative = false;
// Compute the prefix and suffix.
valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
valueSuffix = (type === "s" ? locale_prefixes[8 + formatPrefixAuto_prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
if (maybeSuffix) {
i = -1, n = value.length;
while (++i < n) {
if (c = value.charCodeAt(i), 48 > c || c > 57) {
valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
value = value.slice(0, i);
break;
}
}
}
}
// If the fill character is not "0", grouping is applied before padding.
if (comma && !zero) value = group(value, Infinity);
// Compute the padding.
var length = valuePrefix.length + value.length + valueSuffix.length,
padding = length < width ? new Array(width - length + 1).join(fill) : "";
// If the fill character is "0", grouping is applied after padding.
if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
// Reconstruct the final output based on the desired alignment.
switch (align) {
case "<": value = valuePrefix + value + valueSuffix + padding; break;
case "=": value = valuePrefix + padding + value + valueSuffix; break;
case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
default: value = padding + valuePrefix + value + valueSuffix; break;
}
return numerals(value);
}
format.toString = function() {
return specifier + "";
};
return format;
}
function formatPrefix(specifier, value) {
var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
e = Math.max(-8, Math.min(8, Math.floor(src_exponent(value) / 3))) * 3,
k = Math.pow(10, -e),
prefix = locale_prefixes[8 + e / 3];
return function(value) {
return f(k * value) + prefix;
};
}
return {
format: newFormat,
formatPrefix: formatPrefix
};
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/defaultLocale.js
var defaultLocale_locale;
var defaultLocale_format;
var defaultLocale_formatPrefix;
defaultLocale_defaultLocale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["$", ""]
});
function defaultLocale_defaultLocale(definition) {
defaultLocale_locale = src_locale(definition);
defaultLocale_format = defaultLocale_locale.format;
defaultLocale_formatPrefix = defaultLocale_locale.formatPrefix;
return defaultLocale_locale;
}
// CONCATENATED MODULE: ./node_modules/d3-format/src/precisionFixed.js
/* harmony default export */ var precisionFixed = (function(step) {
return Math.max(0, -src_exponent(Math.abs(step)));
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/precisionPrefix.js
/* harmony default export */ var precisionPrefix = (function(step, value) {
return Math.max(0, Math.max(-8, Math.min(8, Math.floor(src_exponent(value) / 3))) * 3 - src_exponent(Math.abs(step)));
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/precisionRound.js
/* harmony default export */ var precisionRound = (function(step, max) {
step = Math.abs(step), max = Math.abs(max) - step;
return Math.max(0, src_exponent(max) - src_exponent(step)) + 1;
});
// CONCATENATED MODULE: ./node_modules/d3-format/src/index.js
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "formatDefaultLocale", function() { return defaultLocale_defaultLocale; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "format", function() { return defaultLocale_format; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "formatPrefix", function() { return defaultLocale_formatPrefix; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "formatLocale", function() { return src_locale; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "formatSpecifier", function() { return formatSpecifier; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "precisionFixed", function() { return precisionFixed; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "precisionPrefix", function() { return precisionPrefix; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "precisionRound", function() { return precisionRound; });
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.imgToPixelArray = exports.flipImage = exports.isInstanceOfSupportedElement = exports.imgToTensor = exports.cropImage = exports.processVideo = exports.array3DToImage = undefined;
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _p5Utils = __webpack_require__(83);
var _p5Utils2 = _interopRequireDefault(_p5Utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Resize video elements
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var processVideo = function processVideo(input, size) {
var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
var videoInput = input;
var element = document.createElement('video');
videoInput.onplay = function () {
var stream = videoInput.captureStream();
element.srcObject = stream;
element.width = size;
element.height = size;
element.autoplay = true;
element.playsinline = true;
element.muted = true;
callback();
};
return element;
};
// Converts a tf to DOM img
var array3DToImage = function array3DToImage(tensor) {
var _tensor$shape = (0, _slicedToArray3.default)(tensor.shape, 2),
imgHeight = _tensor$shape[0],
imgWidth = _tensor$shape[1];
var data = tensor.dataSync();
var canvas = document.createElement('canvas');
canvas.width = imgWidth;
canvas.height = imgHeight;
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (var i = 0; i < imgWidth * imgHeight; i += 1) {
var j = i * 4;
var k = i * 3;
imageData.data[j + 0] = Math.floor(256 * data[k + 0]);
imageData.data[j + 1] = Math.floor(256 * data[k + 1]);
imageData.data[j + 2] = Math.floor(256 * data[k + 2]);
imageData.data[j + 3] = 255;
}
ctx.putImageData(imageData, 0, 0);
// Create img HTML element from canvas
var dataUrl = canvas.toDataURL();
var outputImg = document.createElement('img');
outputImg.src = dataUrl;
outputImg.style.width = imgWidth;
outputImg.style.height = imgHeight;
tensor.dispose();
return outputImg;
};
// Static Method: crop the image
var cropImage = function cropImage(img) {
var size = Math.min(img.shape[0], img.shape[1]);
var centerHeight = img.shape[0] / 2;
var beginHeight = centerHeight - size / 2;
var centerWidth = img.shape[1] / 2;
var beginWidth = centerWidth - size / 2;
return img.slice([beginHeight, beginWidth, 0], [size, size, 3]);
};
var flipImage = function flipImage(img) {
// image image, bitmap, or canvas
var imgWidth = void 0;
var imgHeight = void 0;
var inputImg = void 0;
if (img instanceof HTMLImageElement || img instanceof HTMLCanvasElement || img instanceof HTMLVideoElement || img instanceof ImageData) {
inputImg = img;
} else if ((typeof img === 'undefined' ? 'undefined' : (0, _typeof3.default)(img)) === 'object' && (img.elt instanceof HTMLImageElement || img.elt instanceof HTMLCanvasElement || img.elt instanceof HTMLVideoElement || img.elt instanceof ImageData)) {
inputImg = img.elt; // Handle p5.js image
} else if ((typeof img === 'undefined' ? 'undefined' : (0, _typeof3.default)(img)) === 'object' && img.canvas instanceof HTMLCanvasElement) {
inputImg = img.canvas; // Handle p5.js image
} else {
inputImg = img;
}
if (inputImg instanceof HTMLVideoElement) {
// should be videoWidth, videoHeight?
imgWidth = inputImg.width;
imgHeight = inputImg.height;
} else {
imgWidth = inputImg.width;
imgHeight = inputImg.height;
}
if (_p5Utils2.default.checkP5()) {
var p5Canvas = _p5Utils2.default.p5Instance.createGraphics(imgWidth, imgHeight);
p5Canvas.push();
p5Canvas.translate(imgWidth, 0);
p5Canvas.scale(-1, 1);
p5Canvas.image(img, 0, 0, imgWidth, imgHeight);
p5Canvas.pop();
return p5Canvas;
}
var canvas = document.createElement('canvas');
canvas.width = imgWidth;
canvas.height = imgHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(inputImg, 0, 0, imgWidth, imgHeight);
ctx.translate(imgWidth, 0);
ctx.scale(-1, 1);
ctx.drawImage(canvas, imgWidth * -1, 0, imgWidth, imgHeight);
return canvas;
};
// Static Method: image to tf tensor
function imgToTensor(input) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return tf.tidy(function () {
var img = tf.browser.fromPixels(input);
if (size) {
img = tf.image.resizeBilinear(img, size);
}
var croppedImage = cropImage(img);
var batchedImage = croppedImage.expandDims(0);
return batchedImage.toFloat().div(tf.scalar(127)).sub(tf.scalar(1));
});
}
function isInstanceOfSupportedElement(subject) {
return subject instanceof HTMLVideoElement || subject instanceof HTMLImageElement || subject instanceof HTMLCanvasElement || subject instanceof ImageData;
}
function imgToPixelArray(img) {
// image image, bitmap, or canvas
var imgWidth = void 0;
var imgHeight = void 0;
var inputImg = void 0;
if (img instanceof HTMLImageElement || img instanceof HTMLCanvasElement || img instanceof HTMLVideoElement || img instanceof ImageData) {
inputImg = img;
} else if ((typeof img === 'undefined' ? 'undefined' : (0, _typeof3.default)(img)) === 'object' && (img.elt instanceof HTMLImageElement || img.elt instanceof HTMLCanvasElement || img.elt instanceof HTMLVideoElement || img.elt instanceof ImageData)) {
inputImg = img.elt; // Handle p5.js image
} else if ((typeof img === 'undefined' ? 'undefined' : (0, _typeof3.default)(img)) === 'object' && img.canvas instanceof HTMLCanvasElement) {
inputImg = img.canvas; // Handle p5.js image
} else {
inputImg = img;
}
if (inputImg instanceof HTMLVideoElement) {
// should be videoWidth, videoHeight?
imgWidth = inputImg.width;
imgHeight = inputImg.height;
} else {
imgWidth = inputImg.width;
imgHeight = inputImg.height;
}
var canvas = document.createElement('canvas');
canvas.width = imgWidth;
canvas.height = imgHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(inputImg, 0, 0, imgWidth, imgHeight);
var imgData = ctx.getImageData(0, 0, imgWidth, imgHeight);
return (0, _from2.default)(imgData.data);
}
exports.array3DToImage = array3DToImage;
exports.processVideo = processVideo;
exports.cropImage = cropImage;
exports.imgToTensor = imgToTensor;
exports.isInstanceOfSupportedElement = isInstanceOfSupportedElement;
exports.flipImage = flipImage;
exports.imgToPixelArray = imgToPixelArray;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(401), __esModule: true };
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(38);
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(43);
var IObject = __webpack_require__(113);
var toObject = __webpack_require__(22);
var toLength = __webpack_require__(17);
var asc = __webpack_require__(174);
module.exports = function (TYPE, $create) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
var create = $create || asc;
return function ($this, callbackfn, that) {
var O = toObject($this);
var self = IObject(O);
var f = ctx(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var val, res;
for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
if (TYPE) {
if (IS_MAP) result[index] = res; // map
else if (res) switch (TYPE) {
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(5);
var core = __webpack_require__(44);
var fails = __webpack_require__(12);
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/* 51 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(13);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 53 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1, eval)("this");
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(366), __esModule: true };
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(398);
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(109);
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var Map = __webpack_require__(259);
var $export = __webpack_require__(5);
var shared = __webpack_require__(114)('metadata');
var store = shared.store || (shared.store = new (__webpack_require__(256))());
var getOrCreateMetadataMap = function (target, targetKey, create) {
var targetMetadata = store.get(target);
if (!targetMetadata) {
if (!create) return undefined;
store.set(target, targetMetadata = new Map());
}
var keyMetadata = targetMetadata.get(targetKey);
if (!keyMetadata) {
if (!create) return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map());
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function (MetadataKey, O, P) {
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) {
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function (target, targetKey) {
var metadataMap = getOrCreateMetadataMap(target, targetKey, false);
var keys = [];
if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); });
return keys;
};
var toMetaKey = function (it) {
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function (O) {
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
if (__webpack_require__(19)) {
var LIBRARY = __webpack_require__(63);
var global = __webpack_require__(11);
var fails = __webpack_require__(12);
var $export = __webpack_require__(5);
var $typed = __webpack_require__(126);
var $buffer = __webpack_require__(166);
var ctx = __webpack_require__(43);
var anInstance = __webpack_require__(72);
var propertyDesc = __webpack_require__(79);
var hide = __webpack_require__(31);
var redefineAll = __webpack_require__(70);
var toInteger = __webpack_require__(41);
var toLength = __webpack_require__(17);
var toIndex = __webpack_require__(254);
var toAbsoluteIndex = __webpack_require__(76);
var toPrimitive = __webpack_require__(52);
var has = __webpack_require__(36);
var classof = __webpack_require__(93);
var isObject = __webpack_require__(13);
var toObject = __webpack_require__(22);
var isArrayIter = __webpack_require__(177);
var create = __webpack_require__(75);
var getPrototypeOf = __webpack_require__(33);
var gOPN = __webpack_require__(74).f;
var getIterFn = __webpack_require__(175);
var uid = __webpack_require__(78);
var wks = __webpack_require__(16);
var createArrayMethod = __webpack_require__(49);
var createArrayIncludes = __webpack_require__(136);
var speciesConstructor = __webpack_require__(110);
var ArrayIterators = __webpack_require__(172);
var Iterators = __webpack_require__(91);
var $iterDetect = __webpack_require__(131);
var setSpecies = __webpack_require__(73);
var arrayFill = __webpack_require__(173);
var arrayCopyWithin = __webpack_require__(265);
var $DP = __webpack_require__(21);
var $GOPD = __webpack_require__(34);
var dP = $DP.f;
var gOPD = $GOPD.f;
var RangeError = global.RangeError;
var TypeError = global.TypeError;
var Uint8Array = global.Uint8Array;
var ARRAY_BUFFER = 'ArrayBuffer';
var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER;
var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';
var PROTOTYPE = 'prototype';
var ArrayProto = Array[PROTOTYPE];
var $ArrayBuffer = $buffer.ArrayBuffer;
var $DataView = $buffer.DataView;
var arrayForEach = createArrayMethod(0);
var arrayFilter = createArrayMethod(2);
var arraySome = createArrayMethod(3);
var arrayEvery = createArrayMethod(4);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var arrayIncludes = createArrayIncludes(true);
var arrayIndexOf = createArrayIncludes(false);
var arrayValues = ArrayIterators.values;
var arrayKeys = ArrayIterators.keys;
var arrayEntries = ArrayIterators.entries;
var arrayLastIndexOf = ArrayProto.lastIndexOf;
var arrayReduce = ArrayProto.reduce;
var arrayReduceRight = ArrayProto.reduceRight;
var arrayJoin = ArrayProto.join;
var arraySort = ArrayProto.sort;
var arraySlice = ArrayProto.slice;
var arrayToString = ArrayProto.toString;
var arrayToLocaleString = ArrayProto.toLocaleString;
var ITERATOR = wks('iterator');
var TAG = wks('toStringTag');
var TYPED_CONSTRUCTOR = uid('typed_constructor');
var DEF_CONSTRUCTOR = uid('def_constructor');
var ALL_CONSTRUCTORS = $typed.CONSTR;
var TYPED_ARRAY = $typed.TYPED;
var VIEW = $typed.VIEW;
var WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function (O, length) {
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function () {
// eslint-disable-next-line no-undef
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () {
new Uint8Array(1).set({});
});
var toOffset = function (it, BYTES) {
var offset = toInteger(it);
if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!');
return offset;
};
var validate = function (it) {
if (isObject(it) && TYPED_ARRAY in it) return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function (C, length) {
if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) {
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function (O, list) {
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function (C, list) {
var index = 0;
var length = list.length;
var result = allocate(C, length);
while (length > index) result[index] = list[index++];
return result;
};
var addGetter = function (it, key, internal) {
dP(it, key, { get: function () { return this._d[internal]; } });
};
var $from = function from(source /* , mapfn, thisArg */) {
var O = toObject(source);
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var iterFn = getIterFn(O);
var i, length, values, result, step, iterator;
if (iterFn != undefined && !isArrayIter(iterFn)) {
for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) {
values.push(step.value);
} O = values;
}
if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2);
for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) {
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/* ...items */) {
var index = 0;
var length = arguments.length;
var result = allocate(this, length);
while (length > index) result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString() {
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /* , end */) {
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /* , thisArg */) {
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /* , thisArg */) {
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /* , thisArg */) {
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /* , thisArg */) {
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /* , thisArg */) {
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /* , fromIndex */) {
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /* , fromIndex */) {
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator) { // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /* , thisArg */) {
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse() {
var that = this;
var length = validate(that).length;
var middle = Math.floor(length / 2);
var index = 0;
var value;
while (index < middle) {
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /* , thisArg */) {
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn) {
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end) {
var O = validate(this);
var length = O.length;
var $begin = toAbsoluteIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end) {
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /* , offset */) {
validate(this);
var offset = toOffset(arguments[1], 1);
var length = this.length;
var src = toObject(arrayLike);
var len = toLength(src.length);
var index = 0;
if (len + offset > length) throw RangeError(WRONG_LENGTH);
while (index < len) this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries() {
return arrayEntries.call(validate(this));
},
keys: function keys() {
return arrayKeys.call(validate(this));
},
values: function values() {
return arrayValues.call(validate(this));
}
};
var isTAIndex = function (target, key) {
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key) {
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc) {
if (isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
) {
target[key] = desc.value;
return target;
} return dP(target, key, desc);
};
if (!ALL_CONSTRUCTORS) {
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if (fails(function () { arrayToString.call({}); })) {
arrayToString = arrayToLocaleString = function toString() {
return arrayJoin.call(this);
};
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function () { /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function () { return this[TYPED_ARRAY]; }
});
// eslint-disable-next-line max-statements
module.exports = function (KEY, BYTES, wrapper, CLAMPED) {
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array';
var GETTER = 'get' + KEY;
var SETTER = 'set' + KEY;
var TypedArray = global[NAME];
var Base = TypedArray || {};
var TAC = TypedArray && getPrototypeOf(TypedArray);
var FORCED = !TypedArray || !$typed.ABV;
var O = {};
var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function (that, index) {
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function (that, index, value) {
var data = that._d;
if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function (that, index) {
dP(that, index, {
get: function () {
return getter(this, index);
},
set: function (value) {
return setter(this, index, value);
},
enumerable: true
});
};
if (FORCED) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME, '_d');
var index = 0;
var offset = 0;
var buffer, byteLength, length, klass;
if (!isObject(data)) {
length = toIndex(data);
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if ($length === undefined) {
if ($len % BYTES) throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if (byteLength < 0) throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if (TYPED_ARRAY in data) {
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while (index < length) addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if (!fails(function () {
TypedArray(1);
}) || !fails(function () {
new TypedArray(-1); // eslint-disable-line no-new
}) || !$iterDetect(function (iter) {
new TypedArray(); // eslint-disable-line no-new
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(1.5); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)) {
TypedArray = wrapper(function (that, data, $offset, $length) {
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if (!isObject(data)) return new Base(toIndex(data));
if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) {
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if (TYPED_ARRAY in data) return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) {
if (!(key in TypedArray)) hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR];
var CORRECT_ITER_NAME = !!$nativeIterator
&& ($nativeIterator.name == 'values' || $nativeIterator.name == undefined);
var $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) {
dP(TypedArrayPrototype, TAG, {
get: function () { return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES
});
$export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, {
from: $from,
of: $of
});
if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, { set: $set });
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString;
$export($export.P + $export.F * fails(function () {
new TypedArray(1).slice();
}), NAME, { slice: $slice });
$export($export.P + $export.F * (fails(function () {
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString();
}) || !fails(function () {
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, { toLocaleString: $toLocaleString });
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function () { /* empty */ };
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
const glamor_1 = __webpack_require__(104);
const render_utils_1 = __webpack_require__(37);
const DEFAULT_SUBSURFACE_OPTS = {
prepend: false,
};
/**
* Utility function to create/retrieve divs within an HTMLElement|Surface
*/
function subSurface(parent, name, opts = {}) {
const container = render_utils_1.getDrawArea(parent);
const style = glamor_1.css({
'& canvas': {
display: 'block',
},
marginTop: '.5rem',
marginBottom: '.5rem',
});
const titleStyle = glamor_1.css({
backgroundColor: 'white',
display: 'inline-block',
boxSizing: 'border-box',
borderBottom: '1px solid #357EDD',
lineHeight: '2em',
padding: '0 10px 0 10px',
marginBottom: '20px',
fontWeight: '600',
textAlign: 'left',
});
const options = Object.assign({}, DEFAULT_SUBSURFACE_OPTS, opts);
let sub = container.querySelector(`div[data-name=${name}]`);
if (!sub) {
sub = document.createElement('div');
sub.setAttribute('class', `${style}`);
sub.dataset.name = name;
if (options.title) {
const title = document.createElement('div');
title.setAttribute('class', `subsurface-title ${titleStyle}`);
title.innerText = options.title;
sub.appendChild(title);
}
if (options.prepend) {
container.insertBefore(sub, container.firstChild);
}
else {
container.appendChild(sub);
}
}
return sub;
}
exports.subSurface = subSurface;
function getDefaultWidth(element) {
const DEFAULT_PADDING = 50;
let padding = 0;
let current = element;
while (current && current.clientWidth === 0) {
current = current.parentElement;
padding = DEFAULT_PADDING;
}
return (current.clientWidth - padding);
}
exports.getDefaultWidth = getDefaultWidth;
function getDefaultHeight(element) {
if (element.clientHeight === 0) {
return 200;
}
else {
return element.clientHeight;
}
}
exports.getDefaultHeight = getDefaultHeight;
//# sourceMappingURL=dom.js.map
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(39);
var createDesc = __webpack_require__(108);
module.exports = __webpack_require__(32) ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(16)('unscopables');
var ArrayProto = Array.prototype;
if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(31)(ArrayProto, UNSCOPABLES, {});
module.exports = function (key) {
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
var META = __webpack_require__(78)('meta');
var isObject = __webpack_require__(13);
var has = __webpack_require__(36);
var setDesc = __webpack_require__(21).f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !__webpack_require__(12)(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ }),
/* 63 */
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _isIterable2 = __webpack_require__(378);
var _isIterable3 = _interopRequireDefault(_isIterable2);
var _getIterator2 = __webpack_require__(375);
var _getIterator3 = _interopRequireDefault(_getIterator2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if ((0, _isIterable3.default)(Object(arr))) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(162);
module.exports = function (it) {
return Object(defined(it));
};
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(163);
var defined = __webpack_require__(162);
module.exports = function (it) {
return IObject(defined(it));
};
/***/ }),
/* 67 */
/***/ (function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
/***/ }),
/* 68 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
module.exports = function (it, TYPE) {
if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
return it;
};
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(30);
module.exports = function (target, src, safe) {
for (var key in src) redefine(target, key, src[key], safe);
return target;
};
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(43);
var call = __webpack_require__(267);
var isArrayIter = __webpack_require__(177);
var anObject = __webpack_require__(6);
var toLength = __webpack_require__(17);
var getIterFn = __webpack_require__(175);
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var length, step, iterator, result;
if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if (result === BREAK || result === RETURN) return result;
} else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
if (result === BREAK || result === RETURN) return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ }),
/* 72 */
/***/ (function(module, exports) {
module.exports = function (it, Constructor, name, forbiddenField) {
if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(11);
var dP = __webpack_require__(21);
var DESCRIPTORS = __webpack_require__(19);
var SPECIES = __webpack_require__(16)('species');
module.exports = function (KEY) {
var C = global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(280);
var hiddenKeys = __webpack_require__(189).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(6);
var dPs = __webpack_require__(279);
var enumBugKeys = __webpack_require__(189);
var IE_PROTO = __webpack_require__(190)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(192)('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__(188).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(41);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(280);
var enumBugKeys = __webpack_require__(189);
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/* 78 */
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 79 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function (data, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (node) {
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
if (node === undefined) return;
if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
if (typeof node !== 'object') return JSON.stringify(node);
var i, out;
if (Array.isArray(node)) {
out = '[';
for (i = 0; i < node.length; i++) {
if (i) out += ',';
out += stringify(node[i]) || 'null';
}
return out + ']';
}
if (node === null) return 'null';
if (seen.indexOf(node) !== -1) {
if (cycles) return JSON.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
var seenIndex = seen.push(node) - 1;
var keys = Object.keys(node).sort(cmp && cmp(node));
out = '';
for (i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node[key]);
if (!value) continue;
if (out) out += ',';
out += JSON.stringify(key) + ':' + value;
}
seen.splice(seenIndex, 1);
return '{' + out + '}';
})(data);
};
/***/ }),
/* 81 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var vega_transforms_namespaceObject = {};
__webpack_require__.d(vega_transforms_namespaceObject, "aggregate", function() { return Aggregate_Aggregate; });
__webpack_require__.d(vega_transforms_namespaceObject, "bin", function() { return Bin_Bin; });
__webpack_require__.d(vega_transforms_namespaceObject, "collect", function() { return Collect_Collect; });
__webpack_require__.d(vega_transforms_namespaceObject, "compare", function() { return Compare_Compare; });
__webpack_require__.d(vega_transforms_namespaceObject, "countpattern", function() { return CountPattern_CountPattern; });
__webpack_require__.d(vega_transforms_namespaceObject, "cross", function() { return Cross_Cross; });
__webpack_require__.d(vega_transforms_namespaceObject, "density", function() { return Density_Density; });
__webpack_require__.d(vega_transforms_namespaceObject, "dotbin", function() { return DotBin_DotBin; });
__webpack_require__.d(vega_transforms_namespaceObject, "expression", function() { return Expression_Expression; });
__webpack_require__.d(vega_transforms_namespaceObject, "extent", function() { return Extent_Extent; });
__webpack_require__.d(vega_transforms_namespaceObject, "facet", function() { return Facet_Facet; });
__webpack_require__.d(vega_transforms_namespaceObject, "field", function() { return Field_Field; });
__webpack_require__.d(vega_transforms_namespaceObject, "filter", function() { return Filter_Filter; });
__webpack_require__.d(vega_transforms_namespaceObject, "flatten", function() { return Flatten_Flatten; });
__webpack_require__.d(vega_transforms_namespaceObject, "fold", function() { return Fold_Fold; });
__webpack_require__.d(vega_transforms_namespaceObject, "formula", function() { return Formula_Formula; });
__webpack_require__.d(vega_transforms_namespaceObject, "generate", function() { return Generate_Generate; });
__webpack_require__.d(vega_transforms_namespaceObject, "impute", function() { return Impute_Impute; });
__webpack_require__.d(vega_transforms_namespaceObject, "joinaggregate", function() { return JoinAggregate_JoinAggregate; });
__webpack_require__.d(vega_transforms_namespaceObject, "kde", function() { return KDE_KDE; });
__webpack_require__.d(vega_transforms_namespaceObject, "key", function() { return Key_Key; });
__webpack_require__.d(vega_transforms_namespaceObject, "load", function() { return Load_Load; });
__webpack_require__.d(vega_transforms_namespaceObject, "lookup", function() { return Lookup_Lookup; });
__webpack_require__.d(vega_transforms_namespaceObject, "multiextent", function() { return MultiExtent_MultiExtent; });
__webpack_require__.d(vega_transforms_namespaceObject, "multivalues", function() { return MultiValues_MultiValues; });
__webpack_require__.d(vega_transforms_namespaceObject, "params", function() { return Params_Params; });
__webpack_require__.d(vega_transforms_namespaceObject, "pivot", function() { return Pivot_Pivot; });
__webpack_require__.d(vega_transforms_namespaceObject, "prefacet", function() { return PreFacet_PreFacet; });
__webpack_require__.d(vega_transforms_namespaceObject, "project", function() { return Project_Project; });
__webpack_require__.d(vega_transforms_namespaceObject, "proxy", function() { return Proxy_Proxy; });
__webpack_require__.d(vega_transforms_namespaceObject, "quantile", function() { return Quantile_Quantile; });
__webpack_require__.d(vega_transforms_namespaceObject, "relay", function() { return Relay_Relay; });
__webpack_require__.d(vega_transforms_namespaceObject, "sample", function() { return Sample_Sample; });
__webpack_require__.d(vega_transforms_namespaceObject, "sequence", function() { return Sequence_Sequence; });
__webpack_require__.d(vega_transforms_namespaceObject, "sieve", function() { return Sieve_Sieve; });
__webpack_require__.d(vega_transforms_namespaceObject, "subflow", function() { return Subflow_Subflow; });
__webpack_require__.d(vega_transforms_namespaceObject, "timeunit", function() { return TimeUnit_TimeUnit; });
__webpack_require__.d(vega_transforms_namespaceObject, "tupleindex", function() { return TupleIndex_TupleIndex; });
__webpack_require__.d(vega_transforms_namespaceObject, "values", function() { return Values_Values; });
__webpack_require__.d(vega_transforms_namespaceObject, "window", function() { return Window_Window; });
var vega_view_transforms_namespaceObject = {};
__webpack_require__.d(vega_view_transforms_namespaceObject, "bound", function() { return Bound_Bound; });
__webpack_require__.d(vega_view_transforms_namespaceObject, "identifier", function() { return Identifier_Identifier; });
__webpack_require__.d(vega_view_transforms_namespaceObject, "mark", function() { return Mark_Mark; });
__webpack_require__.d(vega_view_transforms_namespaceObject, "overlap", function() { return Overlap_Overlap; });
__webpack_require__.d(vega_view_transforms_namespaceObject, "render", function() { return Render_Render; });
__webpack_require__.d(vega_view_transforms_namespaceObject, "viewlayout", function() { return ViewLayout_ViewLayout; });
var d3_interpolate_src_namespaceObject = {};
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolate", function() { return src_value; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateArray", function() { return src_array; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateBasis", function() { return src_basis; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateBasisClosed", function() { return src_basisClosed; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateDate", function() { return src_date; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateDiscrete", function() { return discrete; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateHue", function() { return src_hue; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateNumber", function() { return d3_interpolate_src_number; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateNumberArray", function() { return numberArray; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateObject", function() { return src_object; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateRound", function() { return src_round; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateString", function() { return src_string; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateTransformCss", function() { return transform_interpolateTransformCss; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateTransformSvg", function() { return transform_interpolateTransformSvg; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateZoom", function() { return src_zoom; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateRgb", function() { return src_rgb; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateRgbBasis", function() { return rgb_rgbBasis; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateRgbBasisClosed", function() { return rgb_rgbBasisClosed; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateHsl", function() { return src_hsl; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateHslLong", function() { return hsl_hslLong; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateLab", function() { return src_lab_lab; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateHcl", function() { return src_hcl; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateHclLong", function() { return hcl_hclLong; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateCubehelix", function() { return src_cubehelix; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "interpolateCubehelixLong", function() { return cubehelix_cubehelixLong; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "piecewise", function() { return piecewise_piecewise; });
__webpack_require__.d(d3_interpolate_src_namespaceObject, "quantize", function() { return d3_interpolate_src_quantize; });
var vega_encode_namespaceObject = {};
__webpack_require__.d(vega_encode_namespaceObject, "axisticks", function() { return AxisTicks_AxisTicks; });
__webpack_require__.d(vega_encode_namespaceObject, "datajoin", function() { return DataJoin_DataJoin; });
__webpack_require__.d(vega_encode_namespaceObject, "encode", function() { return Encode_Encode; });
__webpack_require__.d(vega_encode_namespaceObject, "legendentries", function() { return LegendEntries_LegendEntries; });
__webpack_require__.d(vega_encode_namespaceObject, "linkpath", function() { return LinkPath_LinkPath; });
__webpack_require__.d(vega_encode_namespaceObject, "pie", function() { return Pie_Pie; });
__webpack_require__.d(vega_encode_namespaceObject, "scale", function() { return Scale_Scale; });
__webpack_require__.d(vega_encode_namespaceObject, "sortitems", function() { return SortItems_SortItems; });
__webpack_require__.d(vega_encode_namespaceObject, "stack", function() { return Stack_Stack; });
__webpack_require__.d(vega_encode_namespaceObject, "validTicks", function() { return ticks_validTicks; });
var vega_geo_namespaceObject = {};
__webpack_require__.d(vega_geo_namespaceObject, "contour", function() { return Contour_Contour; });
__webpack_require__.d(vega_geo_namespaceObject, "geojson", function() { return GeoJSON_GeoJSON; });
__webpack_require__.d(vega_geo_namespaceObject, "geopath", function() { return GeoPath_GeoPath; });
__webpack_require__.d(vega_geo_namespaceObject, "geopoint", function() { return GeoPoint_GeoPoint; });
__webpack_require__.d(vega_geo_namespaceObject, "geoshape", function() { return GeoShape_GeoShape; });
__webpack_require__.d(vega_geo_namespaceObject, "graticule", function() { return Graticule_Graticule; });
__webpack_require__.d(vega_geo_namespaceObject, "heatmap", function() { return Heatmap_Heatmap; });
__webpack_require__.d(vega_geo_namespaceObject, "isocontour", function() { return Isocontour_Isocontour; });
__webpack_require__.d(vega_geo_namespaceObject, "kde2d", function() { return KDE2D_KDE2D; });
__webpack_require__.d(vega_geo_namespaceObject, "projection", function() { return Projection_Projection; });
var vega_force_namespaceObject = {};
__webpack_require__.d(vega_force_namespaceObject, "force", function() { return Force_Force; });
var vega_hierarchy_namespaceObject = {};
__webpack_require__.d(vega_hierarchy_namespaceObject, "nest", function() { return Nest_Nest; });
__webpack_require__.d(vega_hierarchy_namespaceObject, "pack", function() { return Pack_Pack; });
__webpack_require__.d(vega_hierarchy_namespaceObject, "partition", function() { return Partition_Partition; });
__webpack_require__.d(vega_hierarchy_namespaceObject, "stratify", function() { return Stratify_Stratify; });
__webpack_require__.d(vega_hierarchy_namespaceObject, "tree", function() { return Tree_Tree; });
__webpack_require__.d(vega_hierarchy_namespaceObject, "treelinks", function() { return TreeLinks_TreeLinks; });
__webpack_require__.d(vega_hierarchy_namespaceObject, "treemap", function() { return Treemap_Treemap; });
var vega_regression_namespaceObject = {};
__webpack_require__.d(vega_regression_namespaceObject, "loess", function() { return Loess_Loess; });
__webpack_require__.d(vega_regression_namespaceObject, "regression", function() { return Regression_Regression; });
var vega_voronoi_namespaceObject = {};
__webpack_require__.d(vega_voronoi_namespaceObject, "voronoi", function() { return Voronoi_Voronoi; });
var vega_wordcloud_namespaceObject = {};
__webpack_require__.d(vega_wordcloud_namespaceObject, "wordcloud", function() { return Wordcloud_Wordcloud; });
var vega_crossfilter_namespaceObject = {};
__webpack_require__.d(vega_crossfilter_namespaceObject, "crossfilter", function() { return CrossFilter_CrossFilter; });
__webpack_require__.d(vega_crossfilter_namespaceObject, "resolvefilter", function() { return ResolveFilter_ResolveFilter; });
var vega_namespaceObject = {};
__webpack_require__.d(vega_namespaceObject, "version", function() { return vega_package["a" /* version */]; });
__webpack_require__.d(vega_namespaceObject, "Dataflow", function() { return Dataflow_Dataflow; });
__webpack_require__.d(vega_namespaceObject, "EventStream", function() { return EventStream_EventStream; });
__webpack_require__.d(vega_namespaceObject, "Parameters", function() { return Parameters_Parameters; });
__webpack_require__.d(vega_namespaceObject, "Pulse", function() { return Pulse_Pulse; });
__webpack_require__.d(vega_namespaceObject, "MultiPulse", function() { return MultiPulse_MultiPulse; });
__webpack_require__.d(vega_namespaceObject, "Operator", function() { return Operator_Operator; });
__webpack_require__.d(vega_namespaceObject, "Transform", function() { return Transform_Transform; });
__webpack_require__.d(vega_namespaceObject, "changeset", function() { return ChangeSet_changeset; });
__webpack_require__.d(vega_namespaceObject, "ingest", function() { return Tuple_ingest; });
__webpack_require__.d(vega_namespaceObject, "isTuple", function() { return isTuple; });
__webpack_require__.d(vega_namespaceObject, "definition", function() { return register_definition; });
__webpack_require__.d(vega_namespaceObject, "transform", function() { return register_transform; });
__webpack_require__.d(vega_namespaceObject, "transforms", function() { return register_transforms; });
__webpack_require__.d(vega_namespaceObject, "tupleid", function() { return tupleid; });
__webpack_require__.d(vega_namespaceObject, "scale", function() { return vega_scale_src_scales_scale; });
__webpack_require__.d(vega_namespaceObject, "scheme", function() { return vega_scale_src_schemes_scheme; });
__webpack_require__.d(vega_namespaceObject, "interpolate", function() { return vega_scale_src_interpolate_interpolate; });
__webpack_require__.d(vega_namespaceObject, "interpolateColors", function() { return vega_scale_src_interpolate_interpolateColors; });
__webpack_require__.d(vega_namespaceObject, "interpolateRange", function() { return vega_scale_src_interpolate_interpolateRange; });
__webpack_require__.d(vega_namespaceObject, "timeInterval", function() { return timeInterval_timeInterval; });
__webpack_require__.d(vega_namespaceObject, "quantizeInterpolator", function() { return vega_scale_src_interpolate_quantizeInterpolator; });
__webpack_require__.d(vega_namespaceObject, "projection", function() { return projections_projection; });
__webpack_require__.d(vega_namespaceObject, "View", function() { return View_View; });
__webpack_require__.d(vega_namespaceObject, "expressionFunction", function() { return codegen_expressionFunction; });
__webpack_require__.d(vega_namespaceObject, "formatLocale", function() { return d3_format_src_defaultLocale_defaultLocale; });
__webpack_require__.d(vega_namespaceObject, "timeFormatLocale", function() { return defaultLocale_defaultLocale; });
__webpack_require__.d(vega_namespaceObject, "parse", function() { return src_parse; });
__webpack_require__.d(vega_namespaceObject, "runtime", function() { return src_dataflow; });
__webpack_require__.d(vega_namespaceObject, "runtimeContext", function() { return src_context; });
__webpack_require__.d(vega_namespaceObject, "bandwidthNRD", function() { return src_bandwidth; });
__webpack_require__.d(vega_namespaceObject, "bin", function() { return src_bin; });
__webpack_require__.d(vega_namespaceObject, "bootstrapCI", function() { return bootstrapCI; });
__webpack_require__.d(vega_namespaceObject, "dotbin", function() { return dotbin; });
__webpack_require__.d(vega_namespaceObject, "quantiles", function() { return quantiles; });
__webpack_require__.d(vega_namespaceObject, "quartiles", function() { return quartiles; });
__webpack_require__.d(vega_namespaceObject, "random", function() { return random_random; });
__webpack_require__.d(vega_namespaceObject, "setRandom", function() { return setRandom; });
__webpack_require__.d(vega_namespaceObject, "randomLCG", function() { return lcg; });
__webpack_require__.d(vega_namespaceObject, "randomInteger", function() { return integer; });
__webpack_require__.d(vega_namespaceObject, "randomKDE", function() { return src_kde; });
__webpack_require__.d(vega_namespaceObject, "randomLogNormal", function() { return lognormal; });
__webpack_require__.d(vega_namespaceObject, "sampleLogNormal", function() { return lognormal_sampleLogNormal; });
__webpack_require__.d(vega_namespaceObject, "densityLogNormal", function() { return lognormal_densityLogNormal; });
__webpack_require__.d(vega_namespaceObject, "cumulativeLogNormal", function() { return lognormal_cumulativeLogNormal; });
__webpack_require__.d(vega_namespaceObject, "quantileLogNormal", function() { return lognormal_quantileLogNormal; });
__webpack_require__.d(vega_namespaceObject, "randomMixture", function() { return src_mixture; });
__webpack_require__.d(vega_namespaceObject, "randomNormal", function() { return src_normal; });
__webpack_require__.d(vega_namespaceObject, "sampleNormal", function() { return normal_sampleNormal; });
__webpack_require__.d(vega_namespaceObject, "densityNormal", function() { return normal_densityNormal; });
__webpack_require__.d(vega_namespaceObject, "cumulativeNormal", function() { return normal_cumulativeNormal; });
__webpack_require__.d(vega_namespaceObject, "quantileNormal", function() { return normal_quantileNormal; });
__webpack_require__.d(vega_namespaceObject, "randomUniform", function() { return uniform; });
__webpack_require__.d(vega_namespaceObject, "sampleUniform", function() { return uniform_sampleUniform; });
__webpack_require__.d(vega_namespaceObject, "densityUniform", function() { return uniform_densityUniform; });
__webpack_require__.d(vega_namespaceObject, "cumulativeUniform", function() { return uniform_cumulativeUniform; });
__webpack_require__.d(vega_namespaceObject, "quantileUniform", function() { return uniform_quantileUniform; });
__webpack_require__.d(vega_namespaceObject, "regressionLinear", function() { return regression_linear; });
__webpack_require__.d(vega_namespaceObject, "regressionLog", function() { return regression_log; });
__webpack_require__.d(vega_namespaceObject, "regressionExp", function() { return regression_exp; });
__webpack_require__.d(vega_namespaceObject, "regressionPow", function() { return regression_pow; });
__webpack_require__.d(vega_namespaceObject, "regressionQuad", function() { return regression_quad; });
__webpack_require__.d(vega_namespaceObject, "regressionPoly", function() { return poly; });
__webpack_require__.d(vega_namespaceObject, "regressionLoess", function() { return regression_loess; });
__webpack_require__.d(vega_namespaceObject, "sampleCurve", function() { return sampleCurve; });
__webpack_require__.d(vega_namespaceObject, "accessor", function() { return vega_util["f" /* accessor */]; });
__webpack_require__.d(vega_namespaceObject, "accessorName", function() { return vega_util["h" /* accessorName */]; });
__webpack_require__.d(vega_namespaceObject, "accessorFields", function() { return vega_util["g" /* accessorFields */]; });
__webpack_require__.d(vega_namespaceObject, "id", function() { return vega_util["w" /* id */]; });
__webpack_require__.d(vega_namespaceObject, "identity", function() { return vega_util["x" /* identity */]; });
__webpack_require__.d(vega_namespaceObject, "zero", function() { return vega_util["Ka" /* zero */]; });
__webpack_require__.d(vega_namespaceObject, "one", function() { return vega_util["O" /* one */]; });
__webpack_require__.d(vega_namespaceObject, "truthy", function() { return vega_util["Ga" /* truthy */]; });
__webpack_require__.d(vega_namespaceObject, "falsy", function() { return vega_util["r" /* falsy */]; });
__webpack_require__.d(vega_namespaceObject, "logger", function() { return vega_util["K" /* logger */]; });
__webpack_require__.d(vega_namespaceObject, "None", function() { return vega_util["d" /* None */]; });
__webpack_require__.d(vega_namespaceObject, "Error", function() { return vega_util["b" /* Error */]; });
__webpack_require__.d(vega_namespaceObject, "Warn", function() { return vega_util["e" /* Warn */]; });
__webpack_require__.d(vega_namespaceObject, "Info", function() { return vega_util["c" /* Info */]; });
__webpack_require__.d(vega_namespaceObject, "Debug", function() { return vega_util["a" /* Debug */]; });
__webpack_require__.d(vega_namespaceObject, "mergeConfig", function() { return vega_util["N" /* mergeConfig */]; });
__webpack_require__.d(vega_namespaceObject, "writeConfig", function() { return vega_util["Ja" /* writeConfig */]; });
__webpack_require__.d(vega_namespaceObject, "panLinear", function() { return vega_util["Q" /* panLinear */]; });
__webpack_require__.d(vega_namespaceObject, "panLog", function() { return vega_util["R" /* panLog */]; });
__webpack_require__.d(vega_namespaceObject, "panPow", function() { return vega_util["S" /* panPow */]; });
__webpack_require__.d(vega_namespaceObject, "panSymlog", function() { return vega_util["T" /* panSymlog */]; });
__webpack_require__.d(vega_namespaceObject, "zoomLinear", function() { return vega_util["La" /* zoomLinear */]; });
__webpack_require__.d(vega_namespaceObject, "zoomLog", function() { return vega_util["Ma" /* zoomLog */]; });
__webpack_require__.d(vega_namespaceObject, "zoomPow", function() { return vega_util["Na" /* zoomPow */]; });
__webpack_require__.d(vega_namespaceObject, "zoomSymlog", function() { return vega_util["Oa" /* zoomSymlog */]; });
__webpack_require__.d(vega_namespaceObject, "quarter", function() { return vega_util["V" /* quarter */]; });
__webpack_require__.d(vega_namespaceObject, "utcquarter", function() { return vega_util["Ha" /* utcquarter */]; });
__webpack_require__.d(vega_namespaceObject, "array", function() { return vega_util["i" /* array */]; });
__webpack_require__.d(vega_namespaceObject, "clampRange", function() { return vega_util["j" /* clampRange */]; });
__webpack_require__.d(vega_namespaceObject, "compare", function() { return vega_util["k" /* compare */]; });
__webpack_require__.d(vega_namespaceObject, "constant", function() { return vega_util["l" /* constant */]; });
__webpack_require__.d(vega_namespaceObject, "debounce", function() { return vega_util["m" /* debounce */]; });
__webpack_require__.d(vega_namespaceObject, "error", function() { return vega_util["n" /* error */]; });
__webpack_require__.d(vega_namespaceObject, "extend", function() { return vega_util["o" /* extend */]; });
__webpack_require__.d(vega_namespaceObject, "extent", function() { return vega_util["p" /* extent */]; });
__webpack_require__.d(vega_namespaceObject, "extentIndex", function() { return vega_util["q" /* extentIndex */]; });
__webpack_require__.d(vega_namespaceObject, "fastmap", function() { return vega_util["s" /* fastmap */]; });
__webpack_require__.d(vega_namespaceObject, "field", function() { return vega_util["t" /* field */]; });
__webpack_require__.d(vega_namespaceObject, "flush", function() { return vega_util["u" /* flush */]; });
__webpack_require__.d(vega_namespaceObject, "hasOwnProperty", function() { return vega_util["v" /* hasOwnProperty */]; });
__webpack_require__.d(vega_namespaceObject, "inherits", function() { return vega_util["y" /* inherits */]; });
__webpack_require__.d(vega_namespaceObject, "inrange", function() { return vega_util["z" /* inrange */]; });
__webpack_require__.d(vega_namespaceObject, "isArray", function() { return vega_util["A" /* isArray */]; });
__webpack_require__.d(vega_namespaceObject, "isBoolean", function() { return vega_util["B" /* isBoolean */]; });
__webpack_require__.d(vega_namespaceObject, "isDate", function() { return vega_util["C" /* isDate */]; });
__webpack_require__.d(vega_namespaceObject, "isFunction", function() { return vega_util["D" /* isFunction */]; });
__webpack_require__.d(vega_namespaceObject, "isNumber", function() { return vega_util["E" /* isNumber */]; });
__webpack_require__.d(vega_namespaceObject, "isObject", function() { return vega_util["F" /* isObject */]; });
__webpack_require__.d(vega_namespaceObject, "isRegExp", function() { return vega_util["G" /* isRegExp */]; });
__webpack_require__.d(vega_namespaceObject, "isString", function() { return vega_util["H" /* isString */]; });
__webpack_require__.d(vega_namespaceObject, "key", function() { return vega_util["I" /* key */]; });
__webpack_require__.d(vega_namespaceObject, "lerp", function() { return vega_util["J" /* lerp */]; });
__webpack_require__.d(vega_namespaceObject, "lruCache", function() { return vega_util["L" /* lruCache */]; });
__webpack_require__.d(vega_namespaceObject, "merge", function() { return vega_util["M" /* merge */]; });
__webpack_require__.d(vega_namespaceObject, "pad", function() { return vega_util["P" /* pad */]; });
__webpack_require__.d(vega_namespaceObject, "peek", function() { return vega_util["U" /* peek */]; });
__webpack_require__.d(vega_namespaceObject, "repeat", function() { return vega_util["W" /* repeat */]; });
__webpack_require__.d(vega_namespaceObject, "span", function() { return vega_util["X" /* span */]; });
__webpack_require__.d(vega_namespaceObject, "splitAccessPath", function() { return vega_util["Y" /* splitAccessPath */]; });
__webpack_require__.d(vega_namespaceObject, "stringValue", function() { return vega_util["Z" /* stringValue */]; });
__webpack_require__.d(vega_namespaceObject, "toBoolean", function() { return vega_util["Aa" /* toBoolean */]; });
__webpack_require__.d(vega_namespaceObject, "toDate", function() { return vega_util["Ba" /* toDate */]; });
__webpack_require__.d(vega_namespaceObject, "toNumber", function() { return vega_util["Ca" /* toNumber */]; });
__webpack_require__.d(vega_namespaceObject, "toString", function() { return vega_util["Ea" /* toString */]; });
__webpack_require__.d(vega_namespaceObject, "toSet", function() { return vega_util["Da" /* toSet */]; });
__webpack_require__.d(vega_namespaceObject, "truncate", function() { return vega_util["Fa" /* truncate */]; });
__webpack_require__.d(vega_namespaceObject, "visitArray", function() { return vega_util["Ia" /* visitArray */]; });
__webpack_require__.d(vega_namespaceObject, "loader", function() { return index_browser_loader; });
__webpack_require__.d(vega_namespaceObject, "read", function() { return read; });
__webpack_require__.d(vega_namespaceObject, "inferType", function() { return type_inferType; });
__webpack_require__.d(vega_namespaceObject, "inferTypes", function() { return type_inferTypes; });
__webpack_require__.d(vega_namespaceObject, "typeParsers", function() { return type_typeParsers; });
__webpack_require__.d(vega_namespaceObject, "format", function() { return formats_format; });
__webpack_require__.d(vega_namespaceObject, "formats", function() { return formats_formats; });
__webpack_require__.d(vega_namespaceObject, "responseType", function() { return formats_responseType; });
__webpack_require__.d(vega_namespaceObject, "Bounds", function() { return Bounds; });
__webpack_require__.d(vega_namespaceObject, "Gradient", function() { return Gradient; });
__webpack_require__.d(vega_namespaceObject, "GroupItem", function() { return GroupItem_GroupItem; });
__webpack_require__.d(vega_namespaceObject, "ResourceLoader", function() { return ResourceLoader_ResourceLoader; });
__webpack_require__.d(vega_namespaceObject, "Item", function() { return Item_Item; });
__webpack_require__.d(vega_namespaceObject, "Scenegraph", function() { return Scenegraph_Scenegraph; });
__webpack_require__.d(vega_namespaceObject, "Handler", function() { return Handler_Handler; });
__webpack_require__.d(vega_namespaceObject, "Renderer", function() { return Renderer_Renderer; });
__webpack_require__.d(vega_namespaceObject, "CanvasHandler", function() { return CanvasHandler_CanvasHandler; });
__webpack_require__.d(vega_namespaceObject, "CanvasRenderer", function() { return CanvasRenderer_CanvasRenderer; });
__webpack_require__.d(vega_namespaceObject, "SVGHandler", function() { return SVGHandler_SVGHandler; });
__webpack_require__.d(vega_namespaceObject, "SVGRenderer", function() { return SVGRenderer_SVGRenderer; });
__webpack_require__.d(vega_namespaceObject, "SVGStringRenderer", function() { return SVGStringRenderer_SVGStringRenderer; });
__webpack_require__.d(vega_namespaceObject, "RenderType", function() { return modules_RenderType; });
__webpack_require__.d(vega_namespaceObject, "renderModule", function() { return modules_renderModule; });
__webpack_require__.d(vega_namespaceObject, "intersect", function() { return intersect_intersect; });
__webpack_require__.d(vega_namespaceObject, "Marks", function() { return src_marks; });
__webpack_require__.d(vega_namespaceObject, "boundClip", function() { return boundClip; });
__webpack_require__.d(vega_namespaceObject, "boundContext", function() { return boundContext_context; });
__webpack_require__.d(vega_namespaceObject, "boundStroke", function() { return boundStroke; });
__webpack_require__.d(vega_namespaceObject, "boundItem", function() { return bound_boundItem; });
__webpack_require__.d(vega_namespaceObject, "boundMark", function() { return boundMark; });
__webpack_require__.d(vega_namespaceObject, "pathCurves", function() { return curves_curves; });
__webpack_require__.d(vega_namespaceObject, "pathSymbols", function() { return symbols_symbols; });
__webpack_require__.d(vega_namespaceObject, "pathRectangle", function() { return path_rectangle; });
__webpack_require__.d(vega_namespaceObject, "pathTrail", function() { return path_trail; });
__webpack_require__.d(vega_namespaceObject, "pathParse", function() { return path_parse; });
__webpack_require__.d(vega_namespaceObject, "pathRender", function() { return path_render; });
__webpack_require__.d(vega_namespaceObject, "point", function() { return util_point; });
__webpack_require__.d(vega_namespaceObject, "domCreate", function() { return domCreate; });
__webpack_require__.d(vega_namespaceObject, "domFind", function() { return domFind; });
__webpack_require__.d(vega_namespaceObject, "domChild", function() { return domChild; });
__webpack_require__.d(vega_namespaceObject, "domClear", function() { return domClear; });
__webpack_require__.d(vega_namespaceObject, "openTag", function() { return openTag; });
__webpack_require__.d(vega_namespaceObject, "closeTag", function() { return closeTag; });
__webpack_require__.d(vega_namespaceObject, "font", function() { return text_font; });
__webpack_require__.d(vega_namespaceObject, "fontFamily", function() { return text_fontFamily; });
__webpack_require__.d(vega_namespaceObject, "fontSize", function() { return text_fontSize; });
__webpack_require__.d(vega_namespaceObject, "lineHeight", function() { return text_lineHeight; });
__webpack_require__.d(vega_namespaceObject, "multiLineOffset", function() { return text_multiLineOffset; });
__webpack_require__.d(vega_namespaceObject, "textMetrics", function() { return text_textMetrics; });
__webpack_require__.d(vega_namespaceObject, "resetSVGClipId", function() { return clip_resetSVGClipId; });
__webpack_require__.d(vega_namespaceObject, "sceneEqual", function() { return equal_sceneEqual; });
__webpack_require__.d(vega_namespaceObject, "pathEqual", function() { return equal_pathEqual; });
__webpack_require__.d(vega_namespaceObject, "sceneToJSON", function() { return serialize_sceneToJSON; });
__webpack_require__.d(vega_namespaceObject, "sceneFromJSON", function() { return serialize_sceneFromJSON; });
__webpack_require__.d(vega_namespaceObject, "intersectPath", function() { return intersect_intersectPath; });
__webpack_require__.d(vega_namespaceObject, "intersectPoint", function() { return intersect_intersectPoint; });
__webpack_require__.d(vega_namespaceObject, "intersectRule", function() { return intersect_intersectRule; });
__webpack_require__.d(vega_namespaceObject, "intersectBoxLine", function() { return intersect_intersectBoxLine; });
__webpack_require__.d(vega_namespaceObject, "sceneZOrder", function() { return zorder; });
__webpack_require__.d(vega_namespaceObject, "sceneVisit", function() { return visit_visit; });
__webpack_require__.d(vega_namespaceObject, "scenePickVisit", function() { return pickVisit; });
var message_namespaceObject = {};
__webpack_require__.d(message_namespaceObject, "invalidSpec", function() { return message_invalidSpec; });
__webpack_require__.d(message_namespaceObject, "FIT_NON_SINGLE", function() { return message_FIT_NON_SINGLE; });
__webpack_require__.d(message_namespaceObject, "containerSizeNonSingle", function() { return message_containerSizeNonSingle; });
__webpack_require__.d(message_namespaceObject, "containerSizeNotCompatibleWithAutosize", function() { return message_containerSizeNotCompatibleWithAutosize; });
__webpack_require__.d(message_namespaceObject, "droppingFit", function() { return message_droppingFit; });
__webpack_require__.d(message_namespaceObject, "cannotProjectOnChannelWithoutField", function() { return message_cannotProjectOnChannelWithoutField; });
__webpack_require__.d(message_namespaceObject, "cannotProjectAggregate", function() { return message_cannotProjectAggregate; });
__webpack_require__.d(message_namespaceObject, "nearestNotSupportForContinuous", function() { return message_nearestNotSupportForContinuous; });
__webpack_require__.d(message_namespaceObject, "selectionNotSupported", function() { return message_selectionNotSupported; });
__webpack_require__.d(message_namespaceObject, "selectionNotFound", function() { return message_selectionNotFound; });
__webpack_require__.d(message_namespaceObject, "SCALE_BINDINGS_CONTINUOUS", function() { return message_SCALE_BINDINGS_CONTINUOUS; });
__webpack_require__.d(message_namespaceObject, "LEGEND_BINDINGS_PROJECT_LENGTH", function() { return message_LEGEND_BINDINGS_PROJECT_LENGTH; });
__webpack_require__.d(message_namespaceObject, "noSameUnitLookup", function() { return message_noSameUnitLookup; });
__webpack_require__.d(message_namespaceObject, "noSuchRepeatedValue", function() { return message_noSuchRepeatedValue; });
__webpack_require__.d(message_namespaceObject, "columnsNotSupportByRowCol", function() { return message_columnsNotSupportByRowCol; });
__webpack_require__.d(message_namespaceObject, "CONCAT_CANNOT_SHARE_AXIS", function() { return message_CONCAT_CANNOT_SHARE_AXIS; });
__webpack_require__.d(message_namespaceObject, "REPEAT_CANNOT_SHARE_AXIS", function() { return message_REPEAT_CANNOT_SHARE_AXIS; });
__webpack_require__.d(message_namespaceObject, "unrecognizedParse", function() { return message_unrecognizedParse; });
__webpack_require__.d(message_namespaceObject, "differentParse", function() { return message_differentParse; });
__webpack_require__.d(message_namespaceObject, "invalidTransformIgnored", function() { return message_invalidTransformIgnored; });
__webpack_require__.d(message_namespaceObject, "NO_FIELDS_NEEDS_AS", function() { return message_NO_FIELDS_NEEDS_AS; });
__webpack_require__.d(message_namespaceObject, "encodingOverridden", function() { return message_encodingOverridden; });
__webpack_require__.d(message_namespaceObject, "projectionOverridden", function() { return message_projectionOverridden; });
__webpack_require__.d(message_namespaceObject, "primitiveChannelDef", function() { return message_primitiveChannelDef; });
__webpack_require__.d(message_namespaceObject, "invalidFieldType", function() { return message_invalidFieldType; });
__webpack_require__.d(message_namespaceObject, "nonZeroScaleUsedWithLengthMark", function() { return message_nonZeroScaleUsedWithLengthMark; });
__webpack_require__.d(message_namespaceObject, "invalidFieldTypeForCountAggregate", function() { return message_invalidFieldTypeForCountAggregate; });
__webpack_require__.d(message_namespaceObject, "invalidAggregate", function() { return message_invalidAggregate; });
__webpack_require__.d(message_namespaceObject, "missingFieldType", function() { return message_missingFieldType; });
__webpack_require__.d(message_namespaceObject, "droppingColor", function() { return message_droppingColor; });
__webpack_require__.d(message_namespaceObject, "emptyFieldDef", function() { return message_emptyFieldDef; });
__webpack_require__.d(message_namespaceObject, "latLongDeprecated", function() { return message_latLongDeprecated; });
__webpack_require__.d(message_namespaceObject, "LINE_WITH_VARYING_SIZE", function() { return message_LINE_WITH_VARYING_SIZE; });
__webpack_require__.d(message_namespaceObject, "incompatibleChannel", function() { return message_incompatibleChannel; });
__webpack_require__.d(message_namespaceObject, "invalidEncodingChannel", function() { return message_invalidEncodingChannel; });
__webpack_require__.d(message_namespaceObject, "facetChannelShouldBeDiscrete", function() { return message_facetChannelShouldBeDiscrete; });
__webpack_require__.d(message_namespaceObject, "facetChannelDropped", function() { return message_facetChannelDropped; });
__webpack_require__.d(message_namespaceObject, "discreteChannelCannotEncode", function() { return message_discreteChannelCannotEncode; });
__webpack_require__.d(message_namespaceObject, "lineWithRange", function() { return message_lineWithRange; });
__webpack_require__.d(message_namespaceObject, "orientOverridden", function() { return message_orientOverridden; });
__webpack_require__.d(message_namespaceObject, "CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN", function() { return message_CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN; });
__webpack_require__.d(message_namespaceObject, "RANGE_STEP_DEPRECATED", function() { return message_RANGE_STEP_DEPRECATED; });
__webpack_require__.d(message_namespaceObject, "cannotUseScalePropertyWithNonColor", function() { return message_cannotUseScalePropertyWithNonColor; });
__webpack_require__.d(message_namespaceObject, "unaggregateDomainHasNoEffectForRawField", function() { return message_unaggregateDomainHasNoEffectForRawField; });
__webpack_require__.d(message_namespaceObject, "unaggregateDomainWithNonSharedDomainOp", function() { return message_unaggregateDomainWithNonSharedDomainOp; });
__webpack_require__.d(message_namespaceObject, "unaggregatedDomainWithLogScale", function() { return message_unaggregatedDomainWithLogScale; });
__webpack_require__.d(message_namespaceObject, "cannotApplySizeToNonOrientedMark", function() { return message_cannotApplySizeToNonOrientedMark; });
__webpack_require__.d(message_namespaceObject, "scaleTypeNotWorkWithChannel", function() { return message_scaleTypeNotWorkWithChannel; });
__webpack_require__.d(message_namespaceObject, "scaleTypeNotWorkWithFieldDef", function() { return message_scaleTypeNotWorkWithFieldDef; });
__webpack_require__.d(message_namespaceObject, "scalePropertyNotWorkWithScaleType", function() { return message_scalePropertyNotWorkWithScaleType; });
__webpack_require__.d(message_namespaceObject, "scaleTypeNotWorkWithMark", function() { return message_scaleTypeNotWorkWithMark; });
__webpack_require__.d(message_namespaceObject, "stepDropped", function() { return message_stepDropped; });
__webpack_require__.d(message_namespaceObject, "mergeConflictingProperty", function() { return message_mergeConflictingProperty; });
__webpack_require__.d(message_namespaceObject, "mergeConflictingDomainProperty", function() { return message_mergeConflictingDomainProperty; });
__webpack_require__.d(message_namespaceObject, "independentScaleMeansIndependentGuide", function() { return message_independentScaleMeansIndependentGuide; });
__webpack_require__.d(message_namespaceObject, "domainSortDropped", function() { return message_domainSortDropped; });
__webpack_require__.d(message_namespaceObject, "UNABLE_TO_MERGE_DOMAINS", function() { return message_UNABLE_TO_MERGE_DOMAINS; });
__webpack_require__.d(message_namespaceObject, "MORE_THAN_ONE_SORT", function() { return message_MORE_THAN_ONE_SORT; });
__webpack_require__.d(message_namespaceObject, "INVALID_CHANNEL_FOR_AXIS", function() { return message_INVALID_CHANNEL_FOR_AXIS; });
__webpack_require__.d(message_namespaceObject, "cannotStackRangedMark", function() { return message_cannotStackRangedMark; });
__webpack_require__.d(message_namespaceObject, "cannotStackNonLinearScale", function() { return message_cannotStackNonLinearScale; });
__webpack_require__.d(message_namespaceObject, "stackNonSummativeAggregate", function() { return message_stackNonSummativeAggregate; });
__webpack_require__.d(message_namespaceObject, "invalidTimeUnit", function() { return message_invalidTimeUnit; });
__webpack_require__.d(message_namespaceObject, "dayReplacedWithDate", function() { return message_dayReplacedWithDate; });
__webpack_require__.d(message_namespaceObject, "droppedDay", function() { return message_droppedDay; });
__webpack_require__.d(message_namespaceObject, "errorBarCenterAndExtentAreNotNeeded", function() { return message_errorBarCenterAndExtentAreNotNeeded; });
__webpack_require__.d(message_namespaceObject, "errorBarCenterIsUsedWithWrongExtent", function() { return message_errorBarCenterIsUsedWithWrongExtent; });
__webpack_require__.d(message_namespaceObject, "errorBarContinuousAxisHasCustomizedAggregate", function() { return message_errorBarContinuousAxisHasCustomizedAggregate; });
__webpack_require__.d(message_namespaceObject, "errorBarCenterIsNotNeeded", function() { return message_errorBarCenterIsNotNeeded; });
__webpack_require__.d(message_namespaceObject, "errorBand1DNotSupport", function() { return message_errorBand1DNotSupport; });
__webpack_require__.d(message_namespaceObject, "channelRequiredForBinned", function() { return message_channelRequiredForBinned; });
__webpack_require__.d(message_namespaceObject, "domainRequiredForThresholdScale", function() { return message_domainRequiredForThresholdScale; });
var legend_encode_namespaceObject = {};
__webpack_require__.d(legend_encode_namespaceObject, "symbols", function() { return encode_symbols; });
__webpack_require__.d(legend_encode_namespaceObject, "gradient", function() { return legend_encode_gradient; });
__webpack_require__.d(legend_encode_namespaceObject, "labels", function() { return encode_labels; });
__webpack_require__.d(legend_encode_namespaceObject, "entries", function() { return encode_entries; });
__webpack_require__.d(legend_encode_namespaceObject, "getFirstConditionValue", function() { return encode_getFirstConditionValue; });
var build_src_namespaceObject = {};
__webpack_require__.d(build_src_namespaceObject, "compile", function() { return compile_compile; });
__webpack_require__.d(build_src_namespaceObject, "extractTransforms", function() { return transformextract_extractTransforms; });
__webpack_require__.d(build_src_namespaceObject, "normalize", function() { return normalize_normalize; });
__webpack_require__.d(build_src_namespaceObject, "version", function() { return src_version; });
var vega_themes_build_src_namespaceObject = {};
__webpack_require__.d(vega_themes_build_src_namespaceObject, "dark", function() { return theme_dark; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "excel", function() { return theme_excel; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "fivethirtyeight", function() { return theme_fivethirtyeight; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "ggplot2", function() { return theme_ggplot2; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "latimes", function() { return theme_latimes; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "quartz", function() { return theme_quartz; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "vox", function() { return theme_vox; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "urbaninstitute", function() { return theme_urbaninstitute; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "googlecharts", function() { return theme_googlecharts; });
__webpack_require__.d(vega_themes_build_src_namespaceObject, "version", function() { return build_src_version; });
// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
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.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function tslib_es6_rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selector.js
function none() {}
/* harmony default export */ var src_selector = (function(selector) {
return selector == null ? none : function() {
return this.querySelector(selector);
};
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/select.js
/* harmony default export */ var selection_select = (function(select) {
if (typeof select !== "function") select = src_selector(select);
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
if ("__data__" in node) subnode.__data__ = node.__data__;
subgroup[i] = subnode;
}
}
}
return new selection_Selection(subgroups, this._parents);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selectorAll.js
function selectorAll_empty() {
return [];
}
/* harmony default export */ var selectorAll = (function(selector) {
return selector == null ? selectorAll_empty : function() {
return this.querySelectorAll(selector);
};
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/selectAll.js
/* harmony default export */ var selectAll = (function(select) {
if (typeof select !== "function") select = selectorAll(select);
for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
if (node = group[i]) {
subgroups.push(select.call(node, node.__data__, i, group));
parents.push(node);
}
}
}
return new selection_Selection(subgroups, parents);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/matcher.js
/* harmony default export */ var matcher = (function(selector) {
return function() {
return this.matches(selector);
};
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/filter.js
/* harmony default export */ var selection_filter = (function(match) {
if (typeof match !== "function") match = matcher(match);
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
subgroup.push(node);
}
}
}
return new selection_Selection(subgroups, this._parents);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/sparse.js
/* harmony default export */ var sparse = (function(update) {
return new Array(update.length);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/enter.js
/* harmony default export */ var selection_enter = (function() {
return new selection_Selection(this._enter || this._groups.map(sparse), this._parents);
});
function enter_EnterNode(parent, datum) {
this.ownerDocument = parent.ownerDocument;
this.namespaceURI = parent.namespaceURI;
this._next = null;
this._parent = parent;
this.__data__ = datum;
}
enter_EnterNode.prototype = {
constructor: enter_EnterNode,
appendChild: function(child) { return this._parent.insertBefore(child, this._next); },
insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },
querySelector: function(selector) { return this._parent.querySelector(selector); },
querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }
};
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/constant.js
/* harmony default export */ var src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/data.js
var data_keyPrefix = "$"; // Protect against keys like “__proto__”.
function data_bindIndex(parent, group, enter, update, exit, data) {
var i = 0,
node,
groupLength = group.length,
dataLength = data.length;
// Put any non-null nodes that fit into update.
// Put any null nodes into enter.
// Put any remaining data into enter.
for (; i < dataLength; ++i) {
if (node = group[i]) {
node.__data__ = data[i];
update[i] = node;
} else {
enter[i] = new enter_EnterNode(parent, data[i]);
}
}
// Put any non-null nodes that dont fit into exit.
for (; i < groupLength; ++i) {
if (node = group[i]) {
exit[i] = node;
}
}
}
function data_bindKey(parent, group, enter, update, exit, data, key) {
var i,
node,
nodeByKeyValue = {},
groupLength = group.length,
dataLength = data.length,
keyValues = new Array(groupLength),
keyValue;
// Compute the key for each node.
// If multiple nodes have the same key, the duplicates are added to exit.
for (i = 0; i < groupLength; ++i) {
if (node = group[i]) {
keyValues[i] = keyValue = data_keyPrefix + key.call(node, node.__data__, i, group);
if (keyValue in nodeByKeyValue) {
exit[i] = node;
} else {
nodeByKeyValue[keyValue] = node;
}
}
}
// Compute the key for each datum.
// If there a node associated with this key, join and add it to update.
// If there is not (or the key is a duplicate), add it to enter.
for (i = 0; i < dataLength; ++i) {
keyValue = data_keyPrefix + key.call(parent, data[i], i, data);
if (node = nodeByKeyValue[keyValue]) {
update[i] = node;
node.__data__ = data[i];
nodeByKeyValue[keyValue] = null;
} else {
enter[i] = new enter_EnterNode(parent, data[i]);
}
}
// Add any remaining nodes that were not bound to data to exit.
for (i = 0; i < groupLength; ++i) {
if ((node = group[i]) && (nodeByKeyValue[keyValues[i]] === node)) {
exit[i] = node;
}
}
}
/* harmony default export */ var selection_data = (function(value, key) {
if (!value) {
data = new Array(this.size()), j = -1;
this.each(function(d) { data[++j] = d; });
return data;
}
var bind = key ? data_bindKey : data_bindIndex,
parents = this._parents,
groups = this._groups;
if (typeof value !== "function") value = src_constant(value);
for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
var parent = parents[j],
group = groups[j],
groupLength = group.length,
data = value.call(parent, parent && parent.__data__, j, parents),
dataLength = data.length,
enterGroup = enter[j] = new Array(dataLength),
updateGroup = update[j] = new Array(dataLength),
exitGroup = exit[j] = new Array(groupLength);
bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
// Now connect the enter nodes to their following update node, such that
// appendChild can insert the materialized enter node before this node,
// rather than at the end of the parent node.
for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
if (previous = enterGroup[i0]) {
if (i0 >= i1) i1 = i0 + 1;
while (!(next = updateGroup[i1]) && ++i1 < dataLength);
previous._next = next || null;
}
}
}
update = new selection_Selection(update, parents);
update._enter = enter;
update._exit = exit;
return update;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/exit.js
/* harmony default export */ var selection_exit = (function() {
return new selection_Selection(this._exit || this._groups.map(sparse), this._parents);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/join.js
/* harmony default export */ var selection_join = (function(onenter, onupdate, onexit) {
var enter = this.enter(), update = this, exit = this.exit();
enter = typeof onenter === "function" ? onenter(enter) : enter.append(onenter + "");
if (onupdate != null) update = onupdate(update);
if (onexit == null) exit.remove(); else onexit(exit);
return enter && update ? enter.merge(update).order() : update;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/merge.js
/* harmony default export */ var selection_merge = (function(selection) {
for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group0[i] || group1[i]) {
merge[i] = node;
}
}
}
for (; j < m0; ++j) {
merges[j] = groups0[j];
}
return new selection_Selection(merges, this._parents);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/order.js
/* harmony default export */ var selection_order = (function() {
for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {
for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {
if (node = group[i]) {
if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next);
next = node;
}
}
}
return this;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/sort.js
/* harmony default export */ var selection_sort = (function(compare) {
if (!compare) compare = sort_ascending;
function compareNode(a, b) {
return a && b ? compare(a.__data__, b.__data__) : !a - !b;
}
for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group[i]) {
sortgroup[i] = node;
}
}
sortgroup.sort(compareNode);
}
return new selection_Selection(sortgroups, this._parents).order();
});
function sort_ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/call.js
/* harmony default export */ var call = (function() {
var callback = arguments[0];
arguments[0] = this;
callback.apply(null, arguments);
return this;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/nodes.js
/* harmony default export */ var selection_nodes = (function() {
var nodes = new Array(this.size()), i = -1;
this.each(function() { nodes[++i] = this; });
return nodes;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/node.js
/* harmony default export */ var selection_node = (function() {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
var node = group[i];
if (node) return node;
}
}
return null;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/size.js
/* harmony default export */ var selection_size = (function() {
var size = 0;
this.each(function() { ++size; });
return size;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/empty.js
/* harmony default export */ var selection_empty = (function() {
return !this.node();
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/each.js
/* harmony default export */ var each = (function(callback) {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
if (node = group[i]) callback.call(node, node.__data__, i, group);
}
}
return this;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";
/* harmony default export */ var namespaces = ({
svg: "http://www.w3.org/2000/svg",
xhtml: xhtml,
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/namespace.js
/* harmony default export */ var namespace = (function(name) {
var prefix = name += "", i = prefix.indexOf(":");
if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/attr.js
function attr_attrRemove(name) {
return function() {
this.removeAttribute(name);
};
}
function attr_attrRemoveNS(fullname) {
return function() {
this.removeAttributeNS(fullname.space, fullname.local);
};
}
function attr_attrConstant(name, value) {
return function() {
this.setAttribute(name, value);
};
}
function attr_attrConstantNS(fullname, value) {
return function() {
this.setAttributeNS(fullname.space, fullname.local, value);
};
}
function attr_attrFunction(name, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) this.removeAttribute(name);
else this.setAttribute(name, v);
};
}
function attr_attrFunctionNS(fullname, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
else this.setAttributeNS(fullname.space, fullname.local, v);
};
}
/* harmony default export */ var selection_attr = (function(name, value) {
var fullname = namespace(name);
if (arguments.length < 2) {
var node = this.node();
return fullname.local
? node.getAttributeNS(fullname.space, fullname.local)
: node.getAttribute(fullname);
}
return this.each((value == null
? (fullname.local ? attr_attrRemoveNS : attr_attrRemove) : (typeof value === "function"
? (fullname.local ? attr_attrFunctionNS : attr_attrFunction)
: (fullname.local ? attr_attrConstantNS : attr_attrConstant)))(fullname, value));
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/window.js
/* harmony default export */ var src_window = (function(node) {
return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node
|| (node.document && node) // node is a Window
|| node.defaultView; // node is a Document
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/style.js
function style_styleRemove(name) {
return function() {
this.style.removeProperty(name);
};
}
function style_styleConstant(name, value, priority) {
return function() {
this.style.setProperty(name, value, priority);
};
}
function style_styleFunction(name, value, priority) {
return function() {
var v = value.apply(this, arguments);
if (v == null) this.style.removeProperty(name);
else this.style.setProperty(name, v, priority);
};
}
/* harmony default export */ var selection_style = (function(name, value, priority) {
return arguments.length > 1
? this.each((value == null
? style_styleRemove : typeof value === "function"
? style_styleFunction
: style_styleConstant)(name, value, priority == null ? "" : priority))
: style_styleValue(this.node(), name);
});
function style_styleValue(node, name) {
return node.style.getPropertyValue(name)
|| src_window(node).getComputedStyle(node, null).getPropertyValue(name);
}
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/property.js
function propertyRemove(name) {
return function() {
delete this[name];
};
}
function propertyConstant(name, value) {
return function() {
this[name] = value;
};
}
function propertyFunction(name, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) delete this[name];
else this[name] = v;
};
}
/* harmony default export */ var selection_property = (function(name, value) {
return arguments.length > 1
? this.each((value == null
? propertyRemove : typeof value === "function"
? propertyFunction
: propertyConstant)(name, value))
: this.node()[name];
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/classed.js
function classArray(string) {
return string.trim().split(/^|\s+/);
}
function classList(node) {
return node.classList || new ClassList(node);
}
function ClassList(node) {
this._node = node;
this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
add: function(name) {
var i = this._names.indexOf(name);
if (i < 0) {
this._names.push(name);
this._node.setAttribute("class", this._names.join(" "));
}
},
remove: function(name) {
var i = this._names.indexOf(name);
if (i >= 0) {
this._names.splice(i, 1);
this._node.setAttribute("class", this._names.join(" "));
}
},
contains: function(name) {
return this._names.indexOf(name) >= 0;
}
};
function classedAdd(node, names) {
var list = classList(node), i = -1, n = names.length;
while (++i < n) list.add(names[i]);
}
function classedRemove(node, names) {
var list = classList(node), i = -1, n = names.length;
while (++i < n) list.remove(names[i]);
}
function classedTrue(names) {
return function() {
classedAdd(this, names);
};
}
function classedFalse(names) {
return function() {
classedRemove(this, names);
};
}
function classedFunction(names, value) {
return function() {
(value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
};
}
/* harmony default export */ var classed = (function(name, value) {
var names = classArray(name + "");
if (arguments.length < 2) {
var list = classList(this.node()), i = -1, n = names.length;
while (++i < n) if (!list.contains(names[i])) return false;
return true;
}
return this.each((typeof value === "function"
? classedFunction : value
? classedTrue
: classedFalse)(names, value));
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/text.js
function textRemove() {
this.textContent = "";
}
function textConstant(value) {
return function() {
this.textContent = value;
};
}
function textFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
};
}
/* harmony default export */ var selection_text = (function(value) {
return arguments.length
? this.each(value == null
? textRemove : (typeof value === "function"
? textFunction
: textConstant)(value))
: this.node().textContent;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
this.innerHTML = "";
}
function htmlConstant(value) {
return function() {
this.innerHTML = value;
};
}
function htmlFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
};
}
/* harmony default export */ var html = (function(value) {
return arguments.length
? this.each(value == null
? htmlRemove : (typeof value === "function"
? htmlFunction
: htmlConstant)(value))
: this.node().innerHTML;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/raise.js
function raise() {
if (this.nextSibling) this.parentNode.appendChild(this);
}
/* harmony default export */ var selection_raise = (function() {
return this.each(raise);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/lower.js
function lower() {
if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
/* harmony default export */ var selection_lower = (function() {
return this.each(lower);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/creator.js
function creator_creatorInherit(name) {
return function() {
var document = this.ownerDocument,
uri = this.namespaceURI;
return uri === xhtml && document.documentElement.namespaceURI === xhtml
? document.createElement(name)
: document.createElementNS(uri, name);
};
}
function creator_creatorFixed(fullname) {
return function() {
return this.ownerDocument.createElementNS(fullname.space, fullname.local);
};
}
/* harmony default export */ var creator = (function(name) {
var fullname = namespace(name);
return (fullname.local
? creator_creatorFixed
: creator_creatorInherit)(fullname);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/append.js
/* harmony default export */ var append = (function(name) {
var create = typeof name === "function" ? name : creator(name);
return this.select(function() {
return this.appendChild(create.apply(this, arguments));
});
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/insert.js
function insert_constantNull() {
return null;
}
/* harmony default export */ var selection_insert = (function(name, before) {
var create = typeof name === "function" ? name : creator(name),
select = before == null ? insert_constantNull : typeof before === "function" ? before : src_selector(before);
return this.select(function() {
return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
});
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/remove.js
function remove_remove() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
}
/* harmony default export */ var selection_remove = (function() {
return this.each(remove_remove);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
var clone = this.cloneNode(false), parent = this.parentNode;
return parent ? parent.insertBefore(clone, this.nextSibling) : clone;
}
function selection_cloneDeep() {
var clone = this.cloneNode(true), parent = this.parentNode;
return parent ? parent.insertBefore(clone, this.nextSibling) : clone;
}
/* harmony default export */ var selection_clone = (function(deep) {
return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/datum.js
/* harmony default export */ var selection_datum = (function(value) {
return arguments.length
? this.property("__data__", value)
: this.node().__data__;
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/on.js
var filterEvents = {};
var on_event = null;
if (typeof document !== "undefined") {
var on_element = document.documentElement;
if (!("onmouseenter" in on_element)) {
filterEvents = {mouseenter: "mouseover", mouseleave: "mouseout"};
}
}
function filterContextListener(listener, index, group) {
listener = contextListener(listener, index, group);
return function(event) {
var related = event.relatedTarget;
if (!related || (related !== this && !(related.compareDocumentPosition(this) & 8))) {
listener.call(this, event);
}
};
}
function contextListener(listener, index, group) {
return function(event1) {
var event0 = on_event; // Events can be reentrant (e.g., focus).
on_event = event1;
try {
listener.call(this, this.__data__, index, group);
} finally {
on_event = event0;
}
};
}
function parseTypenames(typenames) {
return typenames.trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
return {type: t, name: name};
});
}
function onRemove(typename) {
return function() {
var on = this.__on;
if (!on) return;
for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
this.removeEventListener(o.type, o.listener, o.capture);
} else {
on[++i] = o;
}
}
if (++i) on.length = i;
else delete this.__on;
};
}
function onAdd(typename, value, capture) {
var wrap = filterEvents.hasOwnProperty(typename.type) ? filterContextListener : contextListener;
return function(d, i, group) {
var on = this.__on, o, listener = wrap(value, i, group);
if (on) for (var j = 0, m = on.length; j < m; ++j) {
if ((o = on[j]).type === typename.type && o.name === typename.name) {
this.removeEventListener(o.type, o.listener, o.capture);
this.addEventListener(o.type, o.listener = listener, o.capture = capture);
o.value = value;
return;
}
}
this.addEventListener(typename.type, listener, capture);
o = {type: typename.type, name: typename.name, value: value, listener: listener, capture: capture};
if (!on) this.__on = [o];
else on.push(o);
};
}
/* harmony default export */ var selection_on = (function(typename, value, capture) {
var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;
if (arguments.length < 2) {
var on = this.node().__on;
if (on) for (var j = 0, m = on.length, o; j < m; ++j) {
for (i = 0, o = on[j]; i < n; ++i) {
if ((t = typenames[i]).type === o.type && t.name === o.name) {
return o.value;
}
}
}
return;
}
on = value ? onAdd : onRemove;
if (capture == null) capture = false;
for (i = 0; i < n; ++i) this.each(on(typenames[i], value, capture));
return this;
});
function customEvent(event1, listener, that, args) {
var event0 = on_event;
event1.sourceEvent = on_event;
on_event = event1;
try {
return listener.apply(that, args);
} finally {
on_event = event0;
}
}
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/dispatch.js
function dispatch_dispatchEvent(node, type, params) {
var window = src_window(node),
event = window.CustomEvent;
if (typeof event === "function") {
event = new event(type, params);
} else {
event = window.document.createEvent("Event");
if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
else event.initEvent(type, false, false);
}
node.dispatchEvent(event);
}
function dispatch_dispatchConstant(type, params) {
return function() {
return dispatch_dispatchEvent(this, type, params);
};
}
function dispatch_dispatchFunction(type, params) {
return function() {
return dispatch_dispatchEvent(this, type, params.apply(this, arguments));
};
}
/* harmony default export */ var dispatch = (function(type, params) {
return this.each((typeof params === "function"
? dispatch_dispatchFunction
: dispatch_dispatchConstant)(type, params));
});
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/selection/index.js
var selection_root = [null];
function selection_Selection(groups, parents) {
this._groups = groups;
this._parents = parents;
}
function selection_selection() {
return new selection_Selection([[document.documentElement]], selection_root);
}
selection_Selection.prototype = selection_selection.prototype = {
constructor: selection_Selection,
select: selection_select,
selectAll: selectAll,
filter: selection_filter,
data: selection_data,
enter: selection_enter,
exit: selection_exit,
join: selection_join,
merge: selection_merge,
order: selection_order,
sort: selection_sort,
call: call,
nodes: selection_nodes,
node: selection_node,
size: selection_size,
empty: selection_empty,
each: each,
attr: selection_attr,
style: selection_style,
property: selection_property,
classed: classed,
text: selection_text,
html: html,
raise: selection_raise,
lower: selection_lower,
append: append,
insert: selection_insert,
remove: selection_remove,
clone: selection_clone,
datum: selection_datum,
on: selection_on,
dispatch: dispatch
};
/* harmony default export */ var src_selection = (selection_selection);
// CONCATENATED MODULE: ./node_modules/vega-embed/node_modules/d3-selection/src/select.js
/* harmony default export */ var src_select = (function(selector) {
return typeof selector === "string"
? new selection_Selection([[document.querySelector(selector)]], [document.documentElement])
: new selection_Selection([[selector]], selection_root);
});
// EXTERNAL MODULE: ./node_modules/deepmerge/dist/cjs.js
var cjs = __webpack_require__(95);
var cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);
// EXTERNAL MODULE: ./node_modules/json-stringify-pretty-compact/index.js
var json_stringify_pretty_compact = __webpack_require__(140);
var json_stringify_pretty_compact_default = /*#__PURE__*/__webpack_require__.n(json_stringify_pretty_compact);
// EXTERNAL MODULE: ./node_modules/semver/semver.js
var semver = __webpack_require__(196);
// EXTERNAL MODULE: ./node_modules/vega-util/index.js + 46 modules
var vega_util = __webpack_require__(1);
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/util/UniqueList.js
function UniqueList_UniqueList(idFunc) {
var $ = idFunc || vega_util["x" /* identity */],
list = [],
ids = {};
list.add = function(_) {
var id = $(_);
if (!ids[id]) {
ids[id] = 1;
list.push(_);
}
return list;
};
list.remove = function(_) {
var id = $(_), idx;
if (ids[id]) {
ids[id] = 0;
if ((idx = list.indexOf(_)) >= 0) {
list.splice(idx, 1);
}
}
return list;
};
return list;
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/util/asyncCallback.js
/**
* Invoke and await a potentially async callback function. If
* an error occurs, trap it and route to Dataflow.error.
* @param {Dataflow} df - The dataflow instance
* @param {function} callback - A callback function to invoke
* and then await. The dataflow will be passed as the single
* argument to the function.
*/
/* harmony default export */ var asyncCallback = (async function(df, callback) {
try { await callback(df); } catch (err) { df.error(err); }
});
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/Tuple.js
var TUPLE_ID_KEY = Symbol('vega_id'),
TUPLE_ID = 1;
/**
* Resets the internal tuple id counter to one.
*/
function Tuple_reset() {
TUPLE_ID = 1;
}
/**
* Checks if an input value is a registered tuple.
* @param {*} t - The value to check.
* @return {boolean} True if the input is a tuple, false otherwise.
*/
function isTuple(t) {
return !!(t && tupleid(t));
}
/**
* Returns the id of a tuple.
* @param {object} t - The input tuple.
* @return {*} the tuple id.
*/
function tupleid(t) {
return t[TUPLE_ID_KEY];
}
/**
* Sets the id of a tuple.
* @param {object} t - The input tuple.
* @param {*} id - The id value to set.
* @return {object} the input tuple.
*/
function setid(t, id) {
t[TUPLE_ID_KEY] = id;
return t;
}
/**
* Ingest an object or value as a data tuple.
* If the input value is an object, an id field will be added to it. For
* efficiency, the input object is modified directly. A copy is not made.
* If the input value is a literal, it will be wrapped in a new object
* instance, with the value accessible as the 'data' property.
* @param datum - The value to ingest.
* @return {object} The ingested data tuple.
*/
function Tuple_ingest(datum) {
var t = (datum === Object(datum)) ? datum : {data: datum};
return tupleid(t) ? t : setid(t, TUPLE_ID++);
}
/**
* Given a source tuple, return a derived copy.
* @param {object} t - The source tuple.
* @return {object} The derived tuple.
*/
function Tuple_derive(t) {
return rederive(t, Tuple_ingest({}));
}
/**
* Rederive a derived tuple by copying values from the source tuple.
* @param {object} t - The source tuple.
* @param {object} d - The derived tuple.
* @return {object} The derived tuple.
*/
function rederive(t, d) {
for (var k in t) d[k] = t[k];
return d;
}
/**
* Replace an existing tuple with a new tuple.
* @param {object} t - The existing data tuple.
* @param {object} d - The new tuple that replaces the old.
* @return {object} The new tuple.
*/
function replace(t, d) {
return setid(d, tupleid(t));
}
/**
* Generate an augmented comparator function that provides stable
* sorting by tuple id when the given comparator produces ties.
* @param {function} cmp - The comparator to augment.
* @param {function} [f] - Optional tuple accessor function.
* @return {function} An augmented comparator function.
*/
function stableCompare(cmp, f) {
return !cmp ? null
: f ? (a, b) => cmp(a, b) || (tupleid(f(a)) - tupleid(f(b)))
: (a, b) => cmp(a, b) || (tupleid(a) - tupleid(b));
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/ChangeSet.js
function ChangeSet_isChangeSet(v) {
return v && v.constructor === ChangeSet_changeset;
}
function ChangeSet_changeset() {
var add = [], // insert tuples
rem = [], // remove tuples
mod = [], // modify tuples
remp = [], // remove by predicate
modp = [], // modify by predicate
reflow = false;
return {
constructor: ChangeSet_changeset,
insert: function(t) {
var d = Object(vega_util["i" /* array */])(t), i = 0, n = d.length;
for (; i<n; ++i) add.push(d[i]);
return this;
},
remove: function(t) {
var a = Object(vega_util["D" /* isFunction */])(t) ? remp : rem,
d = Object(vega_util["i" /* array */])(t), i = 0, n = d.length;
for (; i<n; ++i) a.push(d[i]);
return this;
},
modify: function(t, field, value) {
var m = {field: field, value: Object(vega_util["l" /* constant */])(value)};
if (Object(vega_util["D" /* isFunction */])(t)) {
m.filter = t;
modp.push(m);
} else {
m.tuple = t;
mod.push(m);
}
return this;
},
encode: function(t, set) {
if (Object(vega_util["D" /* isFunction */])(t)) modp.push({filter: t, field: set});
else mod.push({tuple: t, field: set});
return this;
},
reflow: function() {
reflow = true;
return this;
},
pulse: function(pulse, tuples) {
var cur = {}, out = {}, i, n, m, f, t, id;
// build lookup table of current tuples
for (i=0, n=tuples.length; i<n; ++i) {
cur[tupleid(tuples[i])] = 1;
}
// process individual tuples to remove
for (i=0, n=rem.length; i<n; ++i) {
t = rem[i];
cur[tupleid(t)] = -1;
}
// process predicate-based removals
for (i=0, n=remp.length; i<n; ++i) {
f = remp[i];
tuples.forEach(function(t) {
if (f(t)) cur[tupleid(t)] = -1;
});
}
// process all add tuples
for (i=0, n=add.length; i<n; ++i) {
t = add[i];
id = tupleid(t);
if (cur[id]) {
// tuple already resides in dataset
// if flagged for both add and remove, cancel
cur[id] = 1;
} else {
// tuple does not reside in dataset, add
pulse.add.push(Tuple_ingest(add[i]));
}
}
// populate pulse rem list
for (i=0, n=tuples.length; i<n; ++i) {
t = tuples[i];
if (cur[tupleid(t)] < 0) pulse.rem.push(t);
}
// modify helper method
function modify(t, f, v) {
if (v) {
t[f] = v(t);
} else {
pulse.encode = f;
}
if (!reflow) out[tupleid(t)] = t;
}
// process individual tuples to modify
for (i=0, n=mod.length; i<n; ++i) {
m = mod[i];
t = m.tuple;
f = m.field;
id = cur[tupleid(t)];
if (id > 0) {
modify(t, f, m.value);
pulse.modifies(f);
}
}
// process predicate-based modifications
for (i=0, n=modp.length; i<n; ++i) {
m = modp[i];
f = m.filter;
tuples.forEach(function(t) {
if (f(t) && cur[tupleid(t)] > 0) {
modify(t, m.field, m.value);
}
});
pulse.modifies(m.field);
}
// upon reflow request, populate mod with all non-removed tuples
// otherwise, populate mod with modified tuples only
if (reflow) {
pulse.mod = rem.length || remp.length
? tuples.filter(function(t) { return cur[tupleid(t)] > 0; })
: tuples.slice();
} else {
for (id in out) pulse.mod.push(out[id]);
}
return pulse;
}
};
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/Parameters.js
var Parameters_CACHE = '_:mod:_';
/**
* Hash that tracks modifications to assigned values.
* Callers *must* use the set method to update values.
*/
function Parameters_Parameters() {
Object.defineProperty(this, Parameters_CACHE, {writable: true, value: {}});
}
var Parameters_prototype = Parameters_Parameters.prototype;
/**
* Set a parameter value. If the parameter value changes, the parameter
* will be recorded as modified.
* @param {string} name - The parameter name.
* @param {number} index - The index into an array-value parameter. Ignored if
* the argument is undefined, null or less than zero.
* @param {*} value - The parameter value to set.
* @param {boolean} [force=false] - If true, records the parameter as modified
* even if the value is unchanged.
* @return {Parameters} - This parameter object.
*/
Parameters_prototype.set = function(name, index, value, force) {
var o = this,
v = o[name],
mod = o[Parameters_CACHE];
if (index != null && index >= 0) {
if (v[index] !== value || force) {
v[index] = value;
mod[index + ':' + name] = -1;
mod[name] = -1;
}
} else if (v !== value || force) {
o[name] = value;
mod[name] = Object(vega_util["A" /* isArray */])(value) ? 1 + value.length : -1;
}
return o;
};
/**
* Tests if one or more parameters has been modified. If invoked with no
* arguments, returns true if any parameter value has changed. If the first
* argument is array, returns trues if any parameter name in the array has
* changed. Otherwise, tests if the given name and optional array index has
* changed.
* @param {string} name - The parameter name to test.
* @param {number} [index=undefined] - The parameter array index to test.
* @return {boolean} - Returns true if a queried parameter was modified.
*/
Parameters_prototype.modified = function(name, index) {
var mod = this[Parameters_CACHE], k;
if (!arguments.length) {
for (k in mod) { if (mod[k]) return true; }
return false;
} else if (Object(vega_util["A" /* isArray */])(name)) {
for (k=0; k<name.length; ++k) {
if (mod[name[k]]) return true;
}
return false;
}
return (index != null && index >= 0)
? (index + 1 < mod[name] || !!mod[index + ':' + name])
: !!mod[name];
};
/**
* Clears the modification records. After calling this method,
* all parameters are considered unmodified.
*/
Parameters_prototype.clear = function() {
this[Parameters_CACHE] = {};
return this;
};
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/Operator.js
var Operator_OP_ID = 0;
var Operator_PULSE = 'pulse';
var Operator_NO_PARAMS = new Parameters_Parameters();
// Boolean Flags
var Operator_SKIP = 1,
Operator_MODIFIED = 2;
/**
* An Operator is a processing node in a dataflow graph.
* Each operator stores a value and an optional value update function.
* Operators can accept a hash of named parameters. Parameter values can
* either be direct (JavaScript literals, arrays, objects) or indirect
* (other operators whose values will be pulled dynamically). Operators
* included as parameters will have this operator added as a dependency.
* @constructor
* @param {*} [init] - The initial value for this operator.
* @param {function(object, Pulse)} [update] - An update function. Upon
* evaluation of this operator, the update function will be invoked and the
* return value will be used as the new value of this operator.
* @param {object} [params] - The parameters for this operator.
* @param {boolean} [react=true] - Flag indicating if this operator should
* listen for changes to upstream operators included as parameters.
* @see parameters
*/
function Operator_Operator(init, update, params, react) {
this.id = ++Operator_OP_ID;
this.value = init;
this.stamp = -1;
this.rank = -1;
this.qrank = -1;
this.flags = 0;
if (update) {
this._update = update;
}
if (params) this.parameters(params, react);
}
var Operator_prototype = Operator_Operator.prototype;
/**
* Returns a list of target operators dependent on this operator.
* If this list does not exist, it is created and then returned.
* @return {UniqueList}
*/
Operator_prototype.targets = function() {
return this._targets || (this._targets = UniqueList_UniqueList(vega_util["w" /* id */]));
};
/**
* Sets the value of this operator.
* @param {*} value - the value to set.
* @return {Number} Returns 1 if the operator value has changed
* according to strict equality, returns 0 otherwise.
*/
Operator_prototype.set = function(value) {
if (this.value !== value) {
this.value = value;
return 1;
} else {
return 0;
}
};
function Operator_flag(bit) {
return function(state) {
var f = this.flags;
if (arguments.length === 0) return !!(f & bit);
this.flags = state ? (f | bit) : (f & ~bit);
return this;
};
}
/**
* Indicates that operator evaluation should be skipped on the next pulse.
* This operator will still propagate incoming pulses, but its update function
* will not be invoked. The skip flag is reset after every pulse, so calling
* this method will affect processing of the next pulse only.
*/
Operator_prototype.skip = Operator_flag(Operator_SKIP);
/**
* Indicates that this operator's value has been modified on its most recent
* pulse. Normally modification is checked via strict equality; however, in
* some cases it is more efficient to update the internal state of an object.
* In those cases, the modified flag can be used to trigger propagation. Once
* set, the modification flag persists across pulses until unset. The flag can
* be used with the last timestamp to test if a modification is recent.
*/
Operator_prototype.modified = Operator_flag(Operator_MODIFIED);
/**
* Sets the parameters for this operator. The parameter values are analyzed for
* operator instances. If found, this operator will be added as a dependency
* of the parameterizing operator. Operator values are dynamically marshalled
* from each operator parameter prior to evaluation. If a parameter value is
* an array, the array will also be searched for Operator instances. However,
* the search does not recurse into sub-arrays or object properties.
* @param {object} params - A hash of operator parameters.
* @param {boolean} [react=true] - A flag indicating if this operator should
* automatically update (react) when parameter values change. In other words,
* this flag determines if the operator registers itself as a listener on
* any upstream operators included in the parameters.
* @param {boolean} [initonly=false] - A flag indicating if this operator
* should calculate an update only upon its initiatal evaluation, then
* deregister dependencies and suppress all future update invocations.
* @return {Operator[]} - An array of upstream dependencies.
*/
Operator_prototype.parameters = function(params, react, initonly) {
react = react !== false;
var self = this,
argval = (self._argval = self._argval || new Parameters_Parameters()),
argops = (self._argops = self._argops || []),
deps = [],
name, value, n, i;
function add(name, index, value) {
if (value instanceof Operator_Operator) {
if (value !== self) {
if (react) value.targets().add(self);
deps.push(value);
}
argops.push({op:value, name:name, index:index});
} else {
argval.set(name, index, value);
}
}
for (name in params) {
value = params[name];
if (name === Operator_PULSE) {
Object(vega_util["i" /* array */])(value).forEach(function(op) {
if (!(op instanceof Operator_Operator)) {
Object(vega_util["n" /* error */])('Pulse parameters must be operator instances.');
} else if (op !== self) {
op.targets().add(self);
deps.push(op);
}
});
self.source = value;
} else if (Object(vega_util["A" /* isArray */])(value)) {
argval.set(name, -1, Array(n = value.length));
for (i=0; i<n; ++i) add(name, i, value[i]);
} else {
add(name, -1, value);
}
}
this.marshall().clear(); // initialize values
if (initonly) argops.initonly = true;
return deps;
};
/**
* Internal method for marshalling parameter values.
* Visits each operator dependency to pull the latest value.
* @return {Parameters} A Parameters object to pass to the update function.
*/
Operator_prototype.marshall = function(stamp) {
var argval = this._argval || Operator_NO_PARAMS,
argops = this._argops, item, i, n, op, mod;
if (argops) {
for (i=0, n=argops.length; i<n; ++i) {
item = argops[i];
op = item.op;
mod = op.modified() && op.stamp === stamp;
argval.set(item.name, item.index, op.value, mod);
}
if (argops.initonly) {
for (i=0; i<n; ++i) {
item = argops[i];
item.op.targets().remove(this);
}
this._argops = null;
this._update = null;
}
}
return argval;
};
/**
* Delegate method to perform operator processing.
* Subclasses can override this method to perform custom processing.
* By default, it marshalls parameters and calls the update function
* if that function is defined. If the update function does not
* change the operator value then StopPropagation is returned.
* If no update function is defined, this method does nothing.
* @param {Pulse} pulse - the current dataflow pulse.
* @return The output pulse or StopPropagation. A falsy return value
* (including undefined) will let the input pulse pass through.
*/
Operator_prototype.evaluate = function(pulse) {
var update = this._update;
if (update) {
var params = this.marshall(pulse.stamp),
v = update.call(this, params, pulse);
params.clear();
if (v !== this.value) {
this.value = v;
} else if (!this.modified()) {
return pulse.StopPropagation;
}
}
};
/**
* Run this operator for the current pulse. If this operator has already
* been run at (or after) the pulse timestamp, returns StopPropagation.
* Internally, this method calls {@link evaluate} to perform processing.
* If {@link evaluate} returns a falsy value, the input pulse is returned.
* This method should NOT be overridden, instead overrride {@link evaluate}.
* @param {Pulse} pulse - the current dataflow pulse.
* @return the output pulse for this operator (or StopPropagation)
*/
Operator_prototype.run = function(pulse) {
if (pulse.stamp < this.stamp) return pulse.StopPropagation;
var rv;
if (this.skip()) {
this.skip(false);
rv = 0;
} else {
rv = this.evaluate(pulse);
}
return (this.pulse = rv || pulse);
};
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/add.js
/**
* Add an operator to the dataflow graph. This function accepts a
* variety of input argument types. The basic signature supports an
* initial value, update function and parameters. If the first parameter
* is an Operator instance, it will be added directly. If it is a
* constructor for an Operator subclass, a new instance will be instantiated.
* Otherwise, if the first parameter is a function instance, it will be used
* as the update function and a null initial value is assumed.
* @param {*} init - One of: the operator to add, the initial value of
* the operator, an operator class to instantiate, or an update function.
* @param {function} [update] - The operator update function.
* @param {object} [params] - The operator parameters.
* @param {boolean} [react=true] - Flag indicating if this operator should
* listen for changes to upstream operators included as parameters.
* @return {Operator} - The added operator.
*/
/* harmony default export */ var dataflow_add = (function(init, update, params, react) {
var shift = 1,
op;
if (init instanceof Operator_Operator) {
op = init;
} else if (init && init.prototype instanceof Operator_Operator) {
op = new init();
} else if (Object(vega_util["D" /* isFunction */])(init)) {
op = new Operator_Operator(null, init);
} else {
shift = 0;
op = new Operator_Operator(init, update);
}
this.rank(op);
if (shift) {
react = params;
params = update;
}
if (params) this.connect(op, op.parameters(params, react));
this.touch(op);
return op;
});
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/connect.js
/**
* Connect a target operator as a dependent of source operators.
* If necessary, this method will rerank the target operator and its
* dependents to ensure propagation proceeds in a topologically sorted order.
* @param {Operator} target - The target operator.
* @param {Array<Operator>} - The source operators that should propagate
* to the target operator.
*/
/* harmony default export */ var connect = (function(target, sources) {
var targetRank = target.rank, i, n;
for (i=0, n=sources.length; i<n; ++i) {
if (targetRank < sources[i].rank) {
this.rerank(target);
return;
}
}
});
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/EventStream.js
var EventStream_STREAM_ID = 0;
/**
* Models an event stream.
* @constructor
* @param {function(Object, number): boolean} [filter] - Filter predicate.
* Events pass through when truthy, events are suppressed when falsy.
* @param {function(Object): *} [apply] - Applied to input events to produce
* new event values.
* @param {function(Object)} [receive] - Event callback function to invoke
* upon receipt of a new event. Use to override standard event processing.
*/
function EventStream_EventStream(filter, apply, receive) {
this.id = ++EventStream_STREAM_ID;
this.value = null;
if (receive) this.receive = receive;
if (filter) this._filter = filter;
if (apply) this._apply = apply;
}
/**
* Creates a new event stream instance with the provided
* (optional) filter, apply and receive functions.
* @param {function(Object, number): boolean} [filter] - Filter predicate.
* Events pass through when truthy, events are suppressed when falsy.
* @param {function(Object): *} [apply] - Applied to input events to produce
* new event values.
* @see EventStream
*/
function EventStream_stream(filter, apply, receive) {
return new EventStream_EventStream(filter, apply, receive);
}
var EventStream_prototype = EventStream_EventStream.prototype;
EventStream_prototype._filter = vega_util["Ga" /* truthy */];
EventStream_prototype._apply = vega_util["x" /* identity */];
EventStream_prototype.targets = function() {
return this._targets || (this._targets = UniqueList_UniqueList(vega_util["w" /* id */]));
};
EventStream_prototype.consume = function(_) {
if (!arguments.length) return !!this._consume;
this._consume = !!_;
return this;
};
EventStream_prototype.receive = function(evt) {
if (this._filter(evt)) {
var val = (this.value = this._apply(evt)),
trg = this._targets,
n = trg ? trg.length : 0,
i = 0;
for (; i<n; ++i) trg[i].receive(val);
if (this._consume) {
evt.preventDefault();
evt.stopPropagation();
}
}
};
EventStream_prototype.filter = function(filter) {
var s = EventStream_stream(filter);
this.targets().add(s);
return s;
};
EventStream_prototype.apply = function(apply) {
var s = EventStream_stream(null, apply);
this.targets().add(s);
return s;
};
EventStream_prototype.merge = function() {
var s = EventStream_stream();
this.targets().add(s);
for (var i=0, n=arguments.length; i<n; ++i) {
arguments[i].targets().add(s);
}
return s;
};
EventStream_prototype.throttle = function(pause) {
var t = -1;
return this.filter(function() {
var now = Date.now();
if ((now - t) > pause) {
t = now;
return 1;
} else {
return 0;
}
});
};
EventStream_prototype.debounce = function(delay) {
var s = EventStream_stream();
this.targets().add(EventStream_stream(null, null,
Object(vega_util["m" /* debounce */])(delay, function(e) {
var df = e.dataflow;
s.receive(e);
if (df && df.run) df.run();
})
));
return s;
};
EventStream_prototype.between = function(a, b) {
var active = false;
a.targets().add(EventStream_stream(null, null, function() { active = true; }));
b.targets().add(EventStream_stream(null, null, function() { active = false; }));
return this.filter(function() { return active; });
};
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/events.js
/**
* Create a new event stream from an event source.
* @param {object} source - The event source to monitor. The input must
* support the addEventListener method.
* @param {string} type - The event type.
* @param {function(object): boolean} [filter] - Event filter function.
* @param {function(object): *} [apply] - Event application function.
* If provided, this function will be invoked and the result will be
* used as the downstream event value.
* @return {EventStream}
*/
/* harmony default export */ var dataflow_events = (function(source, type, filter, apply) {
var df = this,
s = EventStream_stream(filter, apply),
send = function(e) {
e.dataflow = df;
try {
s.receive(e);
} catch (error) {
df.error(error);
} finally {
df.run();
}
},
sources;
if (typeof source === 'string' && typeof document !== 'undefined') {
sources = document.querySelectorAll(source);
} else {
sources = Object(vega_util["i" /* array */])(source);
}
for (var i=0, n=sources.length; i<n; ++i) {
sources[i].addEventListener(type, send);
}
return s;
});
// CONCATENATED MODULE: ./node_modules/vega-loader/src/loader.js
// Matches absolute URLs with optional protocol
// https://... file://... //...
const loader_protocol_re = /^([A-Za-z]+:)?\/\//;
// Matches allowed URIs. From https://github.com/cure53/DOMPurify/blob/master/src/regexp.js with added file://
const loader_allowed_re = /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|file|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i; // eslint-disable-line no-useless-escape
const loader_whitespace_re = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g; // eslint-disable-line no-control-regex
// Special treatment in node.js for the file: protocol
const loader_fileProtocol = 'file://';
/**
* Factory for a loader constructor that provides methods for requesting
* files from either the network or disk, and for sanitizing request URIs.
* @param {function} fetch - The Fetch API for HTTP network requests.
* If null or undefined, HTTP loading will be disabled.
* @param {object} fs - The file system interface for file loading.
* If null or undefined, local file loading will be disabled.
* @return {function} A loader constructor with the following signature:
* param {object} [options] - Optional default loading options to use.
* return {object} - A new loader instance.
*/
/* harmony default export */ var src_loader = (function(fetch, fs) {
return function(options) {
return {
options: options || {},
sanitize: loader_sanitize,
load: loader_load,
fileAccess: !!fs,
file: loader_fileLoader(fs),
http: loader_httpLoader(fetch)
};
};
});
/**
* Load an external resource, typically either from the web or from the local
* filesystem. This function uses {@link sanitize} to first sanitize the uri,
* then calls either {@link http} (for web requests) or {@link file} (for
* filesystem loading).
* @param {string} uri - The resource indicator (e.g., URL or filename).
* @param {object} [options] - Optional loading options. These options will
* override any existing default options.
* @return {Promise} - A promise that resolves to the loaded content.
*/
async function loader_load(uri, options) {
const opt = await this.sanitize(uri, options),
url = opt.href;
return opt.localFile
? this.file(url)
: this.http(url, options);
}
/**
* URI sanitizer function.
* @param {string} uri - The uri (url or filename) to sanity check.
* @param {object} options - An options hash.
* @return {Promise} - A promise that resolves to an object containing
* sanitized uri data, or rejects it the input uri is deemed invalid.
* The properties of the resolved object are assumed to be
* valid attributes for an HTML 'a' tag. The sanitized uri *must* be
* provided by the 'href' property of the returned object.
*/
async function loader_sanitize(uri, options) {
options = Object(vega_util["o" /* extend */])({}, this.options, options);
const fileAccess = this.fileAccess,
result = {href: null};
let isFile, loadFile, base;
const isAllowed = loader_allowed_re.test(uri.replace(loader_whitespace_re, ''));
if (uri == null || typeof uri !== 'string' || !isAllowed) {
Object(vega_util["n" /* error */])('Sanitize failure, invalid URI: ' + Object(vega_util["Z" /* stringValue */])(uri));
}
const hasProtocol = loader_protocol_re.test(uri);
// if relative url (no protocol/host), prepend baseURL
if ((base = options.baseURL) && !hasProtocol) {
// Ensure that there is a slash between the baseURL (e.g. hostname) and url
if (!uri.startsWith('/') && base[base.length-1] !== '/') {
uri = '/' + uri;
}
uri = base + uri;
}
// should we load from file system?
loadFile = (isFile = uri.startsWith(loader_fileProtocol))
|| options.mode === 'file'
|| options.mode !== 'http' && !hasProtocol && fileAccess;
if (isFile) {
// strip file protocol
uri = uri.slice(loader_fileProtocol.length);
} else if (uri.startsWith('//')) {
if (options.defaultProtocol === 'file') {
// if is file, strip protocol and set loadFile flag
uri = uri.slice(2);
loadFile = true;
} else {
// if relative protocol (starts with '//'), prepend default protocol
uri = (options.defaultProtocol || 'http') + ':' + uri;
}
}
// set non-enumerable mode flag to indicate local file load
Object.defineProperty(result, 'localFile', {value: !!loadFile});
// set uri
result.href = uri;
// set default result target, if specified
if (options.target) {
result.target = options.target + '';
}
// set default result rel, if specified (#1542)
if (options.rel) {
result.rel = options.rel + '';
}
// provide control over cross-origin image handling (#2238)
// https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
if (options.context === 'image' && options.crossOrigin) {
result.crossOrigin = options.crossOrigin + '';
}
// return
return result;
}
/**
* File system loader factory.
* @param {object} fs - The file system interface.
* @return {function} - A file loader with the following signature:
* param {string} filename - The file system path to load.
* param {string} filename - The file system path to load.
* return {Promise} A promise that resolves to the file contents.
*/
function loader_fileLoader(fs) {
return fs
? function(filename) {
return new Promise(function(accept, reject) {
fs.readFile(filename, function(error, data) {
if (error) reject(error);
else accept(data);
});
});
}
: loader_fileReject;
}
/**
* Default file system loader that simply rejects.
*/
async function loader_fileReject() {
Object(vega_util["n" /* error */])('No file system access.');
}
/**
* HTTP request handler factory.
* @param {function} fetch - The Fetch API method.
* @return {function} - An http loader with the following signature:
* param {string} url - The url to request.
* param {object} options - An options hash.
* return {Promise} - A promise that resolves to the file contents.
*/
function loader_httpLoader(fetch) {
return fetch
? async function(url, options) {
const opt = Object(vega_util["o" /* extend */])({}, this.options.http, options),
type = options && options.response,
response = await fetch(url, opt);
return !response.ok
? Object(vega_util["n" /* error */])(response.status + '' + response.statusText)
: Object(vega_util["D" /* isFunction */])(response[type]) ? response[type]()
: response.text();
}
: loader_httpReject;
}
/**
* Default http request handler that simply rejects.
*/
async function loader_httpReject() {
Object(vega_util["n" /* error */])('No HTTP fetch method available.');
}
// CONCATENATED MODULE: ./node_modules/vega-loader/src/type.js
var type_typeParsers = {
boolean: vega_util["Aa" /* toBoolean */],
integer: vega_util["Ca" /* toNumber */],
number: vega_util["Ca" /* toNumber */],
date: vega_util["Ba" /* toDate */],
string: vega_util["Ea" /* toString */],
unknown: vega_util["x" /* identity */]
};
var type_typeTests = [
type_isBoolean,
type_isInteger,
type_isNumber,
type_isDate
];
var type_typeList = [
'boolean',
'integer',
'number',
'date'
];
function type_inferType(values, field) {
if (!values || !values.length) return 'unknown';
var value, i, j, t = 0,
n = values.length,
m = type_typeTests.length,
a = type_typeTests.map(function(_, i) { return i + 1; });
for (i=0, n=values.length; i<n; ++i) {
value = field ? values[i][field] : values[i];
for (j=0; j<m; ++j) {
if (a[j] && type_isValid(value) && !type_typeTests[j](value)) {
a[j] = 0;
++t;
if (t === type_typeTests.length) return 'string';
}
}
}
t = a.reduce(function(u, v) { return u === 0 ? v : u; }, 0) - 1;
return type_typeList[t];
}
function type_inferTypes(data, fields) {
return fields.reduce(function(types, field) {
types[field] = type_inferType(data, field);
return types;
}, {});
}
// -- Type Checks ----
function type_isValid(_) {
return _ != null && _ === _;
}
function type_isBoolean(_) {
return _ === 'true' || _ === 'false' || _ === true || _ === false;
}
function type_isDate(_) {
return !Number.isNaN(Date.parse(_));
}
function type_isNumber(_) {
return !Number.isNaN(+_) && !(_ instanceof Date);
}
function type_isInteger(_) {
return type_isNumber(_) && Number.isInteger(+_);
}
// CONCATENATED MODULE: ./node_modules/d3-dsv/src/dsv.js
var EOL = {},
EOF = {},
QUOTE = 34,
NEWLINE = 10,
RETURN = 13;
function objectConverter(columns) {
return new Function("d", "return {" + columns.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "] || \"\"";
}).join(",") + "}");
}
function customConverter(columns, f) {
var object = objectConverter(columns);
return function(row, i) {
return f(object(row), i, columns);
};
}
// Compute unique columns in order of discovery.
function inferColumns(rows) {
var columnSet = Object.create(null),
columns = [];
rows.forEach(function(row) {
for (var column in row) {
if (!(column in columnSet)) {
columns.push(columnSet[column] = column);
}
}
});
return columns;
}
function dsv_pad(value, width) {
var s = value + "", length = s.length;
return length < width ? new Array(width - length + 1).join(0) + s : s;
}
function dsv_formatYear(year) {
return year < 0 ? "-" + dsv_pad(-year, 6)
: year > 9999 ? "+" + dsv_pad(year, 6)
: dsv_pad(year, 4);
}
function formatDate(date) {
var hours = date.getUTCHours(),
minutes = date.getUTCMinutes(),
seconds = date.getUTCSeconds(),
milliseconds = date.getUTCMilliseconds();
return isNaN(date) ? "Invalid Date"
: dsv_formatYear(date.getUTCFullYear(), 4) + "-" + dsv_pad(date.getUTCMonth() + 1, 2) + "-" + dsv_pad(date.getUTCDate(), 2)
+ (milliseconds ? "T" + dsv_pad(hours, 2) + ":" + dsv_pad(minutes, 2) + ":" + dsv_pad(seconds, 2) + "." + dsv_pad(milliseconds, 3) + "Z"
: seconds ? "T" + dsv_pad(hours, 2) + ":" + dsv_pad(minutes, 2) + ":" + dsv_pad(seconds, 2) + "Z"
: minutes || hours ? "T" + dsv_pad(hours, 2) + ":" + dsv_pad(minutes, 2) + "Z"
: "");
}
/* harmony default export */ var src_dsv = (function(delimiter) {
var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
DELIMITER = delimiter.charCodeAt(0);
function parse(text, f) {
var convert, columns, rows = parseRows(text, function(row, i) {
if (convert) return convert(row, i - 1);
columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
});
rows.columns = columns || [];
return rows;
}
function parseRows(text, f) {
var rows = [], // output rows
N = text.length,
I = 0, // current character index
n = 0, // current line number
t, // current token
eof = N <= 0, // current token followed by EOF?
eol = false; // current token followed by EOL?
// Strip the trailing newline.
if (text.charCodeAt(N - 1) === NEWLINE) --N;
if (text.charCodeAt(N - 1) === RETURN) --N;
function token() {
if (eof) return EOF;
if (eol) return eol = false, EOL;
// Unescape quotes.
var i, j = I, c;
if (text.charCodeAt(j) === QUOTE) {
while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);
if ((i = I) >= N) eof = true;
else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;
else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
return text.slice(j + 1, i - 1).replace(/""/g, "\"");
}
// Find next delimiter or newline.
while (I < N) {
if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;
else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }
else if (c !== DELIMITER) continue;
return text.slice(j, i);
}
// Return last token before EOF.
return eof = true, text.slice(j, N);
}
while ((t = token()) !== EOF) {
var row = [];
while (t !== EOL && t !== EOF) row.push(t), t = token();
if (f && (row = f(row, n++)) == null) continue;
rows.push(row);
}
return rows;
}
function preformatBody(rows, columns) {
return rows.map(function(row) {
return columns.map(function(column) {
return formatValue(row[column]);
}).join(delimiter);
});
}
function format(rows, columns) {
if (columns == null) columns = inferColumns(rows);
return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");
}
function formatBody(rows, columns) {
if (columns == null) columns = inferColumns(rows);
return preformatBody(rows, columns).join("\n");
}
function formatRows(rows) {
return rows.map(formatRow).join("\n");
}
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(value) {
return value == null ? ""
: value instanceof Date ? formatDate(value)
: reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\""
: value;
}
return {
parse: parse,
parseRows: parseRows,
format: format,
formatBody: formatBody,
formatRows: formatRows,
formatRow: formatRow,
formatValue: formatValue
};
});
// CONCATENATED MODULE: ./node_modules/vega-loader/src/formats/dsv.js
function dsv_delimitedFormat(delimiter) {
const parse = function(data, format) {
const delim = {delimiter: delimiter};
return dsv_dsv(data, format ? Object(vega_util["o" /* extend */])(format, delim) : delim);
};
parse.responseType = 'text';
return parse;
}
function dsv_dsv(data, format) {
if (format.header) {
data = format.header
.map(vega_util["Z" /* stringValue */])
.join(format.delimiter) + '\n' + data;
}
return src_dsv(format.delimiter).parse(data + '');
}
dsv_dsv.responseType = 'text';
// EXTERNAL MODULE: ./node_modules/vega-loader/src/formats/json.js
var json = __webpack_require__(139);
// CONCATENATED MODULE: ./node_modules/topojson-client/src/identity.js
/* harmony default export */ var src_identity = (function(x) {
return x;
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/transform.js
/* harmony default export */ var src_transform = (function(transform) {
if (transform == null) return src_identity;
var x0,
y0,
kx = transform.scale[0],
ky = transform.scale[1],
dx = transform.translate[0],
dy = transform.translate[1];
return function(input, i) {
if (!i) x0 = y0 = 0;
var j = 2, n = input.length, output = new Array(n);
output[0] = (x0 += input[0]) * kx + dx;
output[1] = (y0 += input[1]) * ky + dy;
while (j < n) output[j] = input[j], ++j;
return output;
};
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/bbox.js
/* harmony default export */ var src_bbox = (function(topology) {
var t = src_transform(topology.transform), key,
x0 = Infinity, y0 = x0, x1 = -x0, y1 = -x0;
function bboxPoint(p) {
p = t(p);
if (p[0] < x0) x0 = p[0];
if (p[0] > x1) x1 = p[0];
if (p[1] < y0) y0 = p[1];
if (p[1] > y1) y1 = p[1];
}
function bboxGeometry(o) {
switch (o.type) {
case "GeometryCollection": o.geometries.forEach(bboxGeometry); break;
case "Point": bboxPoint(o.coordinates); break;
case "MultiPoint": o.coordinates.forEach(bboxPoint); break;
}
}
topology.arcs.forEach(function(arc) {
var i = -1, n = arc.length, p;
while (++i < n) {
p = t(arc[i], i);
if (p[0] < x0) x0 = p[0];
if (p[0] > x1) x1 = p[0];
if (p[1] < y0) y0 = p[1];
if (p[1] > y1) y1 = p[1];
}
});
for (key in topology.objects) {
bboxGeometry(topology.objects[key]);
}
return [x0, y0, x1, y1];
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/reverse.js
/* harmony default export */ var src_reverse = (function(array, n) {
var t, j = array.length, i = j - n;
while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/feature.js
/* harmony default export */ var src_feature = (function(topology, o) {
if (typeof o === "string") o = topology.objects[o];
return o.type === "GeometryCollection"
? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature_feature(topology, o); })}
: feature_feature(topology, o);
});
function feature_feature(topology, o) {
var id = o.id,
bbox = o.bbox,
properties = o.properties == null ? {} : o.properties,
geometry = feature_object(topology, o);
return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry}
: bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry}
: {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry};
}
function feature_object(topology, o) {
var transformPoint = src_transform(topology.transform),
arcs = topology.arcs;
function arc(i, points) {
if (points.length) points.pop();
for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) {
points.push(transformPoint(a[k], k));
}
if (i < 0) src_reverse(points, n);
}
function point(p) {
return transformPoint(p);
}
function line(arcs) {
var points = [];
for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
if (points.length < 2) points.push(points[0]); // This should never happen per the specification.
return points;
}
function ring(arcs) {
var points = line(arcs);
while (points.length < 4) points.push(points[0]); // This may happen if an arc has only two points.
return points;
}
function polygon(arcs) {
return arcs.map(ring);
}
function geometry(o) {
var type = o.type, coordinates;
switch (type) {
case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)};
case "Point": coordinates = point(o.coordinates); break;
case "MultiPoint": coordinates = o.coordinates.map(point); break;
case "LineString": coordinates = line(o.arcs); break;
case "MultiLineString": coordinates = o.arcs.map(line); break;
case "Polygon": coordinates = polygon(o.arcs); break;
case "MultiPolygon": coordinates = o.arcs.map(polygon); break;
default: return null;
}
return {type: type, coordinates: coordinates};
}
return geometry(o);
}
// CONCATENATED MODULE: ./node_modules/topojson-client/src/stitch.js
/* harmony default export */ var stitch = (function(topology, arcs) {
var stitchedArcs = {},
fragmentByStart = {},
fragmentByEnd = {},
fragments = [],
emptyIndex = -1;
// Stitch empty arcs first, since they may be subsumed by other arcs.
arcs.forEach(function(i, j) {
var arc = topology.arcs[i < 0 ? ~i : i], t;
if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
}
});
arcs.forEach(function(i) {
var e = ends(i),
start = e[0],
end = e[1],
f, g;
if (f = fragmentByEnd[start]) {
delete fragmentByEnd[f.end];
f.push(i);
f.end = end;
if (g = fragmentByStart[end]) {
delete fragmentByStart[g.start];
var fg = g === f ? f : f.concat(g);
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByStart[end]) {
delete fragmentByStart[f.start];
f.unshift(i);
f.start = start;
if (g = fragmentByEnd[start]) {
delete fragmentByEnd[g.end];
var gf = g === f ? f : g.concat(f);
fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else {
f = [i];
fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
}
});
function ends(i) {
var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
else p1 = arc[arc.length - 1];
return i < 0 ? [p1, p0] : [p0, p1];
}
function flush(fragmentByEnd, fragmentByStart) {
for (var k in fragmentByEnd) {
var f = fragmentByEnd[k];
delete fragmentByStart[f.start];
delete f.start;
delete f.end;
f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
fragments.push(f);
}
}
flush(fragmentByEnd, fragmentByStart);
flush(fragmentByStart, fragmentByEnd);
arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });
return fragments;
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/mesh.js
/* harmony default export */ var mesh = (function(topology) {
return feature_object(topology, mesh_meshArcs.apply(this, arguments));
});
function mesh_meshArcs(topology, object, filter) {
var arcs, i, n;
if (arguments.length > 1) arcs = mesh_extractArcs(topology, object, filter);
else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i;
return {type: "MultiLineString", arcs: stitch(topology, arcs)};
}
function mesh_extractArcs(topology, object, filter) {
var arcs = [],
geomsByArc = [],
geom;
function extract0(i) {
var j = i < 0 ? ~i : i;
(geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
}
function extract1(arcs) {
arcs.forEach(extract0);
}
function extract2(arcs) {
arcs.forEach(extract1);
}
function extract3(arcs) {
arcs.forEach(extract2);
}
function geometry(o) {
switch (geom = o, o.type) {
case "GeometryCollection": o.geometries.forEach(geometry); break;
case "LineString": extract1(o.arcs); break;
case "MultiLineString": case "Polygon": extract2(o.arcs); break;
case "MultiPolygon": extract3(o.arcs); break;
}
}
geometry(object);
geomsByArc.forEach(filter == null
? function(geoms) { arcs.push(geoms[0].i); }
: function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });
return arcs;
}
// CONCATENATED MODULE: ./node_modules/topojson-client/src/merge.js
function merge_planarRingArea(ring) {
var i = -1, n = ring.length, a, b = ring[n - 1], area = 0;
while (++i < n) a = b, b = ring[i], area += a[0] * b[1] - a[1] * b[0];
return Math.abs(area); // Note: doubled area!
}
/* harmony default export */ var src_merge = (function(topology) {
return feature_object(topology, merge_mergeArcs.apply(this, arguments));
});
function merge_mergeArcs(topology, objects) {
var polygonsByArc = {},
polygons = [],
groups = [];
objects.forEach(geometry);
function geometry(o) {
switch (o.type) {
case "GeometryCollection": o.geometries.forEach(geometry); break;
case "Polygon": extract(o.arcs); break;
case "MultiPolygon": o.arcs.forEach(extract); break;
}
}
function extract(polygon) {
polygon.forEach(function(ring) {
ring.forEach(function(arc) {
(polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
});
});
polygons.push(polygon);
}
function area(ring) {
return merge_planarRingArea(feature_object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]);
}
polygons.forEach(function(polygon) {
if (!polygon._) {
var group = [],
neighbors = [polygon];
polygon._ = 1;
groups.push(group);
while (polygon = neighbors.pop()) {
group.push(polygon);
polygon.forEach(function(ring) {
ring.forEach(function(arc) {
polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
if (!polygon._) {
polygon._ = 1;
neighbors.push(polygon);
}
});
});
});
}
}
});
polygons.forEach(function(polygon) {
delete polygon._;
});
return {
type: "MultiPolygon",
arcs: groups.map(function(polygons) {
var arcs = [], n;
// Extract the exterior (unique) arcs.
polygons.forEach(function(polygon) {
polygon.forEach(function(ring) {
ring.forEach(function(arc) {
if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
arcs.push(arc);
}
});
});
});
// Stitch the arcs into one or more rings.
arcs = stitch(topology, arcs);
// If more than one ring is returned,
// at most one of these rings can be the exterior;
// choose the one with the greatest absolute area.
if ((n = arcs.length) > 1) {
for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) {
if ((ki = area(arcs[i])) > k) {
t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki;
}
}
}
return arcs;
}).filter(function(arcs) {
return arcs.length > 0;
})
};
}
// CONCATENATED MODULE: ./node_modules/topojson-client/src/bisect.js
/* harmony default export */ var src_bisect = (function(a, x) {
var lo = 0, hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (a[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/neighbors.js
/* harmony default export */ var src_neighbors = (function(objects) {
var indexesByArc = {}, // arc index -> array of object indexes
neighbors = objects.map(function() { return []; });
function line(arcs, i) {
arcs.forEach(function(a) {
if (a < 0) a = ~a;
var o = indexesByArc[a];
if (o) o.push(i);
else indexesByArc[a] = [i];
});
}
function polygon(arcs, i) {
arcs.forEach(function(arc) { line(arc, i); });
}
function geometry(o, i) {
if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
}
var geometryType = {
LineString: line,
MultiLineString: polygon,
Polygon: polygon,
MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
};
objects.forEach(geometry);
for (var i in indexesByArc) {
for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
for (var k = j + 1; k < m; ++k) {
var ij = indexes[j], ik = indexes[k], n;
if ((n = neighbors[ij])[i = src_bisect(n, ik)] !== ik) n.splice(i, 0, ik);
if ((n = neighbors[ik])[i = src_bisect(n, ij)] !== ij) n.splice(i, 0, ij);
}
}
}
return neighbors;
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/untransform.js
/* harmony default export */ var src_untransform = (function(transform) {
if (transform == null) return src_identity;
var x0,
y0,
kx = transform.scale[0],
ky = transform.scale[1],
dx = transform.translate[0],
dy = transform.translate[1];
return function(input, i) {
if (!i) x0 = y0 = 0;
var j = 2,
n = input.length,
output = new Array(n),
x1 = Math.round((input[0] - dx) / kx),
y1 = Math.round((input[1] - dy) / ky);
output[0] = x1 - x0, x0 = x1;
output[1] = y1 - y0, y0 = y1;
while (j < n) output[j] = input[j], ++j;
return output;
};
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/quantize.js
/* harmony default export */ var src_quantize = (function(topology, transform) {
if (topology.transform) throw new Error("already quantized");
if (!transform || !transform.scale) {
if (!((n = Math.floor(transform)) >= 2)) throw new Error("n must be ≥2");
box = topology.bbox || src_bbox(topology);
var x0 = box[0], y0 = box[1], x1 = box[2], y1 = box[3], n;
transform = {scale: [x1 - x0 ? (x1 - x0) / (n - 1) : 1, y1 - y0 ? (y1 - y0) / (n - 1) : 1], translate: [x0, y0]};
} else {
box = topology.bbox;
}
var t = src_untransform(transform), box, key, inputs = topology.objects, outputs = {};
function quantizePoint(point) {
return t(point);
}
function quantizeGeometry(input) {
var output;
switch (input.type) {
case "GeometryCollection": output = {type: "GeometryCollection", geometries: input.geometries.map(quantizeGeometry)}; break;
case "Point": output = {type: "Point", coordinates: quantizePoint(input.coordinates)}; break;
case "MultiPoint": output = {type: "MultiPoint", coordinates: input.coordinates.map(quantizePoint)}; break;
default: return input;
}
if (input.id != null) output.id = input.id;
if (input.bbox != null) output.bbox = input.bbox;
if (input.properties != null) output.properties = input.properties;
return output;
}
function quantizeArc(input) {
var i = 0, j = 1, n = input.length, p, output = new Array(n); // pessimistic
output[0] = t(input[0], 0);
while (++i < n) if ((p = t(input[i], i))[0] || p[1]) output[j++] = p; // non-coincident points
if (j === 1) output[j++] = [0, 0]; // an arc must have at least two points
output.length = j;
return output;
}
for (key in inputs) outputs[key] = quantizeGeometry(inputs[key]);
return {
type: "Topology",
bbox: box,
transform: transform,
objects: outputs,
arcs: topology.arcs.map(quantizeArc)
};
});
// CONCATENATED MODULE: ./node_modules/topojson-client/src/index.js
// CONCATENATED MODULE: ./node_modules/vega-loader/src/formats/topojson.js
const topojson_filters = {
interior: (a, b) => a !== b,
exterior: (a, b) => a === b
};
function topojson_topojson(data, format) {
let method, object, property, filter;
data = Object(json["a" /* default */])(data, format);
if (format && format.feature) {
method = src_feature;
property = format.feature;
} else if (format && format.mesh) {
method = mesh;
property = format.mesh;
filter = topojson_filters[format.filter];
} else {
Object(vega_util["n" /* error */])('Missing TopoJSON feature or mesh parameter.');
}
object = (object = data.objects[property])
? method(data, object, filter)
: Object(vega_util["n" /* error */])('Invalid TopoJSON object: ' + property);
return object && object.features || [object];
}
topojson_topojson.responseType = 'json';
// CONCATENATED MODULE: ./node_modules/vega-loader/src/formats/index.js
const formats_format = {
dsv: dsv_dsv,
csv: dsv_delimitedFormat(','),
tsv: dsv_delimitedFormat('\t'),
json: json["a" /* default */],
topojson: topojson_topojson
};
function formats_formats(name, reader) {
if (arguments.length > 1) {
formats_format[name] = reader;
return this;
} else {
return Object(vega_util["v" /* hasOwnProperty */])(formats_format, name) ? formats_format[name] : null;
}
}
function formats_responseType(type) {
const f = formats_formats(type);
return f && f.responseType || 'text';
}
// CONCATENATED MODULE: ./node_modules/d3-time/src/interval.js
var interval_t0 = new Date,
interval_t1 = new Date;
function newInterval(floori, offseti, count, field) {
function interval(date) {
return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;
}
interval.floor = function(date) {
return floori(date = new Date(+date)), date;
};
interval.ceil = function(date) {
return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
};
interval.round = function(date) {
var d0 = interval(date),
d1 = interval.ceil(date);
return date - d0 < d1 - date ? d0 : d1;
};
interval.offset = function(date, step) {
return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
};
interval.range = function(start, stop, step) {
var range = [], previous;
start = interval.ceil(start);
step = step == null ? 1 : Math.floor(step);
if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
while (previous < start && start < stop);
return range;
};
interval.filter = function(test) {
return newInterval(function(date) {
if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
}, function(date, step) {
if (date >= date) {
if (step < 0) while (++step <= 0) {
while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty
} else while (--step >= 0) {
while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty
}
}
});
};
if (count) {
interval.count = function(start, end) {
interval_t0.setTime(+start), interval_t1.setTime(+end);
floori(interval_t0), floori(interval_t1);
return Math.floor(count(interval_t0, interval_t1));
};
interval.every = function(step) {
step = Math.floor(step);
return !isFinite(step) || !(step > 0) ? null
: !(step > 1) ? interval
: interval.filter(field
? function(d) { return field(d) % step === 0; }
: function(d) { return interval.count(0, d) % step === 0; });
};
}
return interval;
}
// CONCATENATED MODULE: ./node_modules/d3-time/src/duration.js
var duration_durationSecond = 1e3;
var duration_durationMinute = 6e4;
var duration_durationHour = 36e5;
var duration_durationDay = 864e5;
var duration_durationWeek = 6048e5;
// CONCATENATED MODULE: ./node_modules/d3-time/src/utcWeek.js
function utcWeek_utcWeekday(i) {
return newInterval(function(date) {
date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step * 7);
}, function(start, end) {
return (end - start) / duration_durationWeek;
});
}
var utcWeek_utcSunday = utcWeek_utcWeekday(0);
var utcWeek_utcMonday = utcWeek_utcWeekday(1);
var utcWeek_utcTuesday = utcWeek_utcWeekday(2);
var utcWeek_utcWednesday = utcWeek_utcWeekday(3);
var utcWeek_utcThursday = utcWeek_utcWeekday(4);
var utcWeek_utcFriday = utcWeek_utcWeekday(5);
var utcWeek_utcSaturday = utcWeek_utcWeekday(6);
var utcWeek_utcSundays = utcWeek_utcSunday.range;
var utcWeek_utcMondays = utcWeek_utcMonday.range;
var utcWeek_utcTuesdays = utcWeek_utcTuesday.range;
var utcWeek_utcWednesdays = utcWeek_utcWednesday.range;
var utcWeek_utcThursdays = utcWeek_utcThursday.range;
var utcWeek_utcFridays = utcWeek_utcFriday.range;
var utcWeek_utcSaturdays = utcWeek_utcSaturday.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/utcDay.js
var utcDay_utcDay = newInterval(function(date) {
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
return (end - start) / duration_durationDay;
}, function(date) {
return date.getUTCDate() - 1;
});
/* harmony default export */ var src_utcDay = (utcDay_utcDay);
var utcDay_utcDays = utcDay_utcDay.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/week.js
function week_weekday(i) {
return newInterval(function(date) {
date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + step * 7);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * duration_durationMinute) / duration_durationWeek;
});
}
var week_sunday = week_weekday(0);
var week_monday = week_weekday(1);
var week_tuesday = week_weekday(2);
var week_wednesday = week_weekday(3);
var week_thursday = week_weekday(4);
var week_friday = week_weekday(5);
var week_saturday = week_weekday(6);
var week_sundays = week_sunday.range;
var week_mondays = week_monday.range;
var week_tuesdays = week_tuesday.range;
var week_wednesdays = week_wednesday.range;
var week_thursdays = week_thursday.range;
var week_fridays = week_friday.range;
var week_saturdays = week_saturday.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/day.js
var day_day = newInterval(function(date) {
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + step);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * duration_durationMinute) / duration_durationDay;
}, function(date) {
return date.getDate() - 1;
});
/* harmony default export */ var src_day = (day_day);
var day_days = day_day.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/year.js
var year_year = newInterval(function(date) {
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
return end.getFullYear() - start.getFullYear();
}, function(date) {
return date.getFullYear();
});
// An optimized implementation for this simple case.
year_year.every = function(k) {
return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
date.setFullYear(Math.floor(date.getFullYear() / k) * k);
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step * k);
});
};
/* harmony default export */ var src_year = (year_year);
var year_years = year_year.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/utcYear.js
var utcYear_utcYear = newInterval(function(date) {
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
return date.getUTCFullYear();
});
// An optimized implementation for this simple case.
utcYear_utcYear.every = function(k) {
return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) {
date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step * k);
});
};
/* harmony default export */ var src_utcYear = (utcYear_utcYear);
var utcYear_utcYears = utcYear_utcYear.range;
// CONCATENATED MODULE: ./node_modules/d3-time-format/src/locale.js
function locale_localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
date.setFullYear(d.y);
return date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function locale_utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
date.setUTCFullYear(d.y);
return date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function locale_newDate(y, m, d) {
return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};
}
function locale_formatLocale(locale) {
var locale_dateTime = locale.dateTime,
locale_date = locale.date,
locale_time = locale.time,
locale_periods = locale.periods,
locale_weekdays = locale.days,
locale_shortWeekdays = locale.shortDays,
locale_months = locale.months,
locale_shortMonths = locale.shortMonths;
var periodRe = locale_formatRe(locale_periods),
periodLookup = locale_formatLookup(locale_periods),
weekdayRe = locale_formatRe(locale_weekdays),
weekdayLookup = locale_formatLookup(locale_weekdays),
shortWeekdayRe = locale_formatRe(locale_shortWeekdays),
shortWeekdayLookup = locale_formatLookup(locale_shortWeekdays),
monthRe = locale_formatRe(locale_months),
monthLookup = locale_formatLookup(locale_months),
shortMonthRe = locale_formatRe(locale_shortMonths),
shortMonthLookup = locale_formatLookup(locale_shortMonths);
var formats = {
"a": formatShortWeekday,
"A": formatWeekday,
"b": formatShortMonth,
"B": formatMonth,
"c": null,
"d": locale_formatDayOfMonth,
"e": locale_formatDayOfMonth,
"f": locale_formatMicroseconds,
"H": locale_formatHour24,
"I": locale_formatHour12,
"j": locale_formatDayOfYear,
"L": locale_formatMilliseconds,
"m": locale_formatMonthNumber,
"M": locale_formatMinutes,
"p": formatPeriod,
"q": formatQuarter,
"Q": locale_formatUnixTimestamp,
"s": locale_formatUnixTimestampSeconds,
"S": locale_formatSeconds,
"u": locale_formatWeekdayNumberMonday,
"U": locale_formatWeekNumberSunday,
"V": locale_formatWeekNumberISO,
"w": locale_formatWeekdayNumberSunday,
"W": locale_formatWeekNumberMonday,
"x": null,
"X": null,
"y": locale_formatYear,
"Y": locale_formatFullYear,
"Z": locale_formatZone,
"%": locale_formatLiteralPercent
};
var utcFormats = {
"a": formatUTCShortWeekday,
"A": formatUTCWeekday,
"b": formatUTCShortMonth,
"B": formatUTCMonth,
"c": null,
"d": locale_formatUTCDayOfMonth,
"e": locale_formatUTCDayOfMonth,
"f": locale_formatUTCMicroseconds,
"H": locale_formatUTCHour24,
"I": locale_formatUTCHour12,
"j": locale_formatUTCDayOfYear,
"L": locale_formatUTCMilliseconds,
"m": locale_formatUTCMonthNumber,
"M": locale_formatUTCMinutes,
"p": formatUTCPeriod,
"q": formatUTCQuarter,
"Q": locale_formatUnixTimestamp,
"s": locale_formatUnixTimestampSeconds,
"S": locale_formatUTCSeconds,
"u": locale_formatUTCWeekdayNumberMonday,
"U": locale_formatUTCWeekNumberSunday,
"V": locale_formatUTCWeekNumberISO,
"w": locale_formatUTCWeekdayNumberSunday,
"W": locale_formatUTCWeekNumberMonday,
"x": null,
"X": null,
"y": locale_formatUTCYear,
"Y": locale_formatUTCFullYear,
"Z": locale_formatUTCZone,
"%": locale_formatLiteralPercent
};
var parses = {
"a": parseShortWeekday,
"A": parseWeekday,
"b": parseShortMonth,
"B": parseMonth,
"c": parseLocaleDateTime,
"d": locale_parseDayOfMonth,
"e": locale_parseDayOfMonth,
"f": locale_parseMicroseconds,
"H": locale_parseHour24,
"I": locale_parseHour24,
"j": locale_parseDayOfYear,
"L": locale_parseMilliseconds,
"m": locale_parseMonthNumber,
"M": locale_parseMinutes,
"p": parsePeriod,
"q": locale_parseQuarter,
"Q": locale_parseUnixTimestamp,
"s": locale_parseUnixTimestampSeconds,
"S": locale_parseSeconds,
"u": locale_parseWeekdayNumberMonday,
"U": locale_parseWeekNumberSunday,
"V": locale_parseWeekNumberISO,
"w": locale_parseWeekdayNumberSunday,
"W": locale_parseWeekNumberMonday,
"x": parseLocaleDate,
"X": parseLocaleTime,
"y": locale_parseYear,
"Y": locale_parseFullYear,
"Z": locale_parseZone,
"%": locale_parseLiteralPercent
};
// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats);
formats.X = newFormat(locale_time, formats);
formats.c = newFormat(locale_dateTime, formats);
utcFormats.x = newFormat(locale_date, utcFormats);
utcFormats.X = newFormat(locale_time, utcFormats);
utcFormats.c = newFormat(locale_dateTime, utcFormats);
function newFormat(specifier, formats) {
return function(date) {
var string = [],
i = -1,
j = 0,
n = specifier.length,
c,
pad,
format;
if (!(date instanceof Date)) date = new Date(+date);
while (++i < n) {
if (specifier.charCodeAt(i) === 37) {
string.push(specifier.slice(j, i));
if ((pad = locale_pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
else pad = c === "e" ? " " : "0";
if (format = formats[c]) c = format(date, pad);
string.push(c);
j = i + 1;
}
}
string.push(specifier.slice(j, i));
return string.join("");
};
}
function newParse(specifier, Z) {
return function(string) {
var d = locale_newDate(1900, undefined, 1),
i = parseSpecifier(d, specifier, string += "", 0),
week, day;
if (i != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d) return new Date(d.s * 1000 + ("L" in d ? d.L : 0));
// If this is utcParse, never use the local timezone.
if (Z && !("Z" in d)) d.Z = 0;
// The am-pm flag is 0 for AM, and 1 for PM.
if ("p" in d) d.H = d.H % 12 + d.p * 12;
// If the month was not specified, inherit from the quarter.
if (d.m === undefined) d.m = "q" in d ? d.q : 0;
// Convert day-of-week and week-of-year to day-of-year.
if ("V" in d) {
if (d.V < 1 || d.V > 53) return null;
if (!("w" in d)) d.w = 1;
if ("Z" in d) {
week = locale_utcDate(locale_newDate(d.y, 0, 1)), day = week.getUTCDay();
week = day > 4 || day === 0 ? utcWeek_utcMonday.ceil(week) : utcWeek_utcMonday(week);
week = src_utcDay.offset(week, (d.V - 1) * 7);
d.y = week.getUTCFullYear();
d.m = week.getUTCMonth();
d.d = week.getUTCDate() + (d.w + 6) % 7;
} else {
week = locale_localDate(locale_newDate(d.y, 0, 1)), day = week.getDay();
week = day > 4 || day === 0 ? week_monday.ceil(week) : week_monday(week);
week = src_day.offset(week, (d.V - 1) * 7);
d.y = week.getFullYear();
d.m = week.getMonth();
d.d = week.getDate() + (d.w + 6) % 7;
}
} else if ("W" in d || "U" in d) {
if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
day = "Z" in d ? locale_utcDate(locale_newDate(d.y, 0, 1)).getUTCDay() : locale_localDate(locale_newDate(d.y, 0, 1)).getDay();
d.m = 0;
d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
}
// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
if ("Z" in d) {
d.H += d.Z / 100 | 0;
d.M += d.Z % 100;
return locale_utcDate(d);
}
// Otherwise, all fields are in local time.
return locale_localDate(d);
};
}
function parseSpecifier(d, specifier, string, j) {
var i = 0,
n = specifier.length,
m = string.length,
c,
parse;
while (i < n) {
if (j >= m) return -1;
c = specifier.charCodeAt(i++);
if (c === 37) {
c = specifier.charAt(i++);
parse = parses[c in locale_pads ? specifier.charAt(i++) : c];
if (!parse || ((j = parse(d, string, j)) < 0)) return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
function parsePeriod(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseShortWeekday(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseWeekday(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseShortMonth(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseMonth(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseLocaleDateTime(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
}
function parseLocaleDate(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
}
function parseLocaleTime(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
}
function formatShortWeekday(d) {
return locale_shortWeekdays[d.getDay()];
}
function formatWeekday(d) {
return locale_weekdays[d.getDay()];
}
function formatShortMonth(d) {
return locale_shortMonths[d.getMonth()];
}
function formatMonth(d) {
return locale_months[d.getMonth()];
}
function formatPeriod(d) {
return locale_periods[+(d.getHours() >= 12)];
}
function formatQuarter(d) {
return 1 + ~~(d.getMonth() / 3);
}
function formatUTCShortWeekday(d) {
return locale_shortWeekdays[d.getUTCDay()];
}
function formatUTCWeekday(d) {
return locale_weekdays[d.getUTCDay()];
}
function formatUTCShortMonth(d) {
return locale_shortMonths[d.getUTCMonth()];
}
function formatUTCMonth(d) {
return locale_months[d.getUTCMonth()];
}
function formatUTCPeriod(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
}
function formatUTCQuarter(d) {
return 1 + ~~(d.getUTCMonth() / 3);
}
return {
format: function(specifier) {
var f = newFormat(specifier += "", formats);
f.toString = function() { return specifier; };
return f;
},
parse: function(specifier) {
var p = newParse(specifier += "", false);
p.toString = function() { return specifier; };
return p;
},
utcFormat: function(specifier) {
var f = newFormat(specifier += "", utcFormats);
f.toString = function() { return specifier; };
return f;
},
utcParse: function(specifier) {
var p = newParse(specifier += "", true);
p.toString = function() { return specifier; };
return p;
}
};
}
var locale_pads = {"-": "", "_": " ", "0": "0"},
locale_numberRe = /^\s*\d+/, // note: ignores next directive
locale_percentRe = /^%/,
locale_requoteRe = /[\\^$*+?|[\]().{}]/g;
function locale_pad(value, fill, width) {
var sign = value < 0 ? "-" : "",
string = (sign ? -value : value) + "",
length = string.length;
return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}
function locale_requote(s) {
return s.replace(locale_requoteRe, "\\$&");
}
function locale_formatRe(names) {
return new RegExp("^(?:" + names.map(locale_requote).join("|") + ")", "i");
}
function locale_formatLookup(names) {
var map = {}, i = -1, n = names.length;
while (++i < n) map[names[i].toLowerCase()] = i;
return map;
}
function locale_parseWeekdayNumberSunday(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 1));
return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function locale_parseWeekdayNumberMonday(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 1));
return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function locale_parseWeekNumberSunday(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function locale_parseWeekNumberISO(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function locale_parseWeekNumberMonday(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function locale_parseFullYear(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 4));
return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function locale_parseYear(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}
function locale_parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function locale_parseQuarter(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 1));
return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
}
function locale_parseMonthNumber(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function locale_parseDayOfMonth(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function locale_parseDayOfYear(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 3));
return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function locale_parseHour24(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function locale_parseMinutes(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function locale_parseSeconds(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 2));
return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function locale_parseMilliseconds(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 3));
return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function locale_parseMicroseconds(d, string, i) {
var n = locale_numberRe.exec(string.slice(i, i + 6));
return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}
function locale_parseLiteralPercent(d, string, i) {
var n = locale_percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function locale_parseUnixTimestamp(d, string, i) {
var n = locale_numberRe.exec(string.slice(i));
return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function locale_parseUnixTimestampSeconds(d, string, i) {
var n = locale_numberRe.exec(string.slice(i));
return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function locale_formatDayOfMonth(d, p) {
return locale_pad(d.getDate(), p, 2);
}
function locale_formatHour24(d, p) {
return locale_pad(d.getHours(), p, 2);
}
function locale_formatHour12(d, p) {
return locale_pad(d.getHours() % 12 || 12, p, 2);
}
function locale_formatDayOfYear(d, p) {
return locale_pad(1 + src_day.count(src_year(d), d), p, 3);
}
function locale_formatMilliseconds(d, p) {
return locale_pad(d.getMilliseconds(), p, 3);
}
function locale_formatMicroseconds(d, p) {
return locale_formatMilliseconds(d, p) + "000";
}
function locale_formatMonthNumber(d, p) {
return locale_pad(d.getMonth() + 1, p, 2);
}
function locale_formatMinutes(d, p) {
return locale_pad(d.getMinutes(), p, 2);
}
function locale_formatSeconds(d, p) {
return locale_pad(d.getSeconds(), p, 2);
}
function locale_formatWeekdayNumberMonday(d) {
var day = d.getDay();
return day === 0 ? 7 : day;
}
function locale_formatWeekNumberSunday(d, p) {
return locale_pad(week_sunday.count(src_year(d) - 1, d), p, 2);
}
function locale_formatWeekNumberISO(d, p) {
var day = d.getDay();
d = (day >= 4 || day === 0) ? week_thursday(d) : week_thursday.ceil(d);
return locale_pad(week_thursday.count(src_year(d), d) + (src_year(d).getDay() === 4), p, 2);
}
function locale_formatWeekdayNumberSunday(d) {
return d.getDay();
}
function locale_formatWeekNumberMonday(d, p) {
return locale_pad(week_monday.count(src_year(d) - 1, d), p, 2);
}
function locale_formatYear(d, p) {
return locale_pad(d.getFullYear() % 100, p, 2);
}
function locale_formatFullYear(d, p) {
return locale_pad(d.getFullYear() % 10000, p, 4);
}
function locale_formatZone(d) {
var z = d.getTimezoneOffset();
return (z > 0 ? "-" : (z *= -1, "+"))
+ locale_pad(z / 60 | 0, "0", 2)
+ locale_pad(z % 60, "0", 2);
}
function locale_formatUTCDayOfMonth(d, p) {
return locale_pad(d.getUTCDate(), p, 2);
}
function locale_formatUTCHour24(d, p) {
return locale_pad(d.getUTCHours(), p, 2);
}
function locale_formatUTCHour12(d, p) {
return locale_pad(d.getUTCHours() % 12 || 12, p, 2);
}
function locale_formatUTCDayOfYear(d, p) {
return locale_pad(1 + src_utcDay.count(src_utcYear(d), d), p, 3);
}
function locale_formatUTCMilliseconds(d, p) {
return locale_pad(d.getUTCMilliseconds(), p, 3);
}
function locale_formatUTCMicroseconds(d, p) {
return locale_formatUTCMilliseconds(d, p) + "000";
}
function locale_formatUTCMonthNumber(d, p) {
return locale_pad(d.getUTCMonth() + 1, p, 2);
}
function locale_formatUTCMinutes(d, p) {
return locale_pad(d.getUTCMinutes(), p, 2);
}
function locale_formatUTCSeconds(d, p) {
return locale_pad(d.getUTCSeconds(), p, 2);
}
function locale_formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return dow === 0 ? 7 : dow;
}
function locale_formatUTCWeekNumberSunday(d, p) {
return locale_pad(utcWeek_utcSunday.count(src_utcYear(d) - 1, d), p, 2);
}
function locale_formatUTCWeekNumberISO(d, p) {
var day = d.getUTCDay();
d = (day >= 4 || day === 0) ? utcWeek_utcThursday(d) : utcWeek_utcThursday.ceil(d);
return locale_pad(utcWeek_utcThursday.count(src_utcYear(d), d) + (src_utcYear(d).getUTCDay() === 4), p, 2);
}
function locale_formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function locale_formatUTCWeekNumberMonday(d, p) {
return locale_pad(utcWeek_utcMonday.count(src_utcYear(d) - 1, d), p, 2);
}
function locale_formatUTCYear(d, p) {
return locale_pad(d.getUTCFullYear() % 100, p, 2);
}
function locale_formatUTCFullYear(d, p) {
return locale_pad(d.getUTCFullYear() % 10000, p, 4);
}
function locale_formatUTCZone() {
return "+0000";
}
function locale_formatLiteralPercent() {
return "%";
}
function locale_formatUnixTimestamp(d) {
return +d;
}
function locale_formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
}
// CONCATENATED MODULE: ./node_modules/d3-time-format/src/defaultLocale.js
var defaultLocale_locale;
var defaultLocale_timeFormat;
var defaultLocale_timeParse;
var defaultLocale_utcFormat;
var defaultLocale_utcParse;
defaultLocale_defaultLocale({
dateTime: "%x, %X",
date: "%-m/%-d/%Y",
time: "%-I:%M:%S %p",
periods: ["AM", "PM"],
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
function defaultLocale_defaultLocale(definition) {
defaultLocale_locale = locale_formatLocale(definition);
defaultLocale_timeFormat = defaultLocale_locale.format;
defaultLocale_timeParse = defaultLocale_locale.parse;
defaultLocale_utcFormat = defaultLocale_locale.utcFormat;
defaultLocale_utcParse = defaultLocale_locale.utcParse;
return defaultLocale_locale;
}
// CONCATENATED MODULE: ./node_modules/vega-loader/src/read.js
/* harmony default export */ var read = (function(data, schema, dateParse) {
schema = schema || {};
const reader = formats_formats(schema.type || 'json');
if (!reader) Object(vega_util["n" /* error */])('Unknown data format type: ' + schema.type);
data = reader(data, schema);
if (schema.parse) read_parse(data, schema.parse, dateParse);
if (Object(vega_util["v" /* hasOwnProperty */])(data, 'columns')) delete data.columns;
return data;
});
function read_parse(data, types, dateParse) {
if (!data.length) return; // early exit for empty data
dateParse = dateParse || defaultLocale_timeParse;
var fields = data.columns || Object.keys(data[0]),
parsers, datum, field, i, j, n, m;
if (types === 'auto') types = type_inferTypes(data, fields);
fields = Object.keys(types);
parsers = fields.map(function(field) {
var type = types[field],
parts, pattern;
if (type && (type.startsWith('date:') || type.startsWith('utc:'))) {
parts = type.split(/:(.+)?/, 2); // split on first :
pattern = parts[1];
if ((pattern[0] === '\'' && pattern[pattern.length-1] === '\'') ||
(pattern[0] === '"' && pattern[pattern.length-1] === '"')) {
pattern = pattern.slice(1, -1);
}
return parts[0] === 'utc' ? defaultLocale_utcParse(pattern) : dateParse(pattern);
}
if (!type_typeParsers[type]) {
throw Error('Illegal format pattern: ' + field + ':' + type);
}
return type_typeParsers[type];
});
for (i=0, n=data.length, m=fields.length; i<n; ++i) {
datum = data[i];
for (j=0; j<m; ++j) {
field = fields[j];
datum[field] = parsers[j](datum[field]);
}
}
}
// CONCATENATED MODULE: ./node_modules/vega-loader/index.browser.js
var index_browser_loader = src_loader(
typeof fetch !== 'undefined' && fetch, // use built-in fetch API
null // no file system access
);
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/load.js
const load_parse = read;
/**
* Ingests new data into the dataflow. First parses the data using the
* vega-loader read method, then pulses a changeset to the target operator.
* @param {Operator} target - The Operator to target with ingested data,
* typically a Collect transform instance.
* @param {*} data - The input data, prior to parsing. For JSON this may
* be a string or an object. For CSV, TSV, etc should be a string.
* @param {object} format - The data format description for parsing
* loaded data. This object is passed to the vega-loader read method.
* @returns {Dataflow}
*/
function load_ingest(target, data, format) {
return this.pulse(target, this.changeset().insert(load_parse(data, format)));
}
/**
* Request data from an external source, parse it, and return a Promise.
* @param {string} url - The URL from which to load the data. This string
* is passed to the vega-loader load method.
* @param {object} [format] - The data format description for parsing
* loaded data. This object is passed to the vega-loader read method.
* @return {Promise} A Promise that resolves upon completion of the request.
* The resolved object contains the following properties:
* - data: an array of parsed data (or null upon error)
* - status: a code for success (0), load fail (-1), or parse fail (-2)
*/
async function load_request(url, format) {
const df = this;
let status = 0, data;
try {
data = await df.loader().load(url, {
context: 'dataflow',
response: formats_responseType(format && format.type)
});
try {
data = load_parse(data, format);
} catch (err) {
status = -2;
df.warn('Data ingestion failed', url, err);
}
} catch (err) {
status = -1;
df.warn('Loading failed', url, err);
}
return {data, status};
}
async function load_preload(target, url, format) {
const df = this,
pending = df._pending || load_loadPending(df);
pending.requests += 1;
const res = await df.request(url, format);
df.pulse(target, df.changeset().remove(vega_util["Ga" /* truthy */]).insert(res.data || []));
pending.done();
return res;
}
function load_loadPending(df) {
var pending = new Promise(function(a) { accept = a; }),
accept;
pending.requests = 0;
pending.done = function() {
if (--pending.requests === 0) {
df._pending = null;
accept(df);
}
};
return (df._pending = pending);
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/on.js
var on_SKIP = {skip: true};
/**
* Perform operator updates in response to events. Applies an
* update function to compute a new operator value. If the update function
* returns a {@link ChangeSet}, the operator will be pulsed with those tuple
* changes. Otherwise, the operator value will be updated to the return value.
* @param {EventStream|Operator} source - The event source to react to.
* This argument can be either an EventStream or an Operator.
* @param {Operator|function(object):Operator} target - The operator to update.
* This argument can either be an Operator instance or (if the source
* argument is an EventStream), a function that accepts an event object as
* input and returns an Operator to target.
* @param {function(Parameters,Event): *} [update] - Optional update function
* to compute the new operator value, or a literal value to set. Update
* functions expect to receive a parameter object and event as arguments.
* This function can either return a new operator value or (if the source
* argument is an EventStream) a {@link ChangeSet} instance to pulse
* the target operator with tuple changes.
* @param {object} [params] - The update function parameters.
* @param {object} [options] - Additional options hash. If not overridden,
* updated operators will be skipped by default.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @param {boolean} [options.force] - If true, the operator will
* be re-evaluated even if its value has not changed.
* @return {Dataflow}
*/
/* harmony default export */ var dataflow_on = (function(source, target, update, params, options) {
var fn = source instanceof Operator_Operator ? on_onOperator : on_onStream;
fn(this, source, target, update, params, options);
return this;
});
function on_onStream(df, stream, target, update, params, options) {
var opt = Object(vega_util["o" /* extend */])({}, options, on_SKIP), func, op;
if (!Object(vega_util["D" /* isFunction */])(target)) target = Object(vega_util["l" /* constant */])(target);
if (update === undefined) {
func = e => df.touch(target(e));
} else if (Object(vega_util["D" /* isFunction */])(update)) {
op = new Operator_Operator(null, update, params, false);
func = e => {
op.evaluate(e);
const t = target(e), v = op.value;
ChangeSet_isChangeSet(v) ? df.pulse(t, v, options) : df.update(t, v, opt);
};
} else {
func = e => df.update(target(e), update, opt);
}
stream.apply(func);
}
function on_onOperator(df, source, target, update, params, options) {
if (update === undefined) {
source.targets().add(target);
} else {
const opt = options || {},
op = new Operator_Operator(null, on_updater(target, update), params, false);
op.modified(opt.force);
op.rank = source.rank; // immediately follow source
source.targets().add(op); // add dependency
if (target) {
op.skip(true); // skip first invocation
op.value = target.value; // initialize value
op.targets().add(target); // chain dependencies
df.connect(target, [op]); // rerank as needed, #1672
}
}
}
function on_updater(target, update) {
update = Object(vega_util["D" /* isFunction */])(update) ? update : Object(vega_util["l" /* constant */])(update);
return target
? function(_, pulse) {
const value = update(_, pulse);
if (!target.skip()) {
target.skip(value !== this.value).value = value;
}
return value;
}
: update;
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/rank.js
/**
* Assigns a rank to an operator. Ranks are assigned in increasing order
* by incrementing an internal rank counter.
* @param {Operator} op - The operator to assign a rank.
*/
function rank_rank(op) {
op.rank = ++this._rank;
}
/**
* Re-ranks an operator and all downstream target dependencies. This
* is necessary when upstream dependencies of higher rank are added to
* a target operator.
* @param {Operator} op - The operator to re-rank.
*/
function rank_rerank(op) {
var queue = [op],
cur, list, i;
while (queue.length) {
this.rank(cur = queue.pop());
if (list = cur._targets) {
for (i=list.length; --i >= 0;) {
queue.push(cur = list[i]);
if (cur === op) Object(vega_util["n" /* error */])('Cycle detected in dataflow graph.');
}
}
}
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/Pulse.js
/**
* Sentinel value indicating pulse propagation should stop.
*/
var Pulse_StopPropagation = {};
// Pulse visit type flags
var Pulse_ADD = (1 << 0),
Pulse_REM = (1 << 1),
Pulse_MOD = (1 << 2),
Pulse_ADD_REM = Pulse_ADD | Pulse_REM,
Pulse_ADD_MOD = Pulse_ADD | Pulse_MOD,
Pulse_ALL = Pulse_ADD | Pulse_REM | Pulse_MOD,
Pulse_REFLOW = (1 << 3),
Pulse_SOURCE = (1 << 4),
Pulse_NO_SOURCE = (1 << 5),
Pulse_NO_FIELDS = (1 << 6);
/**
* A Pulse enables inter-operator communication during a run of the
* dataflow graph. In addition to the current timestamp, a pulse may also
* contain a change-set of added, removed or modified data tuples, as well as
* a pointer to a full backing data source. Tuple change sets may not
* be fully materialized; for example, to prevent needless array creation
* a change set may include larger arrays and corresponding filter functions.
* The pulse provides a {@link visit} method to enable proper and efficient
* iteration over requested data tuples.
*
* In addition, each pulse can track modification flags for data tuple fields.
* Responsible transform operators should call the {@link modifies} method to
* indicate changes to data fields. The {@link modified} method enables
* querying of this modification state.
*
* @constructor
* @param {Dataflow} dataflow - The backing dataflow instance.
* @param {number} stamp - The current propagation timestamp.
* @param {string} [encode] - An optional encoding set name, which is then
* accessible as Pulse.encode. Operators can respond to (or ignore) this
* setting as appropriate. This parameter can be used in conjunction with
* the Encode transform in the vega-encode module.
*/
function Pulse_Pulse(dataflow, stamp, encode) {
this.dataflow = dataflow;
this.stamp = stamp == null ? -1 : stamp;
this.add = [];
this.rem = [];
this.mod = [];
this.fields = null;
this.encode = encode || null;
}
var Pulse_prototype = Pulse_Pulse.prototype;
/**
* Sentinel value indicating pulse propagation should stop.
*/
Pulse_prototype.StopPropagation = Pulse_StopPropagation;
/**
* Boolean flag indicating ADD (added) tuples.
*/
Pulse_prototype.ADD = Pulse_ADD;
/**
* Boolean flag indicating REM (removed) tuples.
*/
Pulse_prototype.REM = Pulse_REM;
/**
* Boolean flag indicating MOD (modified) tuples.
*/
Pulse_prototype.MOD = Pulse_MOD;
/**
* Boolean flag indicating ADD (added) and REM (removed) tuples.
*/
Pulse_prototype.ADD_REM = Pulse_ADD_REM;
/**
* Boolean flag indicating ADD (added) and MOD (modified) tuples.
*/
Pulse_prototype.ADD_MOD = Pulse_ADD_MOD;
/**
* Boolean flag indicating ADD, REM and MOD tuples.
*/
Pulse_prototype.ALL = Pulse_ALL;
/**
* Boolean flag indicating all tuples in a data source
* except for the ADD, REM and MOD tuples.
*/
Pulse_prototype.REFLOW = Pulse_REFLOW;
/**
* Boolean flag indicating a 'pass-through' to a
* backing data source, ignoring ADD, REM and MOD tuples.
*/
Pulse_prototype.SOURCE = Pulse_SOURCE;
/**
* Boolean flag indicating that source data should be
* suppressed when creating a forked pulse.
*/
Pulse_prototype.NO_SOURCE = Pulse_NO_SOURCE;
/**
* Boolean flag indicating that field modifications should be
* suppressed when creating a forked pulse.
*/
Pulse_prototype.NO_FIELDS = Pulse_NO_FIELDS;
/**
* Creates a new pulse based on the values of this pulse.
* The dataflow, time stamp and field modification values are copied over.
* By default, new empty ADD, REM and MOD arrays are created.
* @param {number} flags - Integer of boolean flags indicating which (if any)
* tuple arrays should be copied to the new pulse. The supported flag values
* are ADD, REM and MOD. Array references are copied directly: new array
* instances are not created.
* @return {Pulse} - The forked pulse instance.
* @see init
*/
Pulse_prototype.fork = function(flags) {
return new Pulse_Pulse(this.dataflow).init(this, flags);
};
/**
* Creates a copy of this pulse with new materialized array
* instances for the ADD, REM, MOD, and SOURCE arrays.
* The dataflow, time stamp and field modification values are copied over.
* @return {Pulse} - The cloned pulse instance.
* @see init
*/
Pulse_prototype.clone = function() {
var p = this.fork(Pulse_ALL);
p.add = p.add.slice();
p.rem = p.rem.slice();
p.mod = p.mod.slice();
if (p.source) p.source = p.source.slice();
return p.materialize(Pulse_ALL | Pulse_SOURCE);
};
/**
* Returns a pulse that adds all tuples from a backing source. This is
* useful for cases where operators are added to a dataflow after an
* upstream data pipeline has already been processed, ensuring that
* new operators can observe all tuples within a stream.
* @return {Pulse} - A pulse instance with all source tuples included
* in the add array. If the current pulse already has all source
* tuples in its add array, it is returned directly. If the current
* pulse does not have a backing source, it is returned directly.
*/
Pulse_prototype.addAll = function() {
var p = this;
if (!this.source || this.source.length === this.add.length) {
return p;
} else {
p = new Pulse_Pulse(this.dataflow).init(this);
p.add = p.source;
return p;
}
};
/**
* Initialize this pulse based on the values of another pulse. This method
* is used internally by {@link fork} to initialize a new forked tuple.
* The dataflow, time stamp and field modification values are copied over.
* By default, new empty ADD, REM and MOD arrays are created.
* @param {Pulse} src - The source pulse to copy from.
* @param {number} flags - Integer of boolean flags indicating which (if any)
* tuple arrays should be copied to the new pulse. The supported flag values
* are ADD, REM and MOD. Array references are copied directly: new array
* instances are not created. By default, source data arrays are copied
* to the new pulse. Use the NO_SOURCE flag to enforce a null source.
* @return {Pulse} - Returns this Pulse instance.
*/
Pulse_prototype.init = function(src, flags) {
var p = this;
p.stamp = src.stamp;
p.encode = src.encode;
if (src.fields && !(flags & Pulse_NO_FIELDS)) {
p.fields = src.fields;
}
if (flags & Pulse_ADD) {
p.addF = src.addF;
p.add = src.add;
} else {
p.addF = null;
p.add = [];
}
if (flags & Pulse_REM) {
p.remF = src.remF;
p.rem = src.rem;
} else {
p.remF = null;
p.rem = [];
}
if (flags & Pulse_MOD) {
p.modF = src.modF;
p.mod = src.mod;
} else {
p.modF = null;
p.mod = [];
}
if (flags & Pulse_NO_SOURCE) {
p.srcF = null;
p.source = null;
} else {
p.srcF = src.srcF;
p.source = src.source;
}
return p;
};
/**
* Schedules a function to run after pulse propagation completes.
* @param {function} func - The function to run.
*/
Pulse_prototype.runAfter = function(func) {
this.dataflow.runAfter(func);
};
/**
* Indicates if tuples have been added, removed or modified.
* @param {number} [flags] - The tuple types (ADD, REM or MOD) to query.
* Defaults to ALL, returning true if any tuple type has changed.
* @return {boolean} - Returns true if one or more queried tuple types have
* changed, false otherwise.
*/
Pulse_prototype.changed = function(flags) {
var f = flags || Pulse_ALL;
return ((f & Pulse_ADD) && this.add.length)
|| ((f & Pulse_REM) && this.rem.length)
|| ((f & Pulse_MOD) && this.mod.length);
};
/**
* Forces a "reflow" of tuple values, such that all tuples in the backing
* source are added to the MOD set, unless already present in the ADD set.
* @param {boolean} [fork=false] - If true, returns a forked copy of this
* pulse, and invokes reflow on that derived pulse.
* @return {Pulse} - The reflowed pulse instance.
*/
Pulse_prototype.reflow = function(fork) {
if (fork) return this.fork(Pulse_ALL).reflow();
var len = this.add.length,
src = this.source && this.source.length;
if (src && src !== len) {
this.mod = this.source;
if (len) this.filter(Pulse_MOD, Pulse_filter(this, Pulse_ADD));
}
return this;
};
/**
* Marks one or more data field names as modified to assist dependency
* tracking and incremental processing by transform operators.
* @param {string|Array<string>} _ - The field(s) to mark as modified.
* @return {Pulse} - This pulse instance.
*/
Pulse_prototype.modifies = function(_) {
var hash = this.fields || (this.fields = {});
if (Object(vega_util["A" /* isArray */])(_)) {
_.forEach(f => hash[f] = true);
} else {
hash[_] = true;
}
return this;
};
/**
* Checks if one or more data fields have been modified during this pulse
* propagation timestamp.
* @param {string|Array<string>} _ - The field(s) to check for modified.
* @param {boolean} nomod - If true, will check the modified flag even if
* no mod tuples exist. If false (default), mod tuples must be present.
* @return {boolean} - Returns true if any of the provided fields has been
* marked as modified, false otherwise.
*/
Pulse_prototype.modified = function(_, nomod) {
var fields = this.fields;
return !((nomod || this.mod.length) && fields) ? false
: !arguments.length ? !!fields
: Object(vega_util["A" /* isArray */])(_) ? _.some(function(f) { return fields[f]; })
: fields[_];
};
/**
* Adds a filter function to one more tuple sets. Filters are applied to
* backing tuple arrays, to determine the actual set of tuples considered
* added, removed or modified. They can be used to delay materialization of
* a tuple set in order to avoid expensive array copies. In addition, the
* filter functions can serve as value transformers: unlike standard predicate
* function (which return boolean values), Pulse filters should return the
* actual tuple value to process. If a tuple set is already filtered, the
* new filter function will be appended into a conjuntive ('and') query.
* @param {number} flags - Flags indicating the tuple set(s) to filter.
* @param {function(*):object} filter - Filter function that will be applied
* to the tuple set array, and should return a data tuple if the value
* should be included in the tuple set, and falsy (or null) otherwise.
* @return {Pulse} - Returns this pulse instance.
*/
Pulse_prototype.filter = function(flags, filter) {
var p = this;
if (flags & Pulse_ADD) p.addF = Pulse_addFilter(p.addF, filter);
if (flags & Pulse_REM) p.remF = Pulse_addFilter(p.remF, filter);
if (flags & Pulse_MOD) p.modF = Pulse_addFilter(p.modF, filter);
if (flags & Pulse_SOURCE) p.srcF = Pulse_addFilter(p.srcF, filter);
return p;
};
function Pulse_addFilter(a, b) {
return a ? function(t,i) { return a(t,i) && b(t,i); } : b;
}
/**
* Materialize one or more tuple sets in this pulse. If the tuple set(s) have
* a registered filter function, it will be applied and the tuple set(s) will
* be replaced with materialized tuple arrays.
* @param {number} flags - Flags indicating the tuple set(s) to materialize.
* @return {Pulse} - Returns this pulse instance.
*/
Pulse_prototype.materialize = function(flags) {
flags = flags || Pulse_ALL;
var p = this;
if ((flags & Pulse_ADD) && p.addF) {
p.add = Pulse_materialize(p.add, p.addF);
p.addF = null;
}
if ((flags & Pulse_REM) && p.remF) {
p.rem = Pulse_materialize(p.rem, p.remF);
p.remF = null;
}
if ((flags & Pulse_MOD) && p.modF) {
p.mod = Pulse_materialize(p.mod, p.modF);
p.modF = null;
}
if ((flags & Pulse_SOURCE) && p.srcF) {
p.source = p.source.filter(p.srcF);
p.srcF = null;
}
return p;
};
function Pulse_materialize(data, filter) {
var out = [];
Object(vega_util["Ia" /* visitArray */])(data, filter, function(_) { out.push(_); });
return out;
}
function Pulse_filter(pulse, flags) {
var map = {};
pulse.visit(flags, function(t) { map[tupleid(t)] = 1; });
return function(t) { return map[tupleid(t)] ? null : t; };
}
/**
* Visit one or more tuple sets in this pulse.
* @param {number} flags - Flags indicating the tuple set(s) to visit.
* Legal values are ADD, REM, MOD and SOURCE (if a backing data source
* has been set).
* @param {function(object):*} - Visitor function invoked per-tuple.
* @return {Pulse} - Returns this pulse instance.
*/
Pulse_prototype.visit = function(flags, visitor) {
var p = this, v = visitor, src, sum;
if (flags & Pulse_SOURCE) {
Object(vega_util["Ia" /* visitArray */])(p.source, p.srcF, v);
return p;
}
if (flags & Pulse_ADD) Object(vega_util["Ia" /* visitArray */])(p.add, p.addF, v);
if (flags & Pulse_REM) Object(vega_util["Ia" /* visitArray */])(p.rem, p.remF, v);
if (flags & Pulse_MOD) Object(vega_util["Ia" /* visitArray */])(p.mod, p.modF, v);
if ((flags & Pulse_REFLOW) && (src = p.source)) {
sum = p.add.length + p.mod.length;
if (sum === src.length) {
// do nothing
} else if (sum) {
Object(vega_util["Ia" /* visitArray */])(src, Pulse_filter(p, Pulse_ADD_MOD), v);
} else {
// if no add/rem/mod tuples, visit source
Object(vega_util["Ia" /* visitArray */])(src, p.srcF, v);
}
}
return p;
};
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/MultiPulse.js
/**
* Represents a set of multiple pulses. Used as input for operators
* that accept multiple pulses at a time. Contained pulses are
* accessible via the public "pulses" array property. This pulse doe
* not carry added, removed or modified tuples directly. However,
* the visit method can be used to traverse all such tuples contained
* in sub-pulses with a timestamp matching this parent multi-pulse.
* @constructor
* @param {Dataflow} dataflow - The backing dataflow instance.
* @param {number} stamp - The timestamp.
* @param {Array<Pulse>} pulses - The sub-pulses for this multi-pulse.
*/
function MultiPulse_MultiPulse(dataflow, stamp, pulses, encode) {
var p = this,
c = 0,
pulse, hash, i, n, f;
this.dataflow = dataflow;
this.stamp = stamp;
this.fields = null;
this.encode = encode || null;
this.pulses = pulses;
for (i=0, n=pulses.length; i<n; ++i) {
pulse = pulses[i];
if (pulse.stamp !== stamp) continue;
if (pulse.fields) {
hash = p.fields || (p.fields = {});
for (f in pulse.fields) { hash[f] = 1; }
}
if (pulse.changed(p.ADD)) c |= p.ADD;
if (pulse.changed(p.REM)) c |= p.REM;
if (pulse.changed(p.MOD)) c |= p.MOD;
}
this.changes = c;
}
var MultiPulse_prototype = Object(vega_util["y" /* inherits */])(MultiPulse_MultiPulse, Pulse_Pulse);
/**
* Creates a new pulse based on the values of this pulse.
* The dataflow, time stamp and field modification values are copied over.
* @return {Pulse}
*/
MultiPulse_prototype.fork = function(flags) {
var p = new Pulse_Pulse(this.dataflow).init(this, flags & this.NO_FIELDS);
if (flags !== undefined) {
if (flags & p.ADD) {
this.visit(p.ADD, function(t) { return p.add.push(t); });
}
if (flags & p.REM) {
this.visit(p.REM, function(t) { return p.rem.push(t); });
}
if (flags & p.MOD) {
this.visit(p.MOD, function(t) { return p.mod.push(t); });
}
}
return p;
};
MultiPulse_prototype.changed = function(flags) {
return this.changes & flags;
};
MultiPulse_prototype.modified = function(_) {
var p = this, fields = p.fields;
return !(fields && (p.changes & p.MOD)) ? 0
: Object(vega_util["A" /* isArray */])(_) ? _.some(function(f) { return fields[f]; })
: fields[_];
};
MultiPulse_prototype.filter = function() {
Object(vega_util["n" /* error */])('MultiPulse does not support filtering.');
};
MultiPulse_prototype.materialize = function() {
Object(vega_util["n" /* error */])('MultiPulse does not support materialization.');
};
MultiPulse_prototype.visit = function(flags, visitor) {
var p = this,
pulses = p.pulses,
n = pulses.length,
i = 0;
if (flags & p.SOURCE) {
for (; i<n; ++i) {
pulses[i].visit(flags, visitor);
}
} else {
for (; i<n; ++i) {
if (pulses[i].stamp === p.stamp) {
pulses[i].visit(flags, visitor);
}
}
}
return p;
};
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/run.js
/* eslint-disable require-atomic-updates */
/**
* Evaluates the dataflow and returns a Promise that resolves when pulse
* propagation completes. This method will increment the current timestamp
* and process all updated, pulsed and touched operators. When invoked for
* the first time, all registered operators will be processed. This method
* should not be invoked by third-party clients, use {@link runAsync} or
* {@link run} instead.
* @param {string} [encode] - The name of an encoding set to invoke during
* propagation. This value is added to generated Pulse instances;
* operators can then respond to (or ignore) this setting as appropriate.
* This parameter can be used in conjunction with the Encode transform in
* the vega-encode package.
* @param {function} [prerun] - An optional callback function to invoke
* immediately before dataflow evaluation commences.
* @param {function} [postrun] - An optional callback function to invoke
* after dataflow evaluation completes. The callback will be invoked
* after those registered via {@link runAfter}.
* @return {Promise} - A promise that resolves to this dataflow after
* evaluation completes.
*/
async function run_evaluate(encode, prerun, postrun) {
const df = this,
level = df.logLevel(),
async = [];
// if the pulse value is set, this is a re-entrant call
if (df._pulse) return run_reentrant(df);
// wait for pending datasets to load
if (df._pending) {
await df._pending;
}
// invoke prerun function, if provided
if (prerun) await asyncCallback(df, prerun);
// exit early if there are no updates
if (!df._touched.length) {
df.info('Dataflow invoked, but nothing to do.');
return df;
}
// increment timestamp clock
let stamp = ++df._clock,
count = 0, op, next, dt, error;
// set the current pulse
df._pulse = new Pulse_Pulse(df, stamp, encode);
if (level >= vega_util["c" /* Info */]) {
dt = Date.now();
df.debug('-- START PROPAGATION (' + stamp + ') -----');
}
// initialize priority queue, reset touched operators
df._touched.forEach(op => df._enqueue(op, true));
df._touched = UniqueList_UniqueList(vega_util["w" /* id */]);
try {
while (df._heap.size() > 0) {
// dequeue operator with highest priority
op = df._heap.pop();
// re-queue if rank changed
if (op.rank !== op.qrank) { df._enqueue(op, true); continue; }
// otherwise, evaluate the operator
next = op.run(df._getPulse(op, encode));
if (next.then) {
// await if operator returns a promise directly
next = await next;
} else if (next.async) {
// queue parallel asynchronous execution
async.push(next.async);
next = Pulse_StopPropagation;
}
if (level >= vega_util["a" /* Debug */]) {
df.debug(op.id, next === Pulse_StopPropagation ? 'STOP' : next, op);
}
// propagate evaluation, enqueue dependent operators
if (next !== Pulse_StopPropagation) {
if (op._targets) op._targets.forEach(op => df._enqueue(op));
}
// increment visit counter
++count;
}
} catch (err) {
df._heap.clear();
error = err;
}
// reset pulse map
df._input = {};
df._pulse = null;
if (level >= vega_util["c" /* Info */]) {
dt = Date.now() - dt;
df.info('> Pulse ' + stamp + ': ' + count + ' operators; ' + dt + 'ms');
}
if (error) {
df._postrun = [];
df.error(error);
}
// invoke callbacks queued via runAfter
if (df._postrun.length) {
const pr = df._postrun.sort((a, b) => b.priority - a.priority);
df._postrun = [];
for (let i=0; i<pr.length; ++i) {
await asyncCallback(df, pr[i].callback);
}
}
// invoke postrun function, if provided
if (postrun) await asyncCallback(df, postrun);
// handle non-blocking asynchronous callbacks
if (async.length) {
Promise.all(async).then(cb => df.runAsync(null, () => {
cb.forEach(f => { try { f(df); } catch (err) { df.error(err); } });
}));
}
return df;
}
/**
* Queues dataflow evaluation to run once any other queued evaluations have
* completed and returns a Promise that resolves when the queued pulse
* propagation completes. If provided, a callback function will be invoked
* immediately before evaluation commences. This method will ensure a
* separate evaluation is invoked for each time it is called.
* @param {string} [encode] - The name of an encoding set to invoke during
* propagation. This value is added to generated Pulse instances;
* operators can then respond to (or ignore) this setting as appropriate.
* This parameter can be used in conjunction with the Encode transform in
* the vega-encode package.
* @param {function} [prerun] - An optional callback function to invoke
* immediately before dataflow evaluation commences.
* @param {function} [postrun] - An optional callback function to invoke
* after dataflow evaluation completes. The callback will be invoked
* after those registered via {@link runAfter}.
* @return {Promise} - A promise that resolves to this dataflow after
* evaluation completes.
*/
async function run_runAsync(encode, prerun, postrun) {
// await previously queued functions
while (this._running) await this._running;
// run dataflow, manage running promise
const clear = () => this._running = null;
(this._running = this.evaluate(encode, prerun, postrun))
.then(clear, clear);
return this._running;
}
/**
* Requests dataflow evaluation and the immediately returns this dataflow
* instance. If there are pending data loading or other asynchronous
* operations, the dataflow will evaluate asynchronously after this method
* has been invoked. To track when dataflow evaluation completes, use the
* {@link runAsync} method instead. This method will raise an error if
* invoked while the dataflow is already in the midst of evaluation.
* @param {string} [encode] - The name of an encoding set to invoke during
* propagation. This value is added to generated Pulse instances;
* operators can then respond to (or ignore) this setting as appropriate.
* This parameter can be used in conjunction with the Encode transform in
* the vega-encode module.
* @param {function} [prerun] - An optional callback function to invoke
* immediately before dataflow evaluation commences.
* @param {function} [postrun] - An optional callback function to invoke
* after dataflow evaluation completes. The callback will be invoked
* after those registered via {@link runAfter}.
* @return {Dataflow} - This dataflow instance.
*/
function run_run(encode, prerun, postrun) {
return this._pulse ? run_reentrant(this)
: (this.evaluate(encode, prerun, postrun), this);
}
/**
* Schedules a callback function to be invoked after the current pulse
* propagation completes. If no propagation is currently occurring,
* the function is invoked immediately. Callbacks scheduled via runAfter
* are invoked immediately upon completion of the current cycle, before
* any request queued via runAsync. This method is primarily intended for
* internal use. Third-party callers using runAfter to schedule a callback
* that invokes {@link run} or {@link runAsync} should not use this method,
* but instead use {@link runAsync} with prerun or postrun arguments.
* @param {function(Dataflow)} callback - The callback function to run.
* The callback will be invoked with this Dataflow instance as its
* sole argument.
* @param {boolean} enqueue - A boolean flag indicating that the
* callback should be queued up to run after the next propagation
* cycle, suppressing immediate invocation when propagation is not
* currently occurring.
* @param {number} [priority] - A priority value used to sort registered
* callbacks to determine execution order. This argument is intended
* for internal Vega use only.
*/
function run_runAfter(callback, enqueue, priority) {
if (this._pulse || enqueue) {
// pulse propagation is currently running, queue to run after
this._postrun.push({
priority: priority || 0,
callback: callback
});
} else {
// pulse propagation already complete, invoke immediately
try { callback(this); } catch (err) { this.error(err); }
}
}
/**
* Raise an error for re-entrant dataflow evaluation.
*/
function run_reentrant(df) {
df.error('Dataflow already running. Use runAsync() to chain invocations.');
return df;
}
/**
* Enqueue an operator into the priority queue for evaluation. The operator
* will be enqueued if it has no registered pulse for the current cycle, or if
* the force argument is true. Upon enqueue, this method also sets the
* operator's qrank to the current rank value.
* @param {Operator} op - The operator to enqueue.
* @param {boolean} [force] - A flag indicating if the operator should be
* forceably added to the queue, even if it has already been previously
* enqueued during the current pulse propagation. This is useful when the
* dataflow graph is dynamically modified and the operator rank changes.
*/
function run_enqueue(op, force) {
var q = op.stamp < this._clock;
if (q) op.stamp = this._clock;
if (q || force) {
op.qrank = op.rank;
this._heap.push(op);
}
}
/**
* Provide a correct pulse for evaluating an operator. If the operator has an
* explicit source operator, we will try to pull the pulse(s) from it.
* If there is an array of source operators, we build a multi-pulse.
* Otherwise, we return a current pulse with correct source data.
* If the pulse is the pulse map has an explicit target set, we use that.
* Else if the pulse on the upstream source operator is current, we use that.
* Else we use the pulse from the pulse map, but copy the source tuple array.
* @param {Operator} op - The operator for which to get an input pulse.
* @param {string} [encode] - An (optional) encoding set name with which to
* annotate the returned pulse. See {@link run} for more information.
*/
function run_getPulse(op, encode) {
var s = op.source,
stamp = this._clock;
return s && Object(vega_util["A" /* isArray */])(s)
? new MultiPulse_MultiPulse(this, stamp, s.map(_ => _.pulse), encode)
: this._input[op.id] || run_singlePulse(this._pulse, s && s.pulse);
}
function run_singlePulse(p, s) {
if (s && s.stamp === p.stamp) {
return s;
}
p = p.fork();
if (s && s !== Pulse_StopPropagation) {
p.source = s.source;
}
return p;
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/update.js
var update_NO_OPT = {skip: false, force: false};
/**
* Touches an operator, scheduling it to be evaluated. If invoked outside of
* a pulse propagation, the operator will be evaluated the next time this
* dataflow is run. If invoked in the midst of pulse propagation, the operator
* will be queued for evaluation if and only if the operator has not yet been
* evaluated on the current propagation timestamp.
* @param {Operator} op - The operator to touch.
* @param {object} [options] - Additional options hash.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @return {Dataflow}
*/
function update_touch(op, options) {
var opt = options || update_NO_OPT;
if (this._pulse) {
// if in midst of propagation, add to priority queue
this._enqueue(op);
} else {
// otherwise, queue for next propagation
this._touched.add(op);
}
if (opt.skip) op.skip(true);
return this;
}
/**
* Updates the value of the given operator.
* @param {Operator} op - The operator to update.
* @param {*} value - The value to set.
* @param {object} [options] - Additional options hash.
* @param {boolean} [options.force] - If true, the operator will
* be re-evaluated even if its value has not changed.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @return {Dataflow}
*/
function update_update(op, value, options) {
var opt = options || update_NO_OPT;
if (op.set(value) || opt.force) {
this.touch(op, opt);
}
return this;
}
/**
* Pulses an operator with a changeset of tuples. If invoked outside of
* a pulse propagation, the pulse will be applied the next time this
* dataflow is run. If invoked in the midst of pulse propagation, the pulse
* will be added to the set of active pulses and will be applied if and
* only if the target operator has not yet been evaluated on the current
* propagation timestamp.
* @param {Operator} op - The operator to pulse.
* @param {ChangeSet} value - The tuple changeset to apply.
* @param {object} [options] - Additional options hash.
* @param {boolean} [options.skip] - If true, the operator will
* be skipped: it will not be evaluated, but its dependents will be.
* @return {Dataflow}
*/
function update_pulse(op, changeset, options) {
this.touch(op, options || update_NO_OPT);
var p = new Pulse_Pulse(this, this._clock + (this._pulse ? 0 : 1)),
t = op.pulse && op.pulse.source || [];
p.target = op;
this._input[op.id] = changeset.pulse(p, t);
return this;
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/util/Heap.js
function Heap(cmp) {
var nodes = [];
return {
clear: () => nodes = [],
size: () => nodes.length,
peek: () => nodes[0],
push: x => {
nodes.push(x);
return siftdown(nodes, 0, nodes.length - 1, cmp);
},
pop: () => {
var last = nodes.pop(), item;
if (nodes.length) {
item = nodes[0];
nodes[0] = last;
siftup(nodes, 0, cmp);
} else {
item = last;
}
return item;
}
};
}
function siftdown(array, start, idx, cmp) {
var item, parent, pidx;
item = array[idx];
while (idx > start) {
pidx = (idx - 1) >> 1;
parent = array[pidx];
if (cmp(item, parent) < 0) {
array[idx] = parent;
idx = pidx;
continue;
}
break;
}
return (array[idx] = item);
}
function siftup(array, idx, cmp) {
var start = idx,
end = array.length,
item = array[idx],
cidx = (idx << 1) + 1, ridx;
while (cidx < end) {
ridx = cidx + 1;
if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) {
cidx = ridx;
}
array[idx] = array[cidx];
idx = cidx;
cidx = (idx << 1) + 1;
}
array[idx] = item;
return siftdown(array, start, idx, cmp);
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/dataflow/Dataflow.js
/**
* A dataflow graph for reactive processing of data streams.
* @constructor
*/
function Dataflow_Dataflow() {
this.logger(Object(vega_util["K" /* logger */])());
this.logLevel(vega_util["b" /* Error */]);
this._clock = 0;
this._rank = 0;
try {
this._loader = index_browser_loader();
} catch (e) {
// do nothing if loader module is unavailable
}
this._touched = UniqueList_UniqueList(vega_util["w" /* id */]);
this._input = {};
this._pulse = null;
this._heap = Heap((a, b) => a.qrank - b.qrank);
this._postrun = [];
}
var Dataflow_prototype = Dataflow_Dataflow.prototype;
/**
* The current timestamp of this dataflow. This value reflects the
* timestamp of the previous dataflow run. The dataflow is initialized
* with a stamp value of 0. The initial run of the dataflow will have
* a timestap of 1, and so on. This value will match the
* {@link Pulse.stamp} property.
* @return {number} - The current timestamp value.
*/
Dataflow_prototype.stamp = function() {
return this._clock;
};
/**
* Gets or sets the loader instance to use for data file loading. A
* loader object must provide a "load" method for loading files and a
* "sanitize" method for checking URL/filename validity. Both methods
* should accept a URI and options hash as arguments, and return a Promise
* that resolves to the loaded file contents (load) or a hash containing
* sanitized URI data with the sanitized url assigned to the "href" property
* (sanitize).
* @param {object} _ - The loader instance to use.
* @return {object|Dataflow} - If no arguments are provided, returns
* the current loader instance. Otherwise returns this Dataflow instance.
*/
Dataflow_prototype.loader = function(_) {
if (arguments.length) {
this._loader = _;
return this;
} else {
return this._loader;
}
};
/**
* Empty entry threshold for garbage cleaning. Map data structures will
* perform cleaning once the number of empty entries exceeds this value.
*/
Dataflow_prototype.cleanThreshold = 1e4;
// OPERATOR REGISTRATION
Dataflow_prototype.add = dataflow_add;
Dataflow_prototype.connect = connect;
Dataflow_prototype.rank = rank_rank;
Dataflow_prototype.rerank = rank_rerank;
// OPERATOR UPDATES
Dataflow_prototype.pulse = update_pulse;
Dataflow_prototype.touch = update_touch;
Dataflow_prototype.update = update_update;
Dataflow_prototype.changeset = ChangeSet_changeset;
// DATA LOADING
Dataflow_prototype.ingest = load_ingest;
Dataflow_prototype.parse = load_parse;
Dataflow_prototype.preload = load_preload;
Dataflow_prototype.request = load_request;
// EVENT HANDLING
Dataflow_prototype.events = dataflow_events;
Dataflow_prototype.on = dataflow_on;
// PULSE PROPAGATION
Dataflow_prototype.evaluate = run_evaluate;
Dataflow_prototype.run = run_run;
Dataflow_prototype.runAsync = run_runAsync;
Dataflow_prototype.runAfter = run_runAfter;
Dataflow_prototype._enqueue = run_enqueue;
Dataflow_prototype._getPulse = run_getPulse;
// LOGGING AND ERROR HANDLING
function Dataflow_logMethod(method) {
return function() {
return this._log[method].apply(this, arguments);
};
}
/**
* Get or set the logger instance used to log messages. If no arguments are
* provided, returns the current logger instance. Otherwise, sets the logger
* and return this Dataflow instance. Provided loggers must support the full
* API of logger objects generated by the vega-util logger method. Note that
* by default the log level of the new logger will be used; use the logLevel
* method to adjust the log level as needed.
*/
Dataflow_prototype.logger = function(logger) {
if (arguments.length) {
this._log = logger;
return this;
} else {
return this._log;
}
};
/**
* Logs an error message. By default, logged messages are written to console
* output. The message will only be logged if the current log level is high
* enough to permit error messages.
*/
Dataflow_prototype.error = Dataflow_logMethod('error');
/**
* Logs a warning message. By default, logged messages are written to console
* output. The message will only be logged if the current log level is high
* enough to permit warning messages.
*/
Dataflow_prototype.warn = Dataflow_logMethod('warn');
/**
* Logs a information message. By default, logged messages are written to
* console output. The message will only be logged if the current log level is
* high enough to permit information messages.
*/
Dataflow_prototype.info = Dataflow_logMethod('info');
/**
* Logs a debug message. By default, logged messages are written to console
* output. The message will only be logged if the current log level is high
* enough to permit debug messages.
*/
Dataflow_prototype.debug = Dataflow_logMethod('debug');
/**
* Get or set the current log level. If an argument is provided, it
* will be used as the new log level.
* @param {number} [level] - Should be one of None, Warn, Info
* @return {number} - The current log level.
*/
Dataflow_prototype.logLevel = Dataflow_logMethod('level');
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/Transform.js
/**
* Abstract class for operators that process data tuples.
* Subclasses must provide a {@link transform} method for operator processing.
* @constructor
* @param {*} [init] - The initial value for this operator.
* @param {object} [params] - The parameters for this operator.
* @param {Operator} [source] - The operator from which to receive pulses.
*/
function Transform_Transform(init, params) {
Operator_Operator.call(this, init, null, params);
}
var Transform_prototype = Object(vega_util["y" /* inherits */])(Transform_Transform, Operator_Operator);
/**
* Overrides {@link Operator.evaluate} for transform operators.
* Internally, this method calls {@link evaluate} to perform processing.
* If {@link evaluate} returns a falsy value, the input pulse is returned.
* This method should NOT be overridden, instead overrride {@link evaluate}.
* @param {Pulse} pulse - the current dataflow pulse.
* @return the output pulse for this operator (or StopPropagation)
*/
Transform_prototype.run = function(pulse) {
if (pulse.stamp < this.stamp) return pulse.StopPropagation;
var rv;
if (this.skip()) {
this.skip(false);
} else {
rv = this.evaluate(pulse);
}
rv = rv || pulse;
if (rv.then) {
rv = rv.then(_ => this.pulse =_);
} else if (rv !== pulse.StopPropagation) {
this.pulse = rv;
}
return rv;
};
/**
* Overrides {@link Operator.evaluate} for transform operators.
* Marshalls parameter values and then invokes {@link transform}.
* @param {Pulse} pulse - the current dataflow pulse.
* @return {Pulse} The output pulse (or StopPropagation). A falsy return
value (including undefined) will let the input pulse pass through.
*/
Transform_prototype.evaluate = function(pulse) {
var params = this.marshall(pulse.stamp),
out = this.transform(params, pulse);
params.clear();
return out;
};
/**
* Process incoming pulses.
* Subclasses should override this method to implement transforms.
* @param {Parameters} _ - The operator parameter values.
* @param {Pulse} pulse - The current dataflow pulse.
* @return {Pulse} The output pulse (or StopPropagation). A falsy return
* value (including undefined) will let the input pulse pass through.
*/
Transform_prototype.transform = function() {};
// CONCATENATED MODULE: ./node_modules/vega-dataflow/src/register.js
var register_transforms = {};
function register_definition(type) {
var t = register_transform(type);
return t && t.Definition || null;
}
function register_transform(type) {
type = type && type.toLowerCase();
return Object(vega_util["v" /* hasOwnProperty */])(register_transforms, type) ? register_transforms[type] : null;
}
// CONCATENATED MODULE: ./node_modules/vega-dataflow/index.js
// Utilities
// Core Runtime
// Tuple Methods
// Transform Registry
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/AggregateKeys.js
function multikey(f) {
return function(x) {
var n = f.length,
i = 1,
k = String(f[0](x));
for (; i<n; ++i) {
k += '|' + f[i](x);
}
return k;
};
}
function groupkey(fields) {
return !fields || !fields.length ? function() { return ''; }
: fields.length === 1 ? fields[0]
: multikey(fields);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/AggregateOps.js
function AggregateOps_measureName(op, field, as) {
return as || (op + (!field ? '' : '_' + field));
}
var AggregateOps_AggregateOps = {
'values': AggregateOps_measure({
name: 'values',
init: 'cell.store = true;',
set: 'cell.data.values()', idx: -1
}),
'count': AggregateOps_measure({
name: 'count',
set: 'cell.num'
}),
'__count__': AggregateOps_measure({
name: 'count',
set: 'this.missing + this.valid'
}),
'missing': AggregateOps_measure({
name: 'missing',
set: 'this.missing'
}),
'valid': AggregateOps_measure({
name: 'valid',
set: 'this.valid'
}),
'sum': AggregateOps_measure({
name: 'sum',
init: 'this.sum = 0;',
add: 'this.sum += +v;',
rem: 'this.sum -= v;',
set: 'this.sum'
}),
'product': AggregateOps_measure({
name: 'product',
init: 'this.product = 1;',
add: 'this.product *= v;',
rem: 'this.product /= v;',
set: 'this.valid ? this.product : undefined'
}),
'mean': AggregateOps_measure({
name: 'mean',
init: 'this.mean = 0;',
add: 'var d = v - this.mean; this.mean += d / this.valid;',
rem: 'var d = v - this.mean; this.mean -= this.valid ? d / this.valid : this.mean;',
set: 'this.valid ? this.mean : undefined'
}),
'average': AggregateOps_measure({
name: 'average',
set: 'this.valid ? this.mean : undefined',
req: ['mean'], idx: 1
}),
'variance': AggregateOps_measure({
name: 'variance',
init: 'this.dev = 0;',
add: 'this.dev += d * (v - this.mean);',
rem: 'this.dev -= d * (v - this.mean);',
set: 'this.valid > 1 ? this.dev / (this.valid-1) : undefined',
req: ['mean'], idx: 1
}),
'variancep': AggregateOps_measure({
name: 'variancep',
set: 'this.valid > 1 ? this.dev / this.valid : undefined',
req: ['variance'], idx: 2
}),
'stdev': AggregateOps_measure({
name: 'stdev',
set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid-1)) : undefined',
req: ['variance'], idx: 2
}),
'stdevp': AggregateOps_measure({
name: 'stdevp',
set: 'this.valid > 1 ? Math.sqrt(this.dev / this.valid) : undefined',
req: ['variance'], idx: 2
}),
'stderr': AggregateOps_measure({
name: 'stderr',
set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid * (this.valid-1))) : undefined',
req: ['variance'], idx: 2
}),
'distinct': AggregateOps_measure({
name: 'distinct',
set: 'cell.data.distinct(this.get)',
req: ['values'], idx: 3
}),
'ci0': AggregateOps_measure({
name: 'ci0',
set: 'cell.data.ci0(this.get)',
req: ['values'], idx: 3
}),
'ci1': AggregateOps_measure({
name: 'ci1',
set: 'cell.data.ci1(this.get)',
req: ['values'], idx: 3
}),
'median': AggregateOps_measure({
name: 'median',
set: 'cell.data.q2(this.get)',
req: ['values'], idx: 3
}),
'q1': AggregateOps_measure({
name: 'q1',
set: 'cell.data.q1(this.get)',
req: ['values'], idx: 3
}),
'q3': AggregateOps_measure({
name: 'q3',
set: 'cell.data.q3(this.get)',
req: ['values'], idx: 3
}),
'argmin': AggregateOps_measure({
name: 'argmin',
init: 'this.argmin = undefined;',
add: 'if (v < this.min) this.argmin = t;',
rem: 'if (v <= this.min) this.argmin = undefined;',
set: 'this.argmin || cell.data.argmin(this.get)',
req: ['min'], str: ['values'], idx: 3
}),
'argmax': AggregateOps_measure({
name: 'argmax',
init: 'this.argmax = undefined;',
add: 'if (v > this.max) this.argmax = t;',
rem: 'if (v >= this.max) this.argmax = undefined;',
set: 'this.argmax || cell.data.argmax(this.get)',
req: ['max'], str: ['values'], idx: 3
}),
'min': AggregateOps_measure({
name: 'min',
init: 'this.min = undefined;',
add: 'if (v < this.min || this.min === undefined) this.min = v;',
rem: 'if (v <= this.min) this.min = NaN;',
set: 'this.min = (Number.isNaN(this.min) ? cell.data.min(this.get) : this.min)',
str: ['values'], idx: 4
}),
'max': AggregateOps_measure({
name: 'max',
init: 'this.max = undefined;',
add: 'if (v > this.max || this.max === undefined) this.max = v;',
rem: 'if (v >= this.max) this.max = NaN;',
set: 'this.max = (Number.isNaN(this.max) ? cell.data.max(this.get) : this.max)',
str: ['values'], idx: 4
})
};
var AggregateOps_ValidAggregateOps = Object.keys(AggregateOps_AggregateOps);
function AggregateOps_createMeasure(op, name) {
return AggregateOps_AggregateOps[op](name);
}
function AggregateOps_measure(base) {
return function(out) {
var m = Object(vega_util["o" /* extend */])({init:'', add:'', rem:'', idx:0}, base);
m.out = out || base.name;
return m;
};
}
function AggregateOps_compareIndex(a, b) {
return a.idx - b.idx;
}
function AggregateOps_resolve(agg, stream) {
function collect(m, a) {
function helper(r) { if (!m[r]) collect(m, m[r] = AggregateOps_AggregateOps[r]()); }
if (a.req) a.req.forEach(helper);
if (stream && a.str) a.str.forEach(helper);
return m;
}
var map = agg.reduce(
collect,
agg.reduce(function(m, a) {
m[a.name] = a;
return m;
}, {})
);
var values = [], key;
for (key in map) values.push(map[key]);
return values.sort(AggregateOps_compareIndex);
}
function AggregateOps_compileMeasures(agg, field) {
var get = field || vega_util["x" /* identity */],
all = AggregateOps_resolve(agg, true), // assume streaming removes may occur
init = 'var cell = this.cell; this.valid = 0; this.missing = 0;',
ctr = 'this.cell = cell; this.init();',
add = 'if(v==null){++this.missing; return;} if(v!==v) return; ++this.valid;',
rem = 'if(v==null){--this.missing; return;} if(v!==v) return; --this.valid;',
set = 'var cell = this.cell;';
all.forEach(function(a) {
init += a.init;
add += a.add;
rem += a.rem;
});
agg.slice().sort(AggregateOps_compareIndex).forEach(function(a) {
set += 't[' + Object(vega_util["Z" /* stringValue */])(a.out) + ']=' + a.set + ';';
});
set += 'return t;';
ctr = Function('cell', ctr);
ctr.prototype.init = Function(init);
ctr.prototype.add = Function('v', 't', add);
ctr.prototype.rem = Function('v', 't', rem);
ctr.prototype.set = Function('t', set);
ctr.prototype.get = get;
ctr.fields = agg.map(function(_) { return _.out; });
return ctr;
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/numbers.js
/* harmony default export */ var src_numbers = (function*(values, valueof) {
if (valueof === undefined) {
for (let value of values) {
if (value != null && (value = +value) >= value) {
yield value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
yield value;
}
}
}
});
// CONCATENATED MODULE: ./node_modules/d3-array/src/ascending.js
/* harmony default export */ var src_ascending = (function(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
});
// CONCATENATED MODULE: ./node_modules/d3-array/src/max.js
function max_max(values, valueof) {
let max;
if (valueof === undefined) {
for (const value of values) {
if (value != null
&& (max < value || (max === undefined && value >= value))) {
max = value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null
&& (max < value || (max === undefined && value >= value))) {
max = value;
}
}
}
return max;
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/min.js
function min_min(values, valueof) {
let min;
if (valueof === undefined) {
for (const value of values) {
if (value != null
&& (min > value || (min === undefined && value >= value))) {
min = value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null
&& (min > value || (min === undefined && value >= value))) {
min = value;
}
}
}
return min;
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/quickselect.js
// Based on https://github.com/mourner/quickselect
// ISC license, Copyright 2018 Vladimir Agafonkin.
function quickselect_quickselect(array, k, left = 0, right = array.length - 1, compare = src_ascending) {
while (right > left) {
if (right - left > 600) {
const n = right - left + 1;
const m = k - left + 1;
const z = Math.log(n);
const s = 0.5 * Math.exp(2 * z / 3);
const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
quickselect_quickselect(array, k, newLeft, newRight, compare);
}
const t = array[k];
let i = left;
let j = right;
quickselect_swap(array, left, k);
if (compare(array[right], t) > 0) quickselect_swap(array, left, right);
while (i < j) {
quickselect_swap(array, i, j), ++i, --j;
while (compare(array[i], t) < 0) ++i;
while (compare(array[j], t) > 0) --j;
}
if (compare(array[left], t) === 0) quickselect_swap(array, left, j);
else ++j, quickselect_swap(array, j, right);
if (j <= k) left = j + 1;
if (k <= j) right = j - 1;
}
return array;
}
function quickselect_swap(array, i, j) {
const t = array[i];
array[i] = array[j];
array[j] = t;
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/number.js
/* harmony default export */ var src_number = (function(x) {
return x === null ? NaN : +x;
});
function* number_numbers(values, valueof) {
if (valueof === undefined) {
for (let value of values) {
if (value != null && (value = +value) >= value) {
yield value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
yield value;
}
}
}
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/quantile.js
function quantile_quantile(values, p, valueof) {
values = Float64Array.from(number_numbers(values, valueof));
if (!(n = values.length)) return;
if ((p = +p) <= 0 || n < 2) return min_min(values);
if (p >= 1) return max_max(values);
var n,
i = (n - 1) * p,
i0 = Math.floor(i),
value0 = max_max(quickselect_quickselect(values, i0).subarray(0, i0 + 1)),
value1 = min_min(values.subarray(i0 + 1));
return value0 + (value1 - value0) * (i - i0);
}
function quantile_quantileSorted(values, p, valueof = src_number) {
if (!(n = values.length)) return;
if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
if (p >= 1) return +valueof(values[n - 1], n - 1, values);
var n,
i = (n - 1) * p,
i0 = Math.floor(i),
value0 = +valueof(values[i0], i0, values),
value1 = +valueof(values[i0 + 1], i0 + 1, values);
return value0 + (value1 - value0) * (i - i0);
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/quantiles.js
/* harmony default export */ var quantiles = (function(array, p, f) {
var values = Float64Array.from(src_numbers(array, f));
// don't depend on return value from typed array sort call
// protects against undefined sort results in Safari (vega/vega-lite#4964)
values.sort(src_ascending);
return p.map(_ => quantile_quantileSorted(values, _));
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/quartiles.js
/* harmony default export */ var quartiles = (function(array, f) {
return quantiles(array, [0.25, 0.50, 0.75], f);
});
// CONCATENATED MODULE: ./node_modules/d3-array/src/variance.js
function variance(values, valueof) {
let count = 0;
let delta;
let mean = 0;
let sum = 0;
if (valueof === undefined) {
for (let value of values) {
if (value != null && (value = +value) >= value) {
delta = value - mean;
mean += delta / ++count;
sum += delta * (value - mean);
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
delta = value - mean;
mean += delta / ++count;
sum += delta * (value - mean);
}
}
}
if (count > 1) return sum / (count - 1);
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/deviation.js
function deviation_deviation(values, valueof) {
const v = variance(values, valueof);
return v ? Math.sqrt(v) : v;
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/bandwidth.js
// Scott, D. W. (1992) Multivariate Density Estimation:
// Theory, Practice, and Visualization. Wiley.
/* harmony default export */ var src_bandwidth = (function(array, f) {
var n = array.length,
v = deviation_deviation(array, f),
q = quartiles(array, f),
h = (q[2] - q[0]) / 1.34;
v = Math.min(v, h) || v || Math.abs(q[0]) || 1;
return 1.06 * v * Math.pow(n, -0.2);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/bin.js
/* harmony default export */ var src_bin = (function(_) {
// determine range
var maxb = _.maxbins || 20,
base = _.base || 10,
logb = Math.log(base),
div = _.divide || [5, 2],
min = _.extent[0],
max = _.extent[1],
span = _.span || (max - min) || Math.abs(min) || 1,
step, level, minstep, precision, v, i, n, eps;
if (_.step) {
// if step size is explicitly given, use that
step = _.step;
} else if (_.steps) {
// if provided, limit choice to acceptable step sizes
v = span / maxb;
for (i=0, n=_.steps.length; i < n && _.steps[i] < v; ++i);
step = _.steps[Math.max(0, i-1)];
} else {
// else use span to determine step size
level = Math.ceil(Math.log(maxb) / logb);
minstep = _.minstep || 0;
step = Math.max(
minstep,
Math.pow(base, Math.round(Math.log(span) / logb) - level)
);
// increase step size if too many bins
while (Math.ceil(span/step) > maxb) { step *= base; }
// decrease step size if allowed
for (i=0, n=div.length; i<n; ++i) {
v = step / div[i];
if (v >= minstep && span / v <= maxb) step = v;
}
}
// update precision, min and max
v = Math.log(step);
precision = v >= 0 ? 0 : ~~(-v / logb) + 1;
eps = Math.pow(base, -precision - 1);
if (_.nice || _.nice === undefined) {
v = Math.floor(min / step + eps) * step;
min = min < v ? v - step : v;
max = Math.ceil(max / step) * step;
}
return {
start: min,
stop: max === min ? min + step : max,
step: step
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/random.js
var random_random = Math.random;
function setRandom(r) {
random_random = r;
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/bootstrapCI.js
/* harmony default export */ var bootstrapCI = (function(array, samples, alpha, f) {
if (!array.length) return [undefined, undefined];
var values = Float64Array.from(src_numbers(array, f)),
n = values.length,
m = samples,
a, i, j, mu;
for (j=0, mu=Array(m); j<m; ++j) {
for (a=0, i=0; i<n; ++i) {
a += values[~~(random_random() * n)];
}
mu[j] = a / n;
}
mu.sort(src_ascending);
return [
quantile_quantile(mu, alpha/2),
quantile_quantile(mu, 1-(alpha/2))
];
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/dotbin.js
// Dot density binning for dot plot construction.
// Based on Leland Wilkinson, Dot Plots, The American Statistician, 1999.
// https://www.cs.uic.edu/~wilkinson/Publications/dotplots.pdf
/* harmony default export */ var dotbin = (function(array, step, smooth, f) {
f = f || (_ => _);
let i = 0, j = 1,
n = array.length,
v = new Float64Array(n),
a = f(array[0]),
b = a,
w = a + step,
x;
for (; j<n; ++j) {
x = f(array[j]);
if (x >= w) {
b = (a + b) / 2;
for (; i<j; ++i) v[i] = b;
w = x + step;
a = x;
}
b = x;
}
b = (a + b) / 2;
for (; i<j; ++i) v[i] = b;
return smooth ? smoothing(v, step + step / 4) : v;
});
// perform smoothing to reduce variance
// swap points between "adjacent" stacks
// Wilkinson defines adjacent as within step/4 units
function smoothing(v, thresh) {
let n = v.length,
a = 0,
b = 1,
c, d;
// get left stack
while (v[a] === v[b]) ++b;
while (b < n) {
// get right stack
c = b + 1;
while (v[b] === v[c]) ++c;
// are stacks adjacent?
// if so, compare sizes and swap as needed
if (v[b] - v[b-1] < thresh) {
d = b + ((a + c - b - b) >> 1);
while (d < b) v[d++] = v[b];
while (d > b) v[d--] = v[a];
}
// update left stack indices
a = b;
b = c;
}
return v;
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/lcg.js
/* harmony default export */ var lcg = (function(seed) {
// Random numbers using a Linear Congruential Generator with seed value
// Uses glibc values from https://en.wikipedia.org/wiki/Linear_congruential_generator
return function() {
seed = (1103515245 * seed + 12345) % 2147483647;
return seed / 2147483647;
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/integer.js
/* harmony default export */ var integer = (function(min, max) {
if (max == null) {
max = min;
min = 0;
}
var dist = {},
a, b, d;
dist.min = function(_) {
if (arguments.length) {
a = _ || 0;
d = b - a;
return dist;
} else {
return a;
}
};
dist.max = function(_) {
if (arguments.length) {
b = _ || 0;
d = b - a;
return dist;
} else {
return b;
}
};
dist.sample = function() {
return a + Math.floor(d * random_random());
};
dist.pdf = function(x) {
return (x === Math.floor(x) && x >= a && x < b) ? 1 / d : 0;
};
dist.cdf = function(x) {
var v = Math.floor(x);
return v < a ? 0 : v >= b ? 1 : (v - a + 1) / d;
};
dist.icdf = function(p) {
return (p >= 0 && p <= 1) ? a - 1 + Math.floor(p * d) : NaN;
};
return dist.min(min).max(max);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/constants.js
const SQRT2PI = Math.sqrt(2 * Math.PI);
const SQRT2 = Math.SQRT2;
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/normal.js
let normal_nextSample = NaN;
function normal_sampleNormal(mean, stdev) {
mean = mean || 0;
stdev = stdev == null ? 1 : stdev;
let x = 0, y = 0, rds, c;
if (normal_nextSample === normal_nextSample) {
x = normal_nextSample;
normal_nextSample = NaN;
} else {
do {
x = random_random() * 2 - 1;
y = random_random() * 2 - 1;
rds = x * x + y * y;
} while (rds === 0 || rds > 1);
c = Math.sqrt(-2 * Math.log(rds) / rds); // Box-Muller transform
x *= c;
normal_nextSample = y * c;
}
return mean + x * stdev;
}
function normal_densityNormal(value, mean, stdev) {
stdev = stdev == null ? 1 : stdev;
const z = (value - (mean || 0)) / stdev;
return Math.exp(-0.5 * z * z) / (stdev * SQRT2PI);
}
// Approximation from West (2009)
// Better Approximations to Cumulative Normal Functions
function normal_cumulativeNormal(value, mean, stdev) {
mean = mean || 0;
stdev = stdev == null ? 1 : stdev;
let cd,
z = (value - mean) / stdev,
Z = Math.abs(z);
if (Z > 37) {
cd = 0;
} else {
let sum, exp = Math.exp(-Z * Z / 2);
if (Z < 7.07106781186547) {
sum = 3.52624965998911e-02 * Z + 0.700383064443688;
sum = sum * Z + 6.37396220353165;
sum = sum * Z + 33.912866078383;
sum = sum * Z + 112.079291497871;
sum = sum * Z + 221.213596169931;
sum = sum * Z + 220.206867912376;
cd = exp * sum;
sum = 8.83883476483184e-02 * Z + 1.75566716318264;
sum = sum * Z + 16.064177579207;
sum = sum * Z + 86.7807322029461;
sum = sum * Z + 296.564248779674;
sum = sum * Z + 637.333633378831;
sum = sum * Z + 793.826512519948;
sum = sum * Z + 440.413735824752;
cd = cd / sum;
} else {
sum = Z + 0.65;
sum = Z + 4 / sum;
sum = Z + 3 / sum;
sum = Z + 2 / sum;
sum = Z + 1 / sum;
cd = exp / sum / 2.506628274631;
}
}
return z > 0 ? 1 - cd : cd;
}
// Approximation of Probit function using inverse error function.
function normal_quantileNormal(p, mean, stdev) {
if (p < 0 || p > 1) return NaN;
return (mean || 0) + (stdev == null ? 1 : stdev) * SQRT2 * normal_erfinv(2 * p - 1);
}
// Approximate inverse error function. Implementation from "Approximating
// the erfinv function" by Mike Giles, GPU Computing Gems, volume 2, 2010.
// Ported from Apache Commons Math, http://www.apache.org/licenses/LICENSE-2.0
function normal_erfinv(x) {
// beware that the logarithm argument must be
// commputed as (1.0 - x) * (1.0 + x),
// it must NOT be simplified as 1.0 - x * x as this
// would induce rounding errors near the boundaries +/-1
let w = - Math.log((1 - x) * (1 + x)), p;
if (w < 6.25) {
w -= 3.125;
p = -3.6444120640178196996e-21;
p = -1.685059138182016589e-19 + p * w;
p = 1.2858480715256400167e-18 + p * w;
p = 1.115787767802518096e-17 + p * w;
p = -1.333171662854620906e-16 + p * w;
p = 2.0972767875968561637e-17 + p * w;
p = 6.6376381343583238325e-15 + p * w;
p = -4.0545662729752068639e-14 + p * w;
p = -8.1519341976054721522e-14 + p * w;
p = 2.6335093153082322977e-12 + p * w;
p = -1.2975133253453532498e-11 + p * w;
p = -5.4154120542946279317e-11 + p * w;
p = 1.051212273321532285e-09 + p * w;
p = -4.1126339803469836976e-09 + p * w;
p = -2.9070369957882005086e-08 + p * w;
p = 4.2347877827932403518e-07 + p * w;
p = -1.3654692000834678645e-06 + p * w;
p = -1.3882523362786468719e-05 + p * w;
p = 0.0001867342080340571352 + p * w;
p = -0.00074070253416626697512 + p * w;
p = -0.0060336708714301490533 + p * w;
p = 0.24015818242558961693 + p * w;
p = 1.6536545626831027356 + p * w;
} else if (w < 16.0) {
w = Math.sqrt(w) - 3.25;
p = 2.2137376921775787049e-09;
p = 9.0756561938885390979e-08 + p * w;
p = -2.7517406297064545428e-07 + p * w;
p = 1.8239629214389227755e-08 + p * w;
p = 1.5027403968909827627e-06 + p * w;
p = -4.013867526981545969e-06 + p * w;
p = 2.9234449089955446044e-06 + p * w;
p = 1.2475304481671778723e-05 + p * w;
p = -4.7318229009055733981e-05 + p * w;
p = 6.8284851459573175448e-05 + p * w;
p = 2.4031110387097893999e-05 + p * w;
p = -0.0003550375203628474796 + p * w;
p = 0.00095328937973738049703 + p * w;
p = -0.0016882755560235047313 + p * w;
p = 0.0024914420961078508066 + p * w;
p = -0.0037512085075692412107 + p * w;
p = 0.005370914553590063617 + p * w;
p = 1.0052589676941592334 + p * w;
p = 3.0838856104922207635 + p * w;
} else if (Number.isFinite(w)) {
w = Math.sqrt(w) - 5.0;
p = -2.7109920616438573243e-11;
p = -2.5556418169965252055e-10 + p * w;
p = 1.5076572693500548083e-09 + p * w;
p = -3.7894654401267369937e-09 + p * w;
p = 7.6157012080783393804e-09 + p * w;
p = -1.4960026627149240478e-08 + p * w;
p = 2.9147953450901080826e-08 + p * w;
p = -6.7711997758452339498e-08 + p * w;
p = 2.2900482228026654717e-07 + p * w;
p = -9.9298272942317002539e-07 + p * w;
p = 4.5260625972231537039e-06 + p * w;
p = -1.9681778105531670567e-05 + p * w;
p = 7.5995277030017761139e-05 + p * w;
p = -0.00021503011930044477347 + p * w;
p = -0.00013871931833623122026 + p * w;
p = 1.0103004648645343977 + p * w;
p = 4.8499064014085844221 + p * w;
} else {
p = Infinity;
}
return p * x;
}
/* harmony default export */ var src_normal = (function(mean, stdev) {
var mu,
sigma,
dist = {
mean: function(_) {
if (arguments.length) {
mu = _ || 0;
return dist;
} else {
return mu;
}
},
stdev: function(_) {
if (arguments.length) {
sigma = _ == null ? 1 : _;
return dist;
} else {
return sigma;
}
},
sample: () => normal_sampleNormal(mu, sigma),
pdf: value => normal_densityNormal(value, mu, sigma),
cdf: value => normal_cumulativeNormal(value, mu, sigma),
icdf: p => normal_quantileNormal(p, mu, sigma)
};
return dist.mean(mean).stdev(stdev);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/kde.js
// TODO: support for additional kernels?
/* harmony default export */ var src_kde = (function(support, bandwidth) {
var kernel = src_normal(),
dist = {},
n = 0;
dist.data = function(_) {
if (arguments.length) {
support = _;
n = _ ? _.length : 0;
return dist.bandwidth(bandwidth);
} else {
return support;
}
};
dist.bandwidth = function(_) {
if (!arguments.length) return bandwidth;
bandwidth = _;
if (!bandwidth && support) bandwidth = src_bandwidth(support);
return dist;
};
dist.sample = function() {
return support[~~(random_random() * n)] + bandwidth * kernel.sample();
};
dist.pdf = function(x) {
for (var y=0, i=0; i<n; ++i) {
y += kernel.pdf((x - support[i]) / bandwidth);
}
return y / bandwidth / n;
};
dist.cdf = function(x) {
for (var y=0, i=0; i<n; ++i) {
y += kernel.cdf((x - support[i]) / bandwidth);
}
return y / n;
};
dist.icdf = function() {
throw Error('KDE icdf not supported.');
};
return dist.data(support);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/lognormal.js
function lognormal_sampleLogNormal(mean, stdev) {
mean = mean || 0;
stdev = stdev == null ? 1 : stdev;
return Math.exp(mean + normal_sampleNormal() * stdev);
}
function lognormal_densityLogNormal(value, mean, stdev) {
if (value <= 0) return 0;
mean = mean || 0;
stdev = stdev == null ? 1 : stdev;
const z = (Math.log(value) - mean) / stdev;
return Math.exp(-0.5 * z * z) / (stdev * SQRT2PI * value);
}
function lognormal_cumulativeLogNormal(value, mean, stdev) {
return normal_cumulativeNormal(Math.log(value), mean, stdev);
}
function lognormal_quantileLogNormal(p, mean, stdev) {
return Math.exp(normal_quantileNormal(p, mean, stdev));
}
/* harmony default export */ var lognormal = (function(mean, stdev) {
var mu,
sigma,
dist = {
mean: function(_) {
if (arguments.length) {
mu = _ || 0;
return dist;
} else {
return mu;
}
},
stdev: function(_) {
if (arguments.length) {
sigma = _ == null ? 1 : _;
return dist;
} else {
return sigma;
}
},
sample: () => lognormal_sampleLogNormal(mu, sigma),
pdf: value => lognormal_densityLogNormal(value, mu, sigma),
cdf: value => lognormal_cumulativeLogNormal(value, mu, sigma),
icdf: p => lognormal_quantileLogNormal(p, mu, sigma)
};
return dist.mean(mean).stdev(stdev);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/mixture.js
/* harmony default export */ var src_mixture = (function(dists, weights) {
var dist = {}, m = 0, w;
function normalize(x) {
var w = [], sum = 0, i;
for (i=0; i<m; ++i) { sum += (w[i] = (x[i]==null ? 1 : +x[i])); }
for (i=0; i<m; ++i) { w[i] /= sum; }
return w;
}
dist.weights = function(_) {
if (arguments.length) {
w = normalize(weights = (_ || []));
return dist;
}
return weights;
};
dist.distributions = function(_) {
if (arguments.length) {
if (_) {
m = _.length;
dists = _;
} else {
m = 0;
dists = [];
}
return dist.weights(weights);
}
return dists;
};
dist.sample = function() {
var r = random_random(),
d = dists[m-1],
v = w[0],
i = 0;
// first select distribution
for (; i<m-1; v += w[++i]) {
if (r < v) { d = dists[i]; break; }
}
// then sample from it
return d.sample();
};
dist.pdf = function(x) {
for (var p=0, i=0; i<m; ++i) {
p += w[i] * dists[i].pdf(x);
}
return p;
};
dist.cdf = function(x) {
for (var p=0, i=0; i<m; ++i) {
p += w[i] * dists[i].cdf(x);
}
return p;
};
dist.icdf = function() {
throw Error('Mixture icdf not supported.');
};
return dist.distributions(dists).weights(weights);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/uniform.js
function uniform_sampleUniform(min, max) {
if (max == null) {
max = (min == null ? 1 : min);
min = 0;
}
return min + (max - min) * random_random();
}
function uniform_densityUniform(value, min, max) {
if (max == null) {
max = (min == null ? 1 : min);
min = 0;
}
return (value >= min && value <= max) ? 1 / (max - min) : 0;
}
function uniform_cumulativeUniform(value, min, max) {
if (max == null) {
max = (min == null ? 1 : min);
min = 0;
}
return value < min ? 0 : value > max ? 1 : (value - min) / (max - min);
}
function uniform_quantileUniform(p, min, max) {
if (max == null) {
max = (min == null ? 1 : min);
min = 0;
}
return (p >= 0 && p <= 1) ? min + p * (max - min) : NaN;
}
/* harmony default export */ var uniform = (function(min, max) {
var a, b,
dist = {
min: function(_) {
if (arguments.length) {
a = _ || 0;
return dist;
} else {
return a;
}
},
max: function(_) {
if (arguments.length) {
b = _ == null ? 1 : _;
return dist;
} else {
return b;
}
},
sample: () => uniform_sampleUniform(a, b),
pdf: value => uniform_densityUniform(value, a, b),
cdf: value => uniform_cumulativeUniform(value, a, b),
icdf: p => uniform_quantileUniform(p, a, b)
};
if (max == null) {
max = (min == null ? 1 : min);
min = 0;
}
return dist.min(min).max(max);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/ols.js
// Ordinary Least Squares
/* harmony default export */ var ols = (function(uX, uY, uXY, uX2) {
const delta = uX2 - uX * uX,
slope = Math.abs(delta) < 1e-24 ? 0 : (uXY - uX * uY) / delta,
intercept = uY - slope * uX;
return [intercept, slope];
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/points.js
function points_points(data, x, y, sort) {
data = data.filter(d => {
let u = x(d), v = y(d);
return u != null && (u = +u) >= u && v != null && (v = +v) >= v;
});
if (sort) {
data.sort((a, b) => x(a) - x(b));
}
const n = data.length,
X = new Float64Array(n),
Y = new Float64Array(n);
// extract values, calculate means
let i = 0, ux = 0, uy = 0, xv, yv, d;
for (d of data) {
X[i] = xv = +x(d);
Y[i] = yv = +y(d);
++i;
ux += (xv - ux) / i;
uy += (yv - uy) / i;
}
// mean center the data
for (i=0; i<n; ++i) {
X[i] -= ux;
Y[i] -= uy;
}
return [X, Y, ux, uy];
}
function visitPoints(data, x, y, callback) {
let i = -1, u, v;
for (let d of data) {
u = x(d);
v = y(d);
if (u != null && (u = +u) >= u && v != null && (v = +v) >= v) {
callback(u, v, ++i);
}
}
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/r-squared.js
// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
/* harmony default export */ var r_squared = (function(data, x, y, uY, predict) {
let SSE = 0, SST = 0;
visitPoints(data, x, y, (dx, dy) => {
const sse = dy - predict(dx),
sst = dy - uY;
SSE += sse * sse;
SST += sst * sst;
});
return 1 - SSE / SST;
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/linear.js
// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
/* harmony default export */ var regression_linear = (function(data, x, y) {
let X = 0, Y = 0, XY = 0, X2 = 0, n = 0;
visitPoints(data, x, y, (dx, dy) => {
++n;
X += (dx - X) / n;
Y += (dy - Y) / n;
XY += (dx * dy - XY) / n;
X2 += (dx * dx - X2) / n;
});
const coef = ols(X, Y, XY, X2),
predict = x => coef[0] + coef[1] * x;
return {
coef: coef,
predict: predict,
rSquared: r_squared(data, x, y, Y, predict)
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/log.js
// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
/* harmony default export */ var regression_log = (function(data, x, y) {
let X = 0, Y = 0, XY = 0, X2 = 0, n = 0;
visitPoints(data, x, y, (dx, dy) => {
++n;
dx = Math.log(dx);
X += (dx - X) / n;
Y += (dy - Y) / n;
XY += (dx * dy - XY) / n;
X2 += (dx * dx - X2) / n;
});
const coef = ols(X, Y, XY, X2),
predict = x => coef[0] + coef[1] * Math.log(x);
return {
coef: coef,
predict: predict,
rSquared: r_squared(data, x, y, Y, predict)
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/exp.js
/* harmony default export */ var regression_exp = (function(data, x, y) {
// eslint-disable-next-line no-unused-vars
const [xv, yv, ux, uy] = points_points(data, x, y);
let YL = 0, XY = 0, XYL = 0, X2Y = 0, n = 0, dx, ly, xy;
visitPoints(data, x, y, (_, dy) => {
dx = xv[n++];
ly = Math.log(dy);
xy = dx * dy;
YL += (dy * ly - YL) / n;
XY += (xy - XY) / n;
XYL += (xy * ly - XYL) / n;
X2Y += (dx * xy - X2Y) / n;
});
const [c0, c1] = ols(XY / uy, YL / uy, XYL / uy, X2Y / uy),
predict = x => Math.exp(c0 + c1 * (x - ux));
return {
coef: [Math.exp(c0 - c1 * ux), c1],
predict: predict,
rSquared: r_squared(data, x, y, uy, predict)
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/pow.js
// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
/* harmony default export */ var regression_pow = (function(data, x, y) {
let X = 0, Y = 0, XY = 0, X2 = 0, YS = 0, n = 0;
visitPoints(data, x, y, (dx, dy) => {
const lx = Math.log(dx),
ly = Math.log(dy);
++n;
X += (lx - X) / n;
Y += (ly - Y) / n;
XY += (lx * ly - XY) / n;
X2 += (lx * lx - X2) / n;
YS += (dy - YS) / n;
});
const coef = ols(X, Y, XY, X2),
predict = x => coef[0] * Math.pow(x, coef[1]);
coef[0] = Math.exp(coef[0]);
return {
coef: coef,
predict: predict,
rSquared: r_squared(data, x, y, YS, predict)
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/quad.js
/* harmony default export */ var regression_quad = (function(data, x, y) {
const [xv, yv, ux, uy] = points_points(data, x, y),
n = xv.length;
let X2 = 0, X3 = 0, X4 = 0, XY = 0, X2Y = 0,
i, dx, dy, x2;
for (i=0; i<n;) {
dx = xv[i];
dy = yv[i++];
x2 = dx * dx;
X2 += (x2 - X2) / i;
X3 += (x2 * dx - X3) / i;
X4 += (x2 * x2 - X4) / i;
XY += (dx * dy - XY) / i;
X2Y += (x2 * dy - X2Y) / i;
}
const X2X2 = X4 - (X2 * X2),
d = (X2 * X2X2 - X3 * X3),
a = (X2Y * X2 - XY * X3) / d,
b = (XY * X2X2 - X2Y * X3) / d,
c = -a * X2,
predict = x => {
x = x - ux;
return a * x * x + b * x + c + uy;
};
// transform coefficients back from mean-centered space
return {
coef: [
c - b * ux + a * ux * ux + uy,
b - 2 * a * ux,
a
],
predict: predict,
rSquared: r_squared(data, x, y, uy, predict)
};
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/poly.js
// Adapted from d3-regression by Harry Stevens
// License: https://github.com/HarryStevens/d3-regression/blob/master/LICENSE
// ... which was adapted from regression-js by Tom Alexander
// Source: https://github.com/Tom-Alexander/regression-js/blob/master/src/regression.js#L246
// License: https://github.com/Tom-Alexander/regression-js/blob/master/LICENSE
/* harmony default export */ var poly = (function(data, x, y, order) {
// use more efficient methods for lower orders
if (order === 1) return regression_linear(data, x, y);
if (order === 2) return regression_quad(data, x, y);
const [xv, yv, ux, uy] = points_points(data, x, y),
n = xv.length,
lhs = [],
rhs = [],
k = order + 1;
let i, j, l, v, c;
for (i=0; i<k; ++i) {
for (l=0, v=0; l<n; ++l) {
v += Math.pow(xv[l], i) * yv[l];
}
lhs.push(v);
c = new Float64Array(k);
for (j=0; j<k; ++j) {
for (l=0, v=0; l<n; ++l) {
v += Math.pow(xv[l], i + j);
}
c[j] = v;
}
rhs.push(c);
}
rhs.push(lhs);
const coef = poly_gaussianElimination(rhs),
predict = x => {
x -= ux;
let y = uy + coef[0] + coef[1] * x + coef[2] * x * x;
for (i=3; i<k; ++i) y += coef[i] * Math.pow(x, i);
return y;
};
return {
coef: poly_uncenter(k, coef, -ux, uy),
predict: predict,
rSquared: r_squared(data, x, y, uy, predict)
};
});
function poly_uncenter(k, a, x, y) {
const z = Array(k);
let i, j, v, c;
// initialize to zero
for (i=0; i<k; ++i) z[i] = 0;
// polynomial expansion
for (i=k-1; i>=0; --i) {
v = a[i];
c = 1;
z[i] += v;
for (j=1; j<=i; ++j) {
c *= (i + 1 - j) / j; // binomial coefficent
z[i-j] += v * Math.pow(x, j) * c;
}
}
// bias term
z[0] += y;
return z;
}
// Given an array for a two-dimensional matrix and the polynomial order,
// solve A * x = b using Gaussian elimination.
function poly_gaussianElimination(matrix) {
const n = matrix.length - 1,
coef = [];
let i, j, k, r, t;
for (i = 0; i < n; ++i) {
r = i; // max row
for (j = i + 1; j < n; ++j) {
if (Math.abs(matrix[i][j]) > Math.abs(matrix[i][r])) {
r = j;
}
}
for (k = i; k < n + 1; ++k) {
t = matrix[k][i];
matrix[k][i] = matrix[k][r];
matrix[k][r] = t;
}
for (j = i + 1; j < n; ++j) {
for (k = n; k >= i; k--) {
matrix[k][j] -= (matrix[k][i] * matrix[i][j]) / matrix[i][i];
}
}
}
for (j = n - 1; j >= 0; --j) {
t = 0;
for (k = j + 1; k < n; ++k) {
t += matrix[k][j] * coef[k];
}
coef[j] = (matrix[n][j] - t) / matrix[j][j];
}
return coef;
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/median.js
/* harmony default export */ var median = (function(values, valueof) {
return quantile_quantile(values, 0.5, valueof);
});
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/regression/loess.js
const loess_maxiters = 2,
loess_epsilon = 1e-12;
// Adapted from science.js by Jason Davies
// Source: https://github.com/jasondavies/science.js/blob/master/src/stats/loess.js
// License: https://github.com/jasondavies/science.js/blob/master/LICENSE
/* harmony default export */ var regression_loess = (function(data, x, y, bandwidth) {
const [xv, yv, ux, uy] = points_points(data, x, y, true),
n = xv.length,
bw = Math.max(2, ~~(bandwidth * n)), // # nearest neighbors
yhat = new Float64Array(n),
residuals = new Float64Array(n),
robustWeights = new Float64Array(n).fill(1);
for (let iter = -1; ++iter <= loess_maxiters; ) {
const interval = [0, bw - 1];
for (let i = 0; i < n; ++i) {
const dx = xv[i],
i0 = interval[0],
i1 = interval[1],
edge = (dx - xv[i0]) > (xv[i1] - dx) ? i0 : i1;
let W = 0, X = 0, Y = 0, XY = 0, X2 = 0,
denom = 1 / Math.abs(xv[edge] - dx || 1); // avoid singularity!
for (let k = i0; k <= i1; ++k) {
const xk = xv[k],
yk = yv[k],
w = loess_tricube(Math.abs(dx - xk) * denom) * robustWeights[k],
xkw = xk * w;
W += w;
X += xkw;
Y += yk * w;
XY += yk * xkw;
X2 += xk * xkw;
}
// linear regression fit
const [a, b] = ols(X / W, Y / W, XY / W, X2 / W);
yhat[i] = a + b * dx;
residuals[i] = Math.abs(yv[i] - yhat[i]);
loess_updateInterval(xv, i + 1, interval);
}
if (iter === loess_maxiters) {
break;
}
const medianResidual = median(residuals);
if (Math.abs(medianResidual) < loess_epsilon) break;
for (let i = 0, arg, w; i < n; ++i){
arg = residuals[i] / (6 * medianResidual);
// default to epsilon (rather than zero) for large deviations
// keeping weights tiny but non-zero prevents singularites
robustWeights[i] = (arg >= 1) ? loess_epsilon : ((w = 1 - arg * arg) * w);
}
}
return loess_output(xv, yhat, ux, uy);
});
// weighting kernel for local regression
function loess_tricube(x) {
return (x = 1 - x * x * x) * x * x;
}
// advance sliding window interval of nearest neighbors
function loess_updateInterval(xv, i, interval) {
let val = xv[i],
left = interval[0],
right = interval[1] + 1;
if (right >= xv.length) return;
// step right if distance to new right edge is <= distance to old left edge
// step when distance is equal to ensure movement over duplicate x values
while (i > left && (xv[right] - val) <= (val - xv[left])) {
interval[0] = ++left;
interval[1] = right;
++right;
}
}
// generate smoothed output points
// average points with repeated x values
function loess_output(xv, yhat, ux, uy) {
const n = xv.length, out = [];
let i = 0, cnt = 0, prev = [], v;
for (; i<n; ++i) {
v = xv[i] + ux;
if (prev[0] === v) {
// average output values via online update
prev[1] += (yhat[i] - prev[1]) / (++cnt);
} else {
// add new output point
cnt = 0;
prev[1] += uy;
prev = [v, yhat[i]];
out.push(prev);
}
}
prev[1] += uy;
return out;
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/src/sampleCurve.js
// subdivide up to accuracy of 0.1 degrees
const MIN_RADIANS = 0.1 * Math.PI / 180;
// Adaptively sample an interpolated function over a domain extent
/* harmony default export */ var sampleCurve = (function(f, extent, minSteps, maxSteps) {
minSteps = minSteps || 25;
maxSteps = Math.max(minSteps, maxSteps || 200);
const point = x => [x, f(x)],
minX = extent[0],
maxX = extent[1],
span = maxX - minX,
stop = span / maxSteps,
prev = [point(minX)],
next = [];
if (minSteps === maxSteps) {
// no adaptation, sample uniform grid directly and return
for (let i = 1; i < maxSteps; ++i) {
prev.push(point(minX + (i / minSteps) * span));
}
prev.push(point(maxX));
return prev;
} else {
// sample minimum points on uniform grid
// then move on to perform adaptive refinement
next.push(point(maxX));
for (let i = minSteps; --i > 0;) {
next.push(point(minX + (i / minSteps) * span));
}
}
let p0 = prev[0],
p1 = next[next.length - 1];
while (p1) {
// midpoint for potential curve subdivision
const pm = point((p0[0] + p1[0]) / 2);
if (pm[0] - p0[0] >= stop && angleDelta(p0, pm, p1) > MIN_RADIANS) {
// maximum resolution has not yet been met, and
// subdivision midpoint sufficiently different from endpoint
// save subdivision, push midpoint onto the visitation stack
next.push(pm);
} else {
// subdivision midpoint sufficiently similar to endpoint
// skip subdivision, store endpoint, move to next point on the stack
p0 = p1;
prev.push(p1);
next.pop();
}
p1 = next[next.length - 1];
}
return prev;
});
function angleDelta(p, q, r) {
const a0 = Math.atan2(r[1] - p[1], r[0] - p[0]),
a1 = Math.atan2(q[1] - p[1], q[0] - p[0]);
return Math.abs(a0 - a1);
}
// CONCATENATED MODULE: ./node_modules/vega-statistics/index.js
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/TupleStore.js
function TupleStore_TupleStore(key) {
this._key = key ? Object(vega_util["t" /* field */])(key) : tupleid;
this.reset();
}
var TupleStore_prototype = TupleStore_TupleStore.prototype;
TupleStore_prototype.reset = function() {
this._add = [];
this._rem = [];
this._ext = null;
this._get = null;
this._q = null;
};
TupleStore_prototype.add = function(v) {
this._add.push(v);
};
TupleStore_prototype.rem = function(v) {
this._rem.push(v);
};
TupleStore_prototype.values = function() {
this._get = null;
if (this._rem.length === 0) return this._add;
var a = this._add,
r = this._rem,
k = this._key,
n = a.length,
m = r.length,
x = Array(n - m),
map = {}, i, j, v;
// use unique key field to clear removed values
for (i=0; i<m; ++i) {
map[k(r[i])] = 1;
}
for (i=0, j=0; i<n; ++i) {
if (map[k(v = a[i])]) {
map[k(v)] = 0;
} else {
x[j++] = v;
}
}
this._rem = [];
return (this._add = x);
};
// memoizing statistics methods
TupleStore_prototype.distinct = function(get) {
var v = this.values(),
n = v.length,
map = {},
count = 0, s;
while (--n >= 0) {
s = get(v[n]) + '';
if (!Object(vega_util["v" /* hasOwnProperty */])(map, s)) {
map[s] = 1;
++count;
}
}
return count;
};
TupleStore_prototype.extent = function(get) {
if (this._get !== get || !this._ext) {
var v = this.values(),
i = Object(vega_util["q" /* extentIndex */])(v, get);
this._ext = [v[i[0]], v[i[1]]];
this._get = get;
}
return this._ext;
};
TupleStore_prototype.argmin = function(get) {
return this.extent(get)[0] || {};
};
TupleStore_prototype.argmax = function(get) {
return this.extent(get)[1] || {};
};
TupleStore_prototype.min = function(get) {
var m = this.extent(get)[0];
return m != null ? get(m) : undefined;
};
TupleStore_prototype.max = function(get) {
var m = this.extent(get)[1];
return m != null ? get(m) : undefined;
};
TupleStore_prototype.quartile = function(get) {
if (this._get !== get || !this._q) {
this._q = quartiles(this.values(), get);
this._get = get;
}
return this._q;
};
TupleStore_prototype.q1 = function(get) {
return this.quartile(get)[0];
};
TupleStore_prototype.q2 = function(get) {
return this.quartile(get)[1];
};
TupleStore_prototype.q3 = function(get) {
return this.quartile(get)[2];
};
TupleStore_prototype.ci = function(get) {
if (this._get !== get || !this._ci) {
this._ci = bootstrapCI(this.values(), 1000, 0.05, get);
this._get = get;
}
return this._ci;
};
TupleStore_prototype.ci0 = function(get) {
return this.ci(get)[0];
};
TupleStore_prototype.ci1 = function(get) {
return this.ci(get)[1];
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Aggregate.js
/**
* Group-by aggregation operator.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
* @param {Array<function(object): *>} [params.fields] - An array of accessors to aggregate.
* @param {Array<string>} [params.ops] - An array of strings indicating aggregation operations.
* @param {Array<string>} [params.as] - An array of output field names for aggregated values.
* @param {boolean} [params.cross=false] - A flag indicating that the full
* cross-product of groupby values should be generated, including empty cells.
* If true, the drop parameter is ignored and empty cells are retained.
* @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed.
*/
function Aggregate_Aggregate(params) {
Transform_Transform.call(this, null, params);
this._adds = []; // array of added output tuples
this._mods = []; // array of modified output tuples
this._alen = 0; // number of active added tuples
this._mlen = 0; // number of active modified tuples
this._drop = true; // should empty aggregation cells be removed
this._cross = false; // produce full cross-product of group-by values
this._dims = []; // group-by dimension accessors
this._dnames = []; // group-by dimension names
this._measures = []; // collection of aggregation monoids
this._countOnly = false; // flag indicating only count aggregation
this._counts = null; // collection of count fields
this._prev = null; // previous aggregation cells
this._inputs = null; // array of dependent input tuple field names
this._outputs = null; // array of output tuple field names
}
Aggregate_Aggregate.Definition = {
"type": "Aggregate",
"metadata": {"generates": true, "changes": true},
"params": [
{ "name": "groupby", "type": "field", "array": true },
{ "name": "ops", "type": "enum", "array": true, "values": AggregateOps_ValidAggregateOps },
{ "name": "fields", "type": "field", "null": true, "array": true },
{ "name": "as", "type": "string", "null": true, "array": true },
{ "name": "drop", "type": "boolean", "default": true },
{ "name": "cross", "type": "boolean", "default": false },
{ "name": "key", "type": "field" }
]
};
var Aggregate_prototype = Object(vega_util["y" /* inherits */])(Aggregate_Aggregate, Transform_Transform);
Aggregate_prototype.transform = function(_, pulse) {
var aggr = this,
out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
mod = _.modified();
aggr.stamp = out.stamp;
if (aggr.value && (mod || pulse.modified(aggr._inputs, true))) {
aggr._prev = aggr.value;
aggr.value = mod ? aggr.init(_) : {};
pulse.visit(pulse.SOURCE, t => aggr.add(t));
} else {
aggr.value = aggr.value || aggr.init(_);
pulse.visit(pulse.REM, t => aggr.rem(t));
pulse.visit(pulse.ADD, t => aggr.add(t));
}
// Indicate output fields and return aggregate tuples.
out.modifies(aggr._outputs);
// Should empty cells be dropped?
aggr._drop = _.drop !== false;
// If domain cross-product requested, generate empty cells as needed
// and ensure that empty cells are not dropped
if (_.cross && aggr._dims.length > 1) {
aggr._drop = false;
aggr.cross();
}
return aggr.changes(out);
};
Aggregate_prototype.cross = function() {
var aggr = this,
curr = aggr.value,
dims = aggr._dnames,
vals = dims.map(function() { return {}; }),
n = dims.length;
// collect all group-by domain values
function collect(cells) {
var key, i, t, v;
for (key in cells) {
t = cells[key].tuple;
for (i=0; i<n; ++i) {
vals[i][(v = t[dims[i]])] = v;
}
}
}
collect(aggr._prev);
collect(curr);
// iterate over key cross-product, create cells as needed
function generate(base, tuple, index) {
var name = dims[index],
v = vals[index++],
k, key;
for (k in v) {
tuple[name] = v[k];
key = base ? base + '|' + k : k;
if (index < n) generate(key, tuple, index);
else if (!curr[key]) aggr.cell(key, tuple);
}
}
generate('', {}, 0);
};
Aggregate_prototype.init = function(_) {
// initialize input and output fields
var inputs = (this._inputs = []),
outputs = (this._outputs = []),
inputMap = {};
function inputVisit(get) {
var fields = Object(vega_util["i" /* array */])(Object(vega_util["g" /* accessorFields */])(get)),
i = 0, n = fields.length, f;
for (; i<n; ++i) {
if (!inputMap[f=fields[i]]) {
inputMap[f] = 1;
inputs.push(f);
}
}
}
// initialize group-by dimensions
this._dims = Object(vega_util["i" /* array */])(_.groupby);
this._dnames = this._dims.map(function(d) {
var dname = Object(vega_util["h" /* accessorName */])(d);
inputVisit(d);
outputs.push(dname);
return dname;
});
this.cellkey = _.key ? _.key : groupkey(this._dims);
// initialize aggregate measures
this._countOnly = true;
this._counts = [];
this._measures = [];
var fields = _.fields || [null],
ops = _.ops || ['count'],
as = _.as || [],
n = fields.length,
map = {},
field, op, m, mname, outname, i;
if (n !== ops.length) {
Object(vega_util["n" /* error */])('Unmatched number of fields and aggregate ops.');
}
for (i=0; i<n; ++i) {
field = fields[i];
op = ops[i];
if (field == null && op !== 'count') {
Object(vega_util["n" /* error */])('Null aggregate field specified.');
}
mname = Object(vega_util["h" /* accessorName */])(field);
outname = AggregateOps_measureName(op, mname, as[i]);
outputs.push(outname);
if (op === 'count') {
this._counts.push(outname);
continue;
}
m = map[mname];
if (!m) {
inputVisit(field);
m = (map[mname] = []);
m.field = field;
this._measures.push(m);
}
if (op !== 'count') this._countOnly = false;
m.push(AggregateOps_createMeasure(op, outname));
}
this._measures = this._measures.map(function(m) {
return AggregateOps_compileMeasures(m, m.field);
});
return {}; // aggregation cells (this.value)
};
// -- Cell Management -----
Aggregate_prototype.cellkey = groupkey();
Aggregate_prototype.cell = function(key, t) {
var cell = this.value[key];
if (!cell) {
cell = this.value[key] = this.newcell(key, t);
this._adds[this._alen++] = cell;
} else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) {
cell.stamp = this.stamp;
this._adds[this._alen++] = cell;
} else if (cell.stamp < this.stamp) {
cell.stamp = this.stamp;
this._mods[this._mlen++] = cell;
}
return cell;
};
Aggregate_prototype.newcell = function(key, t) {
var cell = {
key: key,
num: 0,
agg: null,
tuple: this.newtuple(t, this._prev && this._prev[key]),
stamp: this.stamp,
store: false
};
if (!this._countOnly) {
var measures = this._measures,
n = measures.length, i;
cell.agg = Array(n);
for (i=0; i<n; ++i) {
cell.agg[i] = new measures[i](cell);
}
}
if (cell.store) {
cell.data = new TupleStore_TupleStore();
}
return cell;
};
Aggregate_prototype.newtuple = function(t, p) {
var names = this._dnames,
dims = this._dims,
x = {}, i, n;
for (i=0, n=dims.length; i<n; ++i) {
x[names[i]] = dims[i](t);
}
return p ? replace(p.tuple, x) : Tuple_ingest(x);
};
// -- Process Tuples -----
Aggregate_prototype.add = function(t) {
var key = this.cellkey(t),
cell = this.cell(key, t),
agg, i, n;
cell.num += 1;
if (this._countOnly) return;
if (cell.store) cell.data.add(t);
agg = cell.agg;
for (i=0, n=agg.length; i<n; ++i) {
agg[i].add(agg[i].get(t), t);
}
};
Aggregate_prototype.rem = function(t) {
var key = this.cellkey(t),
cell = this.cell(key, t),
agg, i, n;
cell.num -= 1;
if (this._countOnly) return;
if (cell.store) cell.data.rem(t);
agg = cell.agg;
for (i=0, n=agg.length; i<n; ++i) {
agg[i].rem(agg[i].get(t), t);
}
};
Aggregate_prototype.celltuple = function(cell) {
var tuple = cell.tuple,
counts = this._counts,
agg, i, n;
// consolidate stored values
if (cell.store) {
cell.data.values();
}
// update tuple properties
for (i=0, n=counts.length; i<n; ++i) {
tuple[counts[i]] = cell.num;
}
if (!this._countOnly) {
agg = cell.agg;
for (i=0, n=agg.length; i<n; ++i) {
agg[i].set(tuple);
}
}
return tuple;
};
Aggregate_prototype.changes = function(out) {
var adds = this._adds,
mods = this._mods,
prev = this._prev,
drop = this._drop,
add = out.add,
rem = out.rem,
mod = out.mod,
cell, key, i, n;
if (prev) for (key in prev) {
cell = prev[key];
if (!drop || cell.num) rem.push(cell.tuple);
}
for (i=0, n=this._alen; i<n; ++i) {
add.push(this.celltuple(adds[i]));
adds[i] = null; // for garbage collection
}
for (i=0, n=this._mlen; i<n; ++i) {
cell = mods[i];
(cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell));
mods[i] = null; // for garbage collection
}
this._alen = this._mlen = 0; // reset list of active cells
this._prev = null;
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Bin.js
// epsilon bias to offset floating point error (#1737)
const Bin_EPSILON = 1e-14;
/**
* Generates a binning function for discretizing data.
* @constructor
* @param {object} params - The parameters for this operator. The
* provided values should be valid options for the {@link bin} function.
* @param {function(object): *} params.field - The data field to bin.
*/
function Bin_Bin(params) {
Transform_Transform.call(this, null, params);
}
Bin_Bin.Definition = {
"type": "Bin",
"metadata": {"modifies": true},
"params": [
{ "name": "field", "type": "field", "required": true },
{ "name": "interval", "type": "boolean", "default": true },
{ "name": "anchor", "type": "number" },
{ "name": "maxbins", "type": "number", "default": 20 },
{ "name": "base", "type": "number", "default": 10 },
{ "name": "divide", "type": "number", "array": true, "default": [5, 2] },
{ "name": "extent", "type": "number", "array": true, "length": 2, "required": true },
{ "name": "span", "type": "number" },
{ "name": "step", "type": "number" },
{ "name": "steps", "type": "number", "array": true },
{ "name": "minstep", "type": "number", "default": 0 },
{ "name": "nice", "type": "boolean", "default": true },
{ "name": "name", "type": "string" },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": ["bin0", "bin1"] }
]
};
var Bin_prototype = Object(vega_util["y" /* inherits */])(Bin_Bin, Transform_Transform);
Bin_prototype.transform = function(_, pulse) {
var band = _.interval !== false,
bins = this._bins(_),
start = bins.start,
step = bins.step,
as = _.as || ['bin0', 'bin1'],
b0 = as[0],
b1 = as[1],
flag;
if (_.modified()) {
pulse = pulse.reflow(true);
flag = pulse.SOURCE;
} else {
flag = pulse.modified(Object(vega_util["g" /* accessorFields */])(_.field)) ? pulse.ADD_MOD : pulse.ADD;
}
pulse.visit(flag, band
? function(t) {
var v = bins(t);
// minimum bin value (inclusive)
t[b0] = v;
// maximum bin value (exclusive)
// use convoluted math for better floating point agreement
// see https://github.com/vega/vega/issues/830
// infinite values propagate through this formula! #2227
t[b1] = v == null ? null : start + step * (1 + (v - start) / step);
}
: function(t) { t[b0] = bins(t); }
);
return pulse.modifies(band ? as : b0);
};
Bin_prototype._bins = function(_) {
if (this.value && !_.modified()) {
return this.value;
}
var field = _.field,
bins = src_bin(_),
step = bins.step,
start = bins.start,
stop = start + Math.ceil((bins.stop - start) / step) * step,
a, d;
if ((a = _.anchor) != null) {
d = a - (start + step * Math.floor((a - start) / step));
start += d;
stop += d;
}
var f = function(t) {
var v = field(t);
return v == null ? null
: v < start ? -Infinity
: v > stop ? +Infinity
: (
v = Math.max(start, Math.min(+v, stop - step)),
start + step * Math.floor(Bin_EPSILON + (v - start) / step)
);
};
f.start = start;
f.stop = bins.stop;
f.step = step;
return this.value = Object(vega_util["f" /* accessor */])(
f,
Object(vega_util["g" /* accessorFields */])(field),
_.name || 'bin_' + Object(vega_util["h" /* accessorName */])(field)
);
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/SortedList.js
/* harmony default export */ var SortedList = (function(idFunc, source, input) {
var $ = idFunc,
data = source || [],
add = input || [],
rem = {},
cnt = 0;
return {
add: function(t) { add.push(t); },
remove: function(t) { rem[$(t)] = ++cnt; },
size: function() { return data.length; },
data: function(compare, resort) {
if (cnt) {
data = data.filter(function(t) { return !rem[$(t)]; });
rem = {};
cnt = 0;
}
if (resort && compare) {
data.sort(compare);
}
if (add.length) {
data = compare
? Object(vega_util["M" /* merge */])(compare, data, add.sort(compare))
: data.concat(add);
add = [];
}
return data;
}
}
});
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Collect.js
/**
* Collects all data tuples that pass through this operator.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(*,*): number} [params.sort] - An optional
* comparator function for additionally sorting the collected tuples.
*/
function Collect_Collect(params) {
Transform_Transform.call(this, [], params);
}
Collect_Collect.Definition = {
"type": "Collect",
"metadata": {"source": true},
"params": [
{ "name": "sort", "type": "compare" }
]
};
var Collect_prototype = Object(vega_util["y" /* inherits */])(Collect_Collect, Transform_Transform);
Collect_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.ALL),
list = SortedList(tupleid, this.value, out.materialize(out.ADD).add),
sort = _.sort,
mod = pulse.changed() || (sort &&
(_.modified('sort') || pulse.modified(sort.fields)));
out.visit(out.REM, list.remove);
this.modified(mod);
this.value = out.source = list.data(stableCompare(sort), mod);
// propagate tree root if defined
if (pulse.source && pulse.source.root) {
this.value.root = pulse.source.root;
}
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Compare.js
/**
* Generates a comparator function.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<string|function>} params.fields - The fields to compare.
* @param {Array<string>} [params.orders] - The sort orders.
* Each entry should be one of "ascending" (default) or "descending".
*/
function Compare_Compare(params) {
Operator_Operator.call(this, null, Compare_update, params);
}
Object(vega_util["y" /* inherits */])(Compare_Compare, Operator_Operator);
function Compare_update(_) {
return (this.value && !_.modified())
? this.value
: Object(vega_util["k" /* compare */])(_.fields, _.orders);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/CountPattern.js
/**
* Count regexp-defined pattern occurrences in a text field.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - An accessor for the text field.
* @param {string} [params.pattern] - RegExp string defining the text pattern.
* @param {string} [params.case] - One of 'lower', 'upper' or null (mixed) case.
* @param {string} [params.stopwords] - RegExp string of words to ignore.
*/
function CountPattern_CountPattern(params) {
Transform_Transform.call(this, null, params);
}
CountPattern_CountPattern.Definition = {
"type": "CountPattern",
"metadata": {"generates": true, "changes": true},
"params": [
{ "name": "field", "type": "field", "required": true },
{ "name": "case", "type": "enum", "values": ["upper", "lower", "mixed"], "default": "mixed" },
{ "name": "pattern", "type": "string", "default": "[\\w\"]+" },
{ "name": "stopwords", "type": "string", "default": "" },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": ["text", "count"] }
]
};
function CountPattern_tokenize(text, tcase, match) {
switch (tcase) {
case 'upper': text = text.toUpperCase(); break;
case 'lower': text = text.toLowerCase(); break;
}
return text.match(match);
}
var CountPattern_prototype = Object(vega_util["y" /* inherits */])(CountPattern_CountPattern, Transform_Transform);
CountPattern_prototype.transform = function(_, pulse) {
function process(update) {
return function(tuple) {
var tokens = CountPattern_tokenize(get(tuple), _.case, match) || [], t;
for (var i=0, n=tokens.length; i<n; ++i) {
if (!stop.test(t = tokens[i])) update(t);
}
};
}
var init = this._parameterCheck(_, pulse),
counts = this._counts,
match = this._match,
stop = this._stop,
get = _.field,
as = _.as || ['text', 'count'],
add = process(function(t) { counts[t] = 1 + (counts[t] || 0); }),
rem = process(function(t) { counts[t] -= 1; });
if (init) {
pulse.visit(pulse.SOURCE, add);
} else {
pulse.visit(pulse.ADD, add);
pulse.visit(pulse.REM, rem);
}
return this._finish(pulse, as); // generate output tuples
};
CountPattern_prototype._parameterCheck = function(_, pulse) {
var init = false;
if (_.modified('stopwords') || !this._stop) {
this._stop = new RegExp('^' + (_.stopwords || '') + '$', 'i');
init = true;
}
if (_.modified('pattern') || !this._match) {
this._match = new RegExp((_.pattern || '[\\w\']+'), 'g');
init = true;
}
if (_.modified('field') || pulse.modified(_.field.fields)) {
init = true;
}
if (init) this._counts = {};
return init;
};
CountPattern_prototype._finish = function(pulse, as) {
var counts = this._counts,
tuples = this._tuples || (this._tuples = {}),
text = as[0],
count = as[1],
out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
w, t, c;
for (w in counts) {
t = tuples[w];
c = counts[w] || 0;
if (!t && c) {
tuples[w] = (t = Tuple_ingest({}));
t[text] = w;
t[count] = c;
out.add.push(t);
} else if (c === 0) {
if (t) out.rem.push(t);
counts[w] = null;
tuples[w] = null;
} else if (t[count] !== c) {
t[count] = c;
out.mod.push(t);
}
}
return out.modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Cross.js
/**
* Perform a cross-product of a tuple stream with itself.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object):boolean} [params.filter] - An optional filter
* function for selectively including tuples in the cross product.
* @param {Array<string>} [params.as] - The names of the output fields.
*/
function Cross_Cross(params) {
Transform_Transform.call(this, null, params);
}
Cross_Cross.Definition = {
"type": "Cross",
"metadata": {"generates": true},
"params": [
{ "name": "filter", "type": "expr" },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": ["a", "b"] }
]
};
var Cross_prototype = Object(vega_util["y" /* inherits */])(Cross_Cross, Transform_Transform);
Cross_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE),
data = this.value,
as = _.as || ['a', 'b'],
a = as[0], b = as[1],
reset = !data
|| pulse.changed(pulse.ADD_REM)
|| _.modified('as')
|| _.modified('filter');
if (reset) {
if (data) out.rem = data;
data = pulse.materialize(pulse.SOURCE).source;
out.add = this.value = Cross_cross(data, a, b, _.filter || vega_util["Ga" /* truthy */]);
} else {
out.mod = data;
}
out.source = this.value;
return out.modifies(as);
};
function Cross_cross(input, a, b, filter) {
var data = [],
t = {},
n = input.length,
i = 0,
j, left;
for (; i<n; ++i) {
t[a] = left = input[i];
for (j=0; j<n; ++j) {
t[b] = input[j];
if (filter(t)) {
data.push(Tuple_ingest(t));
t = {};
t[a] = left;
}
}
}
return data;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/Distributions.js
var Distributions_Distributions = {
kde: src_kde,
mixture: src_mixture,
normal: src_normal,
lognormal: lognormal,
uniform: uniform
};
var Distributions_DISTRIBUTIONS = 'distributions',
Distributions_FUNCTION = 'function',
Distributions_FIELD = 'field';
/**
* Parse a parameter object for a probability distribution.
* @param {object} def - The distribution parameter object.
* @param {function():Array<object>} - A method for requesting
* source data. Used for distributions (such as KDE) that
* require sample data points. This method will only be
* invoked if the 'from' parameter for a target data source
* is not provided. Typically this method returns backing
* source data for a Pulse object.
* @return {object} - The output distribution object.
*/
function Distributions_parse(def, data) {
var func = def[Distributions_FUNCTION];
if (!Object(vega_util["v" /* hasOwnProperty */])(Distributions_Distributions, func)) {
Object(vega_util["n" /* error */])('Unknown distribution function: ' + func);
}
var d = Distributions_Distributions[func]();
for (var name in def) {
// if data field, extract values
if (name === Distributions_FIELD) {
d.data((def.from || data()).map(def[name]));
}
// if distribution mixture, recurse to parse each definition
else if (name === Distributions_DISTRIBUTIONS) {
d[name](def[name].map(function(_) { return Distributions_parse(_, data); }));
}
// otherwise, simply set the parameter
else if (typeof d[name] === Distributions_FUNCTION) {
d[name](def[name]);
}
}
return d;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Density.js
/**
* Grid sample points for a probability density. Given a distribution and
* a sampling extent, will generate points suitable for plotting either
* PDF (probability density function) or CDF (cumulative distribution
* function) curves.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {object} params.distribution - The probability distribution. This
* is an object parameter dependent on the distribution type.
* @param {string} [params.method='pdf'] - The distribution method to sample.
* One of 'pdf' or 'cdf'.
* @param {Array<number>} [params.extent] - The [min, max] extent over which
* to sample the distribution. This argument is required in most cases, but
* can be omitted if the distribution (e.g., 'kde') supports a 'data' method
* that returns numerical sample points from which the extent can be deduced.
* @param {number} [params.minsteps=25] - The minimum number of curve samples
* for plotting the density.
* @param {number} [params.maxsteps=200] - The maximum number of curve samples
* for plotting the density.
* @param {number} [params.steps] - The exact number of curve samples for
* plotting the density. If specified, overrides both minsteps and maxsteps
* to set an exact number of uniform samples. Useful in conjunction with
* a fixed extent to ensure consistent sample points for stacked densities.
*/
function Density_Density(params) {
Transform_Transform.call(this, null, params);
}
var Density_distributions = [
{
"key": {"function": "normal"},
"params": [
{ "name": "mean", "type": "number", "default": 0 },
{ "name": "stdev", "type": "number", "default": 1 }
]
},
{
"key": {"function": "lognormal"},
"params": [
{ "name": "mean", "type": "number", "default": 0 },
{ "name": "stdev", "type": "number", "default": 1 }
]
},
{
"key": {"function": "uniform"},
"params": [
{ "name": "min", "type": "number", "default": 0 },
{ "name": "max", "type": "number", "default": 1 }
]
},
{
"key": {"function": "kde"},
"params": [
{ "name": "field", "type": "field", "required": true },
{ "name": "from", "type": "data" },
{ "name": "bandwidth", "type": "number", "default": 0 }
]
}
];
var Density_mixture = {
"key": {"function": "mixture"},
"params": [
{ "name": "distributions", "type": "param", "array": true,
"params": Density_distributions },
{ "name": "weights", "type": "number", "array": true }
]
};
Density_Density.Definition = {
"type": "Density",
"metadata": {"generates": true},
"params": [
{ "name": "extent", "type": "number", "array": true, "length": 2 },
{ "name": "steps", "type": "number" },
{ "name": "minsteps", "type": "number", "default": 25 },
{ "name": "maxsteps", "type": "number", "default": 200 },
{ "name": "method", "type": "string", "default": "pdf",
"values": ["pdf", "cdf"] },
{ "name": "distribution", "type": "param",
"params": Density_distributions.concat(Density_mixture) },
{ "name": "as", "type": "string", "array": true,
"default": ["value", "density"] }
]
};
var Density_prototype = Object(vega_util["y" /* inherits */])(Density_Density, Transform_Transform);
Density_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
if (!this.value || pulse.changed() || _.modified()) {
var dist = Distributions_parse(_.distribution, Density_source(pulse)),
minsteps = _.steps || _.minsteps || 25,
maxsteps = _.steps || _.maxsteps || 200,
method = _.method || 'pdf';
if (method !== 'pdf' && method !== 'cdf') {
Object(vega_util["n" /* error */])('Invalid density method: ' + method);
}
if (!_.extent && !dist.data) {
Object(vega_util["n" /* error */])('Missing density extent parameter.');
}
method = dist[method];
var as = _.as || ['value', 'density'],
domain = _.extent || Object(vega_util["p" /* extent */])(dist.data()),
values = sampleCurve(method, domain, minsteps, maxsteps).map(v => {
var tuple = {};
tuple[as[0]] = v[0];
tuple[as[1]] = v[1];
return Tuple_ingest(tuple);
});
if (this.value) out.rem = this.value;
this.value = out.add = out.source = values;
}
return out;
};
function Density_source(pulse) {
return function() { return pulse.materialize(pulse.SOURCE).source; };
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/util.js
// use either provided alias or accessor field name
function util_fieldNames(fields, as) {
if (!fields) return null;
return fields.map(function(f, i) {
return as[i] || Object(vega_util["h" /* accessorName */])(f);
});
}
function util_partition(data, groupby, field) {
var groups = [],
get = function(f) { return f(t); },
map, i, n, t, k, g;
// partition data points into groups
if (groupby == null) {
groups.push(data.map(field));
} else {
for (map={}, i=0, n=data.length; i<n; ++i) {
t = data[i];
k = groupby.map(get);
g = map[k];
if (!g) {
map[k] = (g = []);
g.dims = k;
groups.push(g);
}
g.push(field(t));
}
}
return groups;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/DotBin.js
const DotBin_Output = 'bin';
/**
* Dot density binning for dot plot construction.
* Based on Leland Wilkinson, Dot Plots, The American Statistician, 1999.
* https://www.cs.uic.edu/~wilkinson/Publications/dotplots.pdf
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to bin.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
* @param {number} [params.step] - The step size (bin width) within which dots should be
* stacked. Defaults to 1/30 of the extent of the data *field*.
* @param {boolean} [params.smooth=false] - A boolean flag indicating if dot density
* stacks should be smoothed to reduce variance.
*/
function DotBin_DotBin(params) {
Transform_Transform.call(this, null, params);
}
DotBin_DotBin.Definition = {
"type": "DotBin",
"metadata": {"modifies": true},
"params": [
{ "name": "field", "type": "field", "required": true },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "step", "type": "number" },
{ "name": "smooth", "type": "boolean", "default": false },
{ "name": "as", "type": "string", "default": DotBin_Output }
]
};
const DotBin_prototype = Object(vega_util["y" /* inherits */])(DotBin_DotBin, Transform_Transform);
DotBin_prototype.transform = function(_, pulse) {
if (this.value && !(_.modified() || pulse.changed())) {
return pulse; // early exit
}
const source = pulse.materialize(pulse.SOURCE).source,
groups = util_partition(pulse.source, _.groupby, vega_util["x" /* identity */]),
smooth = _.smooth || false,
field = _.field,
step = _.step || DotBin_autostep(source, field),
sort = stableCompare((a, b) => field(a) - field(b)),
as = _.as || DotBin_Output,
n = groups.length;
// compute dotplot bins per group
let min = Infinity, max = -Infinity, i = 0, j;
for (; i<n; ++i) {
const g = groups[i].sort(sort);
j = -1;
for (const v of dotbin(g, step, smooth, field)) {
if (v < min) min = v;
if (v > max) max = v;
g[++j][as] = v;
}
}
this.value = {
start: min,
stop: max,
step: step
};
return pulse.reflow(true).modifies(as);
};
function DotBin_autostep(data, field) {
return Object(vega_util["X" /* span */])(Object(vega_util["p" /* extent */])(data, field)) / 30;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Expression.js
/**
* Wraps an expression function with access to external parameters.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function} params.expr - The expression function. The
* function should accept both a datum and a parameter object.
* This operator's value will be a new function that wraps the
* expression function with access to this operator's parameters.
*/
function Expression_Expression(params) {
Operator_Operator.call(this, null, Expression_update, params);
this.modified(true);
}
Object(vega_util["y" /* inherits */])(Expression_Expression, Operator_Operator);
function Expression_update(_) {
var expr = _.expr;
return this.value && !_.modified('expr')
? this.value
: Object(vega_util["f" /* accessor */])(
datum => expr(datum, _),
Object(vega_util["g" /* accessorFields */])(expr),
Object(vega_util["h" /* accessorName */])(expr)
);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Extent.js
/**
* Computes extents (min/max) for a data field.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The field over which to compute extends.
*/
function Extent_Extent(params) {
Transform_Transform.call(this, [undefined, undefined], params);
}
Extent_Extent.Definition = {
"type": "Extent",
"metadata": {},
"params": [
{ "name": "field", "type": "field", "required": true }
]
};
var Extent_prototype = Object(vega_util["y" /* inherits */])(Extent_Extent, Transform_Transform);
Extent_prototype.transform = function(_, pulse) {
var extent = this.value,
field = _.field,
min = extent[0],
max = extent[1],
mod;
mod = pulse.changed()
|| pulse.modified(field.fields)
|| _.modified('field');
if (mod || min == null) {
min = +Infinity;
max = -Infinity;
}
pulse.visit(mod ? pulse.SOURCE : pulse.ADD, function(t) {
var v = field(t);
if (v != null) {
// coerce to number
v = +v;
// NaNs will fail all comparisons!
if (v < min) min = v;
if (v > max) max = v;
}
});
if (!Number.isFinite(min) || !Number.isFinite(max)) {
let name = Object(vega_util["h" /* accessorName */])(field);
if (name) name = ` for field "${name}"`;
pulse.dataflow.warn(`Infinite extent${name}: [${min}, ${max}]`);
min = max = undefined;
}
this.value = [min, max];
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Subflow.js
/**
* Provides a bridge between a parent transform and a target subflow that
* consumes only a subset of the tuples that pass through the parent.
* @constructor
* @param {Pulse} pulse - A pulse to use as the value of this operator.
* @param {Transform} parent - The parent transform (typically a Facet instance).
* @param {Transform} target - A transform that receives the subflow of tuples.
*/
function Subflow_Subflow(pulse, parent) {
Operator_Operator.call(this, pulse);
this.parent = parent;
}
var Subflow_prototype = Object(vega_util["y" /* inherits */])(Subflow_Subflow, Operator_Operator);
Subflow_prototype.connect = function(target) {
this.targets().add(target);
return (target.source = this);
};
/**
* Add an 'add' tuple to the subflow pulse.
* @param {Tuple} t - The tuple being added.
*/
Subflow_prototype.add = function(t) {
this.value.add.push(t);
};
/**
* Add a 'rem' tuple to the subflow pulse.
* @param {Tuple} t - The tuple being removed.
*/
Subflow_prototype.rem = function(t) {
this.value.rem.push(t);
};
/**
* Add a 'mod' tuple to the subflow pulse.
* @param {Tuple} t - The tuple being modified.
*/
Subflow_prototype.mod = function(t) {
this.value.mod.push(t);
};
/**
* Re-initialize this operator's pulse value.
* @param {Pulse} pulse - The pulse to copy from.
* @see Pulse.init
*/
Subflow_prototype.init = function(pulse) {
this.value.init(pulse, pulse.NO_SOURCE);
};
/**
* Evaluate this operator. This method overrides the
* default behavior to simply return the contained pulse value.
* @return {Pulse}
*/
Subflow_prototype.evaluate = function() {
// assert: this.value.stamp === pulse.stamp
return this.value;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Facet.js
/**
* Facets a dataflow into a set of subflows based on a key.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(Dataflow, string): Operator} params.subflow - A function
* that generates a subflow of operators and returns its root operator.
* @param {function(object): *} params.key - The key field to facet by.
*/
function Facet_Facet(params) {
Transform_Transform.call(this, {}, params);
this._keys = Object(vega_util["s" /* fastmap */])(); // cache previously calculated key values
// keep track of active subflows, use as targets array for listeners
// this allows us to limit propagation to only updated subflows
var a = this._targets = [];
a.active = 0;
a.forEach = function(f) {
for (var i=0, n=a.active; i<n; ++i) f(a[i], i, a);
};
}
var Facet_prototype = Object(vega_util["y" /* inherits */])(Facet_Facet, Transform_Transform);
Facet_prototype.activate = function(flow) {
this._targets[this._targets.active++] = flow;
};
Facet_prototype.subflow = function(key, flow, pulse, parent) {
var flows = this.value,
sf = Object(vega_util["v" /* hasOwnProperty */])(flows, key) && flows[key],
df, p;
if (!sf) {
p = parent || (p = this._group[key]) && p.tuple;
df = pulse.dataflow;
sf = df.add(new Subflow_Subflow(pulse.fork(pulse.NO_SOURCE), this))
.connect(flow(df, key, p));
flows[key] = sf;
this.activate(sf);
} else if (sf.value.stamp < pulse.stamp) {
sf.init(pulse);
this.activate(sf);
}
return sf;
};
Facet_prototype.transform = function(_, pulse) {
var df = pulse.dataflow,
self = this,
key = _.key,
flow = _.subflow,
cache = this._keys,
rekey = _.modified('key');
function subflow(key) {
return self.subflow(key, flow, pulse);
}
this._group = _.group || {};
this._targets.active = 0; // reset list of active subflows
pulse.visit(pulse.REM, function(t) {
var id = tupleid(t),
k = cache.get(id);
if (k !== undefined) {
cache.delete(id);
subflow(k).rem(t);
}
});
pulse.visit(pulse.ADD, function(t) {
var k = key(t);
cache.set(tupleid(t), k);
subflow(k).add(t);
});
if (rekey || pulse.modified(key.fields)) {
pulse.visit(pulse.MOD, function(t) {
var id = tupleid(t),
k0 = cache.get(id),
k1 = key(t);
if (k0 === k1) {
subflow(k1).mod(t);
} else {
cache.set(id, k1);
subflow(k0).rem(t);
subflow(k1).add(t);
}
});
} else if (pulse.changed(pulse.MOD)) {
pulse.visit(pulse.MOD, function(t) {
subflow(cache.get(tupleid(t))).mod(t);
});
}
if (rekey) {
pulse.visit(pulse.REFLOW, function(t) {
var id = tupleid(t),
k0 = cache.get(id),
k1 = key(t);
if (k0 !== k1) {
cache.set(id, k1);
subflow(k0).rem(t);
subflow(k1).add(t);
}
});
}
if (cache.empty > df.cleanThreshold) df.runAfter(cache.clean);
return pulse;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Field.js
/**
* Generates one or more field accessor functions.
* If the 'name' parameter is an array, an array of field accessors
* will be created and the 'as' parameter will be ignored.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {string} params.name - The field name(s) to access.
* @param {string} params.as - The accessor function name.
*/
function Field_Field(params) {
Operator_Operator.call(this, null, Field_update, params);
}
Object(vega_util["y" /* inherits */])(Field_Field, Operator_Operator);
function Field_update(_) {
return (this.value && !_.modified()) ? this.value
: Object(vega_util["A" /* isArray */])(_.name) ? Object(vega_util["i" /* array */])(_.name).map(function(f) { return Object(vega_util["t" /* field */])(f); })
: Object(vega_util["t" /* field */])(_.name, _.as);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Filter.js
/**
* Filters data tuples according to a predicate function.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.expr - The predicate expression function
* that determines a tuple's filter status. Truthy values pass the filter.
*/
function Filter_Filter(params) {
Transform_Transform.call(this, Object(vega_util["s" /* fastmap */])(), params);
}
Filter_Filter.Definition = {
"type": "Filter",
"metadata": {"changes": true},
"params": [
{ "name": "expr", "type": "expr", "required": true }
]
};
var Filter_prototype = Object(vega_util["y" /* inherits */])(Filter_Filter, Transform_Transform);
Filter_prototype.transform = function(_, pulse) {
var df = pulse.dataflow,
cache = this.value, // cache ids of filtered tuples
output = pulse.fork(),
add = output.add,
rem = output.rem,
mod = output.mod,
test = _.expr,
isMod = true;
pulse.visit(pulse.REM, function(t) {
var id = tupleid(t);
if (!cache.has(id)) rem.push(t);
else cache.delete(id);
});
pulse.visit(pulse.ADD, function(t) {
if (test(t, _)) add.push(t);
else cache.set(tupleid(t), 1);
});
function revisit(t) {
var id = tupleid(t),
b = test(t, _),
s = cache.get(id);
if (b && s) {
cache.delete(id);
add.push(t);
} else if (!b && !s) {
cache.set(id, 1);
rem.push(t);
} else if (isMod && b && !s) {
mod.push(t);
}
}
pulse.visit(pulse.MOD, revisit);
if (_.modified()) {
isMod = false;
pulse.visit(pulse.REFLOW, revisit);
}
if (cache.empty > df.cleanThreshold) df.runAfter(cache.clean);
return output;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Flatten.js
/**
* Flattens array-typed field values into new data objects.
* If multiple fields are specified, they are treated as parallel arrays,
* with output values included for each matching index (or null if missing).
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *>} params.fields - An array of field
* accessors for the tuple fields that should be flattened.
* @param {string} [params.index] - Optional output field name for index
* value. If unspecified, no index field is included in the output.
* @param {Array<string>} [params.as] - Output field names for flattened
* array fields. Any unspecified fields will use the field name provided
* by the fields accessors.
*/
function Flatten_Flatten(params) {
Transform_Transform.call(this, [], params);
}
Flatten_Flatten.Definition = {
"type": "Flatten",
"metadata": {"generates": true},
"params": [
{ "name": "fields", "type": "field", "array": true, "required": true },
{ "name": "index", "type": "string" },
{ "name": "as", "type": "string", "array": true }
]
};
var Flatten_prototype = Object(vega_util["y" /* inherits */])(Flatten_Flatten, Transform_Transform);
Flatten_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE),
fields = _.fields,
as = util_fieldNames(fields, _.as || []),
index = _.index || null,
m = as.length;
// remove any previous results
out.rem = this.value;
// generate flattened tuples
pulse.visit(pulse.SOURCE, function(t) {
var arrays = fields.map(f => f(t)),
maxlen = arrays.reduce((l, a) => Math.max(l, a.length), 0),
i = 0, j, d, v;
for (; i<maxlen; ++i) {
d = Tuple_derive(t);
for (j=0; j<m; ++j) {
d[as[j]] = (v = arrays[j][i]) == null ? null : v;
}
if (index) {
d[index] = i;
}
out.add.push(d);
}
});
this.value = out.source = out.add;
if (index) out.modifies(index);
return out.modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Fold.js
/**
* Folds one more tuple fields into multiple tuples in which the field
* name and values are available under new 'key' and 'value' fields.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.fields - An array of field accessors
* for the tuple fields that should be folded.
* @param {Array<string>} [params.as] - Output field names for folded key
* and value fields, defaults to ['key', 'value'].
*/
function Fold_Fold(params) {
Transform_Transform.call(this, [], params);
}
Fold_Fold.Definition = {
"type": "Fold",
"metadata": {"generates": true},
"params": [
{ "name": "fields", "type": "field", "array": true, "required": true },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": ["key", "value"] }
]
};
var Fold_prototype = Object(vega_util["y" /* inherits */])(Fold_Fold, Transform_Transform);
Fold_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE),
fields = _.fields,
fnames = fields.map(vega_util["h" /* accessorName */]),
as = _.as || ['key', 'value'],
k = as[0],
v = as[1],
n = fields.length;
out.rem = this.value;
pulse.visit(pulse.SOURCE, function(t) {
for (var i=0, d; i<n; ++i) {
d = Tuple_derive(t);
d[k] = fnames[i];
d[v] = fields[i](t);
out.add.push(d);
}
});
this.value = out.source = out.add;
return out.modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Formula.js
/**
* Invokes a function for each data tuple and saves the results as a new field.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.expr - The formula function to invoke for each tuple.
* @param {string} params.as - The field name under which to save the result.
* @param {boolean} [params.initonly=false] - If true, the formula is applied to
* added tuples only, and does not update in response to modifications.
*/
function Formula_Formula(params) {
Transform_Transform.call(this, null, params);
}
Formula_Formula.Definition = {
"type": "Formula",
"metadata": {"modifies": true},
"params": [
{ "name": "expr", "type": "expr", "required": true },
{ "name": "as", "type": "string", "required": true },
{ "name": "initonly", "type": "boolean" }
]
};
var Formula_prototype = Object(vega_util["y" /* inherits */])(Formula_Formula, Transform_Transform);
Formula_prototype.transform = function(_, pulse) {
var func = _.expr,
as = _.as,
mod = _.modified(),
flag = _.initonly ? pulse.ADD
: mod ? pulse.SOURCE
: pulse.modified(func.fields) || pulse.modified(as) ? pulse.ADD_MOD
: pulse.ADD;
if (mod) {
// parameters updated, need to reflow
pulse = pulse.materialize().reflow(true);
}
if (!_.initonly) {
pulse.modifies(as);
}
return pulse.visit(flag, t => t[as] = func(t, _));
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Generate.js
/**
* Generates data tuples using a provided generator function.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(Parameters): object} params.generator - A tuple generator
* function. This function is given the operator parameters as input.
* Changes to any additional parameters will not trigger re-calculation
* of previously generated tuples. Only future tuples are affected.
* @param {number} params.size - The number of tuples to produce.
*/
function Generate_Generate(params) {
Transform_Transform.call(this, [], params);
}
var Generate_prototype = Object(vega_util["y" /* inherits */])(Generate_Generate, Transform_Transform);
Generate_prototype.transform = function(_, pulse) {
var data = this.value,
out = pulse.fork(pulse.ALL),
num = _.size - data.length,
gen = _.generator,
add, rem, t;
if (num > 0) {
// need more tuples, generate and add
for (add=[]; --num >= 0;) {
add.push(t = Tuple_ingest(gen(_)));
data.push(t);
}
out.add = out.add.length
? out.materialize(out.ADD).add.concat(add)
: add;
} else {
// need fewer tuples, remove
rem = data.slice(0, -num);
out.rem = out.rem.length
? out.materialize(out.REM).rem.concat(rem)
: rem;
data = data.slice(-num);
}
out.source = this.value = data;
return out;
};
// CONCATENATED MODULE: ./node_modules/d3-array/src/mean.js
function mean_mean(values, valueof) {
let count = 0;
let sum = 0;
if (valueof === undefined) {
for (let value of values) {
if (value != null && (value = +value) >= value) {
++count, sum += value;
}
}
} else {
let index = -1;
for (let value of values) {
if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {
++count, sum += value;
}
}
}
if (count) return sum / count;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Impute.js
var Impute_Methods = {
value: 'value',
median: median,
mean: mean_mean,
min: min_min,
max: max_max
};
var Impute_Empty = [];
/**
* Impute missing values.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to impute.
* @param {Array<function(object): *>} [params.groupby] - An array of
* accessors to determine series within which to perform imputation.
* @param {function(object): *} params.key - An accessor for a key value.
* Each key value should be unique within a group. New tuples will be
* imputed for any key values that are not found within a group.
* @param {Array<*>} [params.keyvals] - Optional array of required key
* values. New tuples will be imputed for any key values that are not
* found within a group. In addition, these values will be automatically
* augmented with the key values observed in the input data.
* @param {string} [method='value'] - The imputation method to use. One of
* 'value', 'mean', 'median', 'max', 'min'.
* @param {*} [value=0] - The constant value to use for imputation
* when using method 'value'.
*/
function Impute_Impute(params) {
Transform_Transform.call(this, [], params);
}
Impute_Impute.Definition = {
"type": "Impute",
"metadata": {"changes": true},
"params": [
{ "name": "field", "type": "field", "required": true },
{ "name": "key", "type": "field", "required": true },
{ "name": "keyvals", "array": true },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "method", "type": "enum", "default": "value",
"values": ["value", "mean", "median", "max", "min"] },
{ "name": "value", "default": 0 }
]
};
var Impute_prototype = Object(vega_util["y" /* inherits */])(Impute_Impute, Transform_Transform);
function Impute_getValue(_) {
var m = _.method || Impute_Methods.value, v;
if (Impute_Methods[m] == null) {
Object(vega_util["n" /* error */])('Unrecognized imputation method: ' + m);
} else if (m === Impute_Methods.value) {
v = _.value !== undefined ? _.value : 0;
return function() { return v; };
} else {
return Impute_Methods[m];
}
}
function Impute_getField(_) {
var f = _.field;
return function(t) { return t ? f(t) : NaN; };
}
Impute_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.ALL),
impute = Impute_getValue(_),
field = Impute_getField(_),
fName = Object(vega_util["h" /* accessorName */])(_.field),
kName = Object(vega_util["h" /* accessorName */])(_.key),
gNames = (_.groupby || []).map(vega_util["h" /* accessorName */]),
groups = Impute_partition(pulse.source, _.groupby, _.key, _.keyvals),
curr = [],
prev = this.value,
m = groups.domain.length,
group, value, gVals, kVal, g, i, j, l, n, t;
for (g=0, l=groups.length; g<l; ++g) {
group = groups[g];
gVals = group.values;
value = NaN;
// add tuples for missing values
for (j=0; j<m; ++j) {
if (group[j] != null) continue;
kVal = groups.domain[j];
t = {_impute: true};
for (i=0, n=gVals.length; i<n; ++i) t[gNames[i]] = gVals[i];
t[kName] = kVal;
t[fName] = Number.isNaN(value) ? (value = impute(group, field)) : value;
curr.push(Tuple_ingest(t));
}
}
// update pulse with imputed tuples
if (curr.length) out.add = out.materialize(out.ADD).add.concat(curr);
if (prev.length) out.rem = out.materialize(out.REM).rem.concat(prev);
this.value = curr;
return out;
};
function Impute_partition(data, groupby, key, keyvals) {
var get = function(f) { return f(t); },
groups = [],
domain = keyvals ? keyvals.slice() : [],
kMap = {},
gMap = {}, gVals, gKey,
group, i, j, k, n, t;
domain.forEach(function(k, i) { kMap[k] = i + 1; });
for (i=0, n=data.length; i<n; ++i) {
t = data[i];
k = key(t);
j = kMap[k] || (kMap[k] = domain.push(k));
gKey = (gVals = groupby ? groupby.map(get) : Impute_Empty) + '';
if (!(group = gMap[gKey])) {
group = (gMap[gKey] = []);
groups.push(group);
group.values = gVals;
}
group[j-1] = t;
}
groups.domain = domain;
return groups;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/JoinAggregate.js
/**
* Extend input tuples with aggregate values.
* Calcuates aggregate values and joins them with the input stream.
* @constructor
*/
function JoinAggregate_JoinAggregate(params) {
Aggregate_Aggregate.call(this, params);
}
JoinAggregate_JoinAggregate.Definition = {
"type": "JoinAggregate",
"metadata": {"modifies": true},
"params": [
{ "name": "groupby", "type": "field", "array": true },
{ "name": "fields", "type": "field", "null": true, "array": true },
{ "name": "ops", "type": "enum", "array": true, "values": AggregateOps_ValidAggregateOps },
{ "name": "as", "type": "string", "null": true, "array": true },
{ "name": "key", "type": "field" }
]
};
var JoinAggregate_prototype = Object(vega_util["y" /* inherits */])(JoinAggregate_JoinAggregate, Aggregate_Aggregate);
JoinAggregate_prototype.transform = function(_, pulse) {
var aggr = this,
mod = _.modified(),
cells;
// process all input tuples to calculate aggregates
if (aggr.value && (mod || pulse.modified(aggr._inputs, true))) {
cells = aggr.value = mod ? aggr.init(_) : {};
pulse.visit(pulse.SOURCE, function(t) { aggr.add(t); });
} else {
cells = aggr.value = aggr.value || this.init(_);
pulse.visit(pulse.REM, function(t) { aggr.rem(t); });
pulse.visit(pulse.ADD, function(t) { aggr.add(t); });
}
// update aggregation cells
aggr.changes();
// write aggregate values to input tuples
pulse.visit(pulse.SOURCE, function(t) {
Object(vega_util["o" /* extend */])(t, cells[aggr.cellkey(t)].tuple);
});
return pulse.reflow(mod).modifies(this._outputs);
};
JoinAggregate_prototype.changes = function() {
var adds = this._adds,
mods = this._mods,
i, n;
for (i=0, n=this._alen; i<n; ++i) {
this.celltuple(adds[i]);
adds[i] = null; // for garbage collection
}
for (i=0, n=this._mlen; i<n; ++i) {
this.celltuple(mods[i]);
mods[i] = null; // for garbage collection
}
this._alen = this._mlen = 0; // reset list of active cells
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/KDE.js
/**
* Compute kernel density estimates (KDE) for one or more data groups.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors
* to groupby.
* @param {function(object): *} params.field - An accessor for the data field
* to estimate.
* @param {number} [params.bandwidth=0] - The KDE kernel bandwidth.
* If zero or unspecified, the bandwidth is automatically determined.
* @param {boolean} [params.counts=false] - A boolean flag indicating if the
* output values should be probability estimates (false, default) or
* smoothed counts (true).
* @param {string} [params.cumulative=false] - A boolean flag indicating if a
* density (false) or cumulative distribution (true) should be generated.
* @param {Array<number>} [params.extent] - The domain extent over which to
* plot the density. If unspecified, the [min, max] data extent is used.
* @param {string} [params.resolve='independent'] - Indicates how parameters for
* multiple densities should be resolved. If "independent" (the default), each
* density may have its own domain extent and dynamic number of curve sample
* steps. If "shared", the KDE transform will ensure that all densities are
* defined over a shared domain and curve steps, enabling stacking.
* @param {number} [params.minsteps=25] - The minimum number of curve samples
* for plotting the density.
* @param {number} [params.maxsteps=200] - The maximum number of curve samples
* for plotting the density.
* @param {number} [params.steps] - The exact number of curve samples for
* plotting the density. If specified, overrides both minsteps and maxsteps
* to set an exact number of uniform samples. Useful in conjunction with
* a fixed extent to ensure consistent sample points for stacked densities.
*/
function KDE_KDE(params) {
Transform_Transform.call(this, null, params);
}
KDE_KDE.Definition = {
"type": "KDE",
"metadata": {"generates": true},
"params": [
{ "name": "groupby", "type": "field", "array": true },
{ "name": "field", "type": "field", "required": true },
{ "name": "cumulative", "type": "boolean", "default": false },
{ "name": "counts", "type": "boolean", "default": false },
{ "name": "bandwidth", "type": "number", "default": 0 },
{ "name": "extent", "type": "number", "array": true, "length": 2 },
{ "name": "resolve", "type": "enum", "values": ["shared", "independent"], "default": "independent" },
{ "name": "steps", "type": "number" },
{ "name": "minsteps", "type": "number", "default": 25 },
{ "name": "maxsteps", "type": "number", "default": 200 },
{ "name": "as", "type": "string", "array": true, "default": ["value", "density"] }
]
};
var KDE_prototype = Object(vega_util["y" /* inherits */])(KDE_KDE, Transform_Transform);
KDE_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
if (!this.value || pulse.changed() || _.modified()) {
const source = pulse.materialize(pulse.SOURCE).source,
groups = util_partition(source, _.groupby, _.field),
names = (_.groupby || []).map(vega_util["h" /* accessorName */]),
bandwidth = _.bandwidth,
method = _.cumulative ? 'cdf' : 'pdf',
as = _.as || ['value', 'density'],
values = [];
let domain = _.extent,
minsteps = _.steps || _.minsteps || 25,
maxsteps = _.steps || _.maxsteps || 200;
if (method !== 'pdf' && method !== 'cdf') {
Object(vega_util["n" /* error */])('Invalid density method: ' + method);
}
if (_.resolve === 'shared') {
if (!domain) domain = Object(vega_util["p" /* extent */])(source, _.field);
minsteps = maxsteps = _.steps || maxsteps;
}
groups.forEach(g => {
const density = src_kde(g, bandwidth)[method],
scale = _.counts ? g.length : 1,
local = domain || Object(vega_util["p" /* extent */])(g);
sampleCurve(density, local, minsteps, maxsteps).forEach(v => {
const t = {};
for (let i=0; i<names.length; ++i) {
t[names[i]] = g.dims[i];
}
t[as[0]] = v[0];
t[as[1]] = v[1] * scale;
values.push(Tuple_ingest(t));
});
});
if (this.value) out.rem = this.value;
this.value = out.add = out.source = values;
}
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Key.js
/**
* Generates a key function.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<string>} params.fields - The field name(s) for the key function.
* @param {boolean} params.flat - A boolean flag indicating if the field names
* should be treated as flat property names, side-stepping nested field
* lookups normally indicated by dot or bracket notation.
*/
function Key_Key(params) {
Operator_Operator.call(this, null, Key_update, params);
}
Object(vega_util["y" /* inherits */])(Key_Key, Operator_Operator);
function Key_update(_) {
return (this.value && !_.modified()) ? this.value : Object(vega_util["I" /* key */])(_.fields, _.flat);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Load.js
/**
* Load and parse data from an external source. Marshalls parameter
* values and then invokes the Dataflow request method.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {string} params.url - The URL to load from.
* @param {object} params.format - The data format options.
*/
function Load_Load(params) {
Transform_Transform.call(this, [], params);
this._pending = null;
}
var Load_prototype = Object(vega_util["y" /* inherits */])(Load_Load, Transform_Transform);
Load_prototype.transform = function(_, pulse) {
const df = pulse.dataflow;
if (this._pending) {
// update state and return pulse
return Load_output(this, pulse, this._pending);
}
if (Load_stop(_)) return pulse.StopPropagation;
if (_.values) {
// parse and ingest values, return output pulse
return Load_output(this, pulse, df.parse(_.values, _.format));
} else if (_.async) {
// return promise for non-blocking async loading
const p = df.request(_.url, _.format).then(res => {
this._pending = Object(vega_util["i" /* array */])(res.data);
return df => df.touch(this);
});
return {async: p};
} else {
// return promise for synchronous loading
return df.request(_.url, _.format)
.then(res => Load_output(this, pulse, Object(vega_util["i" /* array */])(res.data)));
}
};
function Load_stop(_) {
return _.modified('async') && !(
_.modified('values') || _.modified('url') || _.modified('format')
);
}
function Load_output(op, pulse, data) {
data.forEach(Tuple_ingest);
const out = pulse.fork(pulse.NO_FIELDS & pulse.NO_SOURCE);
out.rem = op.value;
op.value = out.source = out.add = data;
op._pending = null;
return out;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Lookup.js
/**
* Extend tuples by joining them with values from a lookup table.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Map} params.index - The lookup table map.
* @param {Array<function(object): *} params.fields - The fields to lookup.
* @param {Array<string>} params.as - Output field names for each lookup value.
* @param {*} [params.default] - A default value to use if lookup fails.
*/
function Lookup_Lookup(params) {
Transform_Transform.call(this, {}, params);
}
Lookup_Lookup.Definition = {
"type": "Lookup",
"metadata": {"modifies": true},
"params": [
{ "name": "index", "type": "index", "params": [
{"name": "from", "type": "data", "required": true },
{"name": "key", "type": "field", "required": true }
] },
{ "name": "values", "type": "field", "array": true },
{ "name": "fields", "type": "field", "array": true, "required": true },
{ "name": "as", "type": "string", "array": true },
{ "name": "default", "default": null }
]
};
var Lookup_prototype = Object(vega_util["y" /* inherits */])(Lookup_Lookup, Transform_Transform);
Lookup_prototype.transform = function(_, pulse) {
var out = pulse,
as = _.as,
keys = _.fields,
index = _.index,
values = _.values,
defaultValue = _.default==null ? null : _.default,
reset = _.modified(),
flag = reset ? pulse.SOURCE : pulse.ADD,
n = keys.length,
set, m, mods;
if (values) {
m = values.length;
if (n > 1 && !as) {
Object(vega_util["n" /* error */])('Multi-field lookup requires explicit "as" parameter.');
}
if (as && as.length !== n * m) {
Object(vega_util["n" /* error */])('The "as" parameter has too few output field names.');
}
as = as || values.map(vega_util["h" /* accessorName */]);
set = function(t) {
for (var i=0, k=0, j, v; i<n; ++i) {
v = index.get(keys[i](t));
if (v == null) for (j=0; j<m; ++j, ++k) t[as[k]] = defaultValue;
else for (j=0; j<m; ++j, ++k) t[as[k]] = values[j](v);
}
};
} else {
if (!as) {
Object(vega_util["n" /* error */])('Missing output field names.');
}
set = function(t) {
for (var i=0, v; i<n; ++i) {
v = index.get(keys[i](t));
t[as[i]] = v==null ? defaultValue : v;
}
};
}
if (reset) {
out = pulse.reflow(true);
} else {
mods = keys.some(function(k) { return pulse.modified(k.fields); });
flag |= (mods ? pulse.MOD : 0);
}
pulse.visit(flag, set);
return out.modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/MultiExtent.js
/**
* Computes global min/max extents over a collection of extents.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<Array<number>>} params.extents - The input extents.
*/
function MultiExtent_MultiExtent(params) {
Operator_Operator.call(this, null, MultiExtent_update, params);
}
Object(vega_util["y" /* inherits */])(MultiExtent_MultiExtent, Operator_Operator);
function MultiExtent_update(_) {
if (this.value && !_.modified()) {
return this.value;
}
var min = +Infinity,
max = -Infinity,
ext = _.extents,
i, n, e;
for (i=0, n=ext.length; i<n; ++i) {
e = ext[i];
if (e[0] < min) min = e[0];
if (e[1] > max) max = e[1];
}
return [min, max];
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/MultiValues.js
/**
* Merge a collection of value arrays.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<Array<*>>} params.values - The input value arrrays.
*/
function MultiValues_MultiValues(params) {
Operator_Operator.call(this, null, MultiValues_update, params);
}
Object(vega_util["y" /* inherits */])(MultiValues_MultiValues, Operator_Operator);
function MultiValues_update(_) {
return (this.value && !_.modified())
? this.value
: _.values.reduce(function(data, _) { return data.concat(_); }, []);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Params.js
/**
* Operator whose value is simply its parameter hash. This operator is
* useful for enabling reactive updates to values of nested objects.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function Params_Params(params) {
Transform_Transform.call(this, null, params);
}
Object(vega_util["y" /* inherits */])(Params_Params, Transform_Transform);
Params_Params.prototype.transform = function(_, pulse) {
this.modified(_.modified());
this.value = _;
return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); // do not pass tuples
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Pivot.js
/**
* Aggregate and pivot selected field values to become new fields.
* This operator is useful to construction cross-tabulations.
* @constructor
* @param {Array<function(object): *>} [params.groupby] - An array of accessors
* to groupby. These fields act just like groupby fields of an Aggregate transform.
* @param {function(object): *} params.field - The field to pivot on. The unique
* values of this field become new field names in the output stream.
* @param {function(object): *} params.value - The field to populate pivoted fields.
* The aggregate values of this field become the values of the new pivoted fields.
* @param {string} [params.op] - The aggregation operation for the value field,
* applied per cell in the output stream. The default is "sum".
* @param {number} [params.limit] - An optional parameter indicating the maximum
* number of pivoted fields to generate. The pivoted field names are sorted in
* ascending order prior to enforcing the limit.
*/
function Pivot_Pivot(params) {
Aggregate_Aggregate.call(this, params);
}
Pivot_Pivot.Definition = {
"type": "Pivot",
"metadata": {"generates": true, "changes": true},
"params": [
{ "name": "groupby", "type": "field", "array": true },
{ "name": "field", "type": "field", "required": true },
{ "name": "value", "type": "field", "required": true },
{ "name": "op", "type": "enum", "values": AggregateOps_ValidAggregateOps, "default": "sum" },
{ "name": "limit", "type": "number", "default": 0 },
{ "name": "key", "type": "field" }
]
};
var Pivot_prototype = Object(vega_util["y" /* inherits */])(Pivot_Pivot, Aggregate_Aggregate);
Pivot_prototype._transform = Pivot_prototype.transform;
Pivot_prototype.transform = function(_, pulse) {
return this._transform(Pivot_aggregateParams(_, pulse), pulse);
};
// Shoehorn a pivot transform into an aggregate transform!
// First collect all unique pivot field values.
// Then generate aggregate fields for each output pivot field.
function Pivot_aggregateParams(_, pulse) {
var key = _.field,
value = _.value,
op = (_.op === 'count' ? '__count__' : _.op) || 'sum',
fields = Object(vega_util["g" /* accessorFields */])(key).concat(Object(vega_util["g" /* accessorFields */])(value)),
keys = Pivot_pivotKeys(key, _.limit || 0, pulse);
// if data stream content changes, pivot fields may change
// flag parameter modification to ensure re-initialization
if (pulse.changed()) _.set('__pivot__', null, null, true);
return {
key: _.key,
groupby: _.groupby,
ops: keys.map(function() { return op; }),
fields: keys.map(function(k) { return Pivot_get(k, key, value, fields); }),
as: keys.map(function(k) { return k + ''; }),
modified: _.modified.bind(_)
};
}
// Generate aggregate field accessor.
// Output NaN for non-existent values; aggregator will ignore!
function Pivot_get(k, key, value, fields) {
return Object(vega_util["f" /* accessor */])(
function(d) { return key(d) === k ? value(d) : NaN; },
fields,
k + ''
);
}
// Collect (and optionally limit) all unique pivot values.
function Pivot_pivotKeys(key, limit, pulse) {
var map = {},
list = [];
pulse.visit(pulse.SOURCE, function(t) {
var k = key(t);
if (!map[k]) {
map[k] = 1;
list.push(k);
}
});
// TODO? Move this comparator to vega-util?
list.sort(function(u, v) {
return (u<v||u==null) && v!=null ? -1
: (u>v||v==null) && u!=null ? 1
: ((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))!==u && v===v ? -1
: v!==v && u===u ? 1 : 0;
});
return limit ? list.slice(0, limit) : list;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/PreFacet.js
/**
* Partitions pre-faceted data into tuple subflows.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(Dataflow, string): Operator} params.subflow - A function
* that generates a subflow of operators and returns its root operator.
* @param {function(object): Array<object>} params.field - The field
* accessor for an array of subflow tuple objects.
*/
function PreFacet_PreFacet(params) {
Facet_Facet.call(this, params);
}
var PreFacet_prototype = Object(vega_util["y" /* inherits */])(PreFacet_PreFacet, Facet_Facet);
PreFacet_prototype.transform = function(_, pulse) {
var self = this,
flow = _.subflow,
field = _.field;
if (_.modified('field') || field && pulse.modified(Object(vega_util["g" /* accessorFields */])(field))) {
Object(vega_util["n" /* error */])('PreFacet does not support field modification.');
}
this._targets.active = 0; // reset list of active subflows
pulse.visit(pulse.MOD, function(t) {
var sf = self.subflow(tupleid(t), flow, pulse, t);
field ? field(t).forEach(function(_) { sf.mod(_); }) : sf.mod(t);
});
pulse.visit(pulse.ADD, function(t) {
var sf = self.subflow(tupleid(t), flow, pulse, t);
field ? field(t).forEach(function(_) { sf.add(Tuple_ingest(_)); }) : sf.add(t);
});
pulse.visit(pulse.REM, function(t) {
var sf = self.subflow(tupleid(t), flow, pulse, t);
field ? field(t).forEach(function(_) { sf.rem(_); }) : sf.rem(t);
});
return pulse;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Project.js
/**
* Performs a relational projection, copying selected fields from source
* tuples to a new set of derived tuples.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *} params.fields - The fields to project,
* as an array of field accessors. If unspecified, all fields will be
* copied with names unchanged.
* @param {Array<string>} [params.as] - Output field names for each projected
* field. Any unspecified fields will use the field name provided by
* the field accessor.
*/
function Project_Project(params) {
Transform_Transform.call(this, null, params);
}
Project_Project.Definition = {
"type": "Project",
"metadata": {"generates": true, "changes": true},
"params": [
{ "name": "fields", "type": "field", "array": true },
{ "name": "as", "type": "string", "null": true, "array": true }
]
};
var Project_prototype = Object(vega_util["y" /* inherits */])(Project_Project, Transform_Transform);
Project_prototype.transform = function(_, pulse) {
var fields = _.fields,
as = util_fieldNames(_.fields, _.as || []),
derive = fields
? function(s, t) { return Project_project(s, t, fields, as); }
: rederive,
out, lut;
if (this.value) {
lut = this.value;
} else {
pulse = pulse.addAll();
lut = this.value = {};
}
out = pulse.fork(pulse.NO_SOURCE);
pulse.visit(pulse.REM, function(t) {
var id = tupleid(t);
out.rem.push(lut[id]);
lut[id] = null;
});
pulse.visit(pulse.ADD, function(t) {
var dt = derive(t, Tuple_ingest({}));
lut[tupleid(t)] = dt;
out.add.push(dt);
});
pulse.visit(pulse.MOD, function(t) {
out.mod.push(derive(t, lut[tupleid(t)]));
});
return out;
};
function Project_project(s, t, fields, as) {
for (var i=0, n=fields.length; i<n; ++i) {
t[as[i]] = fields[i](s);
}
return t;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Proxy.js
/**
* Proxy the value of another operator as a pure signal value.
* Ensures no tuples are propagated.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {*} params.value - The value to proxy, becomes the value of this operator.
*/
function Proxy_Proxy(params) {
Transform_Transform.call(this, null, params);
}
var Proxy_prototype = Object(vega_util["y" /* inherits */])(Proxy_Proxy, Transform_Transform);
Proxy_prototype.transform = function(_, pulse) {
this.value = _.value;
return _.modified('value')
? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS)
: pulse.StopPropagation;
};
// CONCATENATED MODULE: ./node_modules/d3-array/src/range.js
/* harmony default export */ var src_range = (function(start, stop, step) {
start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
var i = -1,
n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
range = new Array(n);
while (++i < n) {
range[i] = start + i * step;
}
return range;
});
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Quantile.js
/**
* Generates sample quantile values from an input data stream.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - An accessor for the data field
* over which to calculate quantile values.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors
* to groupby.
* @param {Array<number>} [params.probs] - An array of probabilities in
* the range (0, 1) for which to compute quantile values. If not specified,
* the *step* parameter will be used.
* @param {Array<number>} [params.step=0.01] - A probability step size for
* sampling quantile values. All values from one-half the step size up to
* 1 (exclusive) will be sampled. This parameter is only used if the
* *quantiles* parameter is not provided.
*/
function Quantile_Quantile(params) {
Transform_Transform.call(this, null, params);
}
Quantile_Quantile.Definition = {
"type": "Quantile",
"metadata": {"generates": true, "changes": true},
"params": [
{ "name": "groupby", "type": "field", "array": true },
{ "name": "field", "type": "field", "required": true },
{ "name": "probs", "type": "number", "array": true },
{ "name": "step", "type": "number", "default": 0.01 },
{ "name": "as", "type": "string", "array": true, "default": ["prob", "value"] }
]
};
var Quantile_prototype = Object(vega_util["y" /* inherits */])(Quantile_Quantile, Transform_Transform);
var Quantile_EPSILON = 1e-14;
Quantile_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
as = _.as || ['prob', 'value'];
if (this.value && !_.modified() && !pulse.changed()) {
out.source = this.value;
return out;
}
const source = pulse.materialize(pulse.SOURCE).source,
groups = util_partition(source, _.groupby, _.field),
names = (_.groupby || []).map(vega_util["h" /* accessorName */]),
values = [],
step = _.step || 0.01,
p = _.probs || src_range(step/2, 1 - Quantile_EPSILON, step),
n = p.length;
groups.forEach(g => {
const q = quantiles(g, p);
for (let i=0; i<n; ++i) {
const t = {};
for (let i=0; i<names.length; ++i) {
t[names[i]] = g.dims[i];
}
t[as[0]] = p[i];
t[as[1]] = q[i];
values.push(Tuple_ingest(t));
}
});
if (this.value) out.rem = this.value;
this.value = out.add = out.source = values;
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Relay.js
/**
* Relays a data stream between data processing pipelines.
* If the derive parameter is set, this transform will create derived
* copies of observed tuples. This provides derived data streams in which
* modifications to the tuples do not pollute an upstream data source.
* @param {object} params - The parameters for this operator.
* @param {number} [params.derive=false] - Boolean flag indicating if
* the transform should make derived copies of incoming tuples.
* @constructor
*/
function Relay_Relay(params) {
Transform_Transform.call(this, null, params);
}
var Relay_prototype = Object(vega_util["y" /* inherits */])(Relay_Relay, Transform_Transform);
Relay_prototype.transform = function(_, pulse) {
var out, lut;
if (this.value) {
lut = this.value;
} else {
out = pulse = pulse.addAll();
lut = this.value = {};
}
if (_.derive) {
out = pulse.fork(pulse.NO_SOURCE);
pulse.visit(pulse.REM, t => {
var id = tupleid(t);
out.rem.push(lut[id]);
lut[id] = null;
});
pulse.visit(pulse.ADD, t => {
var dt = Tuple_derive(t);
lut[tupleid(t)] = dt;
out.add.push(dt);
});
pulse.visit(pulse.MOD, t => {
var dt = lut[tupleid(t)], k;
for (k in t) {
dt[k] = t[k];
// down stream writes may overwrite re-derived tuples
// conservatively mark all source fields as modified
out.modifies(k);
}
out.mod.push(dt);
});
}
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Sample.js
/**
* Samples tuples passing through this operator.
* Uses reservoir sampling to maintain a representative sample.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {number} [params.size=1000] - The maximum number of samples.
*/
function Sample_Sample(params) {
Transform_Transform.call(this, [], params);
this.count = 0;
}
Sample_Sample.Definition = {
"type": "Sample",
"metadata": {},
"params": [
{ "name": "size", "type": "number", "default": 1000 }
]
};
var Sample_prototype = Object(vega_util["y" /* inherits */])(Sample_Sample, Transform_Transform);
Sample_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE),
mod = _.modified('size'),
num = _.size,
res = this.value,
cnt = this.count,
cap = 0,
map = res.reduce(function(m, t) {
m[tupleid(t)] = 1;
return m;
}, {});
// sample reservoir update function
function update(t) {
var p, idx;
if (res.length < num) {
res.push(t);
} else {
idx = ~~((cnt + 1) * random_random());
if (idx < res.length && idx >= cap) {
p = res[idx];
if (map[tupleid(p)]) out.rem.push(p); // eviction
res[idx] = t;
}
}
++cnt;
}
if (pulse.rem.length) {
// find all tuples that should be removed, add to output
pulse.visit(pulse.REM, function(t) {
var id = tupleid(t);
if (map[id]) {
map[id] = -1;
out.rem.push(t);
}
--cnt;
});
// filter removed tuples out of the sample reservoir
res = res.filter(function(t) { return map[tupleid(t)] !== -1; });
}
if ((pulse.rem.length || mod) && res.length < num && pulse.source) {
// replenish sample if backing data source is available
cap = cnt = res.length;
pulse.visit(pulse.SOURCE, function(t) {
// update, but skip previously sampled tuples
if (!map[tupleid(t)]) update(t);
});
cap = -1;
}
if (mod && res.length > num) {
for (var i=0, n=res.length-num; i<n; ++i) {
map[tupleid(res[i])] = -1;
out.rem.push(res[i]);
}
res = res.slice(n);
}
if (pulse.mod.length) {
// propagate modified tuples in the sample reservoir
pulse.visit(pulse.MOD, function(t) {
if (map[tupleid(t)]) out.mod.push(t);
});
}
if (pulse.add.length) {
// update sample reservoir
pulse.visit(pulse.ADD, update);
}
if (pulse.add.length || cap < 0) {
// output newly added tuples
out.add = res.filter(function(t) { return !map[tupleid(t)]; });
}
this.count = cnt;
this.value = out.source = res;
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Sequence.js
/**
* Generates data tuples for a specified sequence range of numbers.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {number} params.start - The first number in the sequence.
* @param {number} params.stop - The last number (exclusive) in the sequence.
* @param {number} [params.step=1] - The step size between numbers in the sequence.
*/
function Sequence_Sequence(params) {
Transform_Transform.call(this, null, params);
}
Sequence_Sequence.Definition = {
"type": "Sequence",
"metadata": {"generates": true, "changes": true},
"params": [
{ "name": "start", "type": "number", "required": true },
{ "name": "stop", "type": "number", "required": true },
{ "name": "step", "type": "number", "default": 1 },
{ "name": "as", "type": "string", "default": "data" }
]
};
var Sequence_prototype = Object(vega_util["y" /* inherits */])(Sequence_Sequence, Transform_Transform);
Sequence_prototype.transform = function(_, pulse) {
if (this.value && !_.modified()) return;
var out = pulse.materialize().fork(pulse.MOD),
as = _.as || 'data';
out.rem = this.value ? pulse.rem.concat(this.value) : pulse.rem;
this.value = src_range(_.start, _.stop, _.step || 1).map(function(v) {
var t = {};
t[as] = v;
return Tuple_ingest(t);
});
out.add = pulse.add.concat(this.value);
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Sieve.js
/**
* Propagates a new pulse without any tuples so long as the input
* pulse contains some added, removed or modified tuples.
* @param {object} params - The parameters for this operator.
* @constructor
*/
function Sieve_Sieve(params) {
Transform_Transform.call(this, null, params);
this.modified(true); // always treat as modified
}
var Sieve_prototype = Object(vega_util["y" /* inherits */])(Sieve_Sieve, Transform_Transform);
Sieve_prototype.transform = function(_, pulse) {
this.value = pulse.source;
return pulse.changed()
? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS)
: pulse.StopPropagation;
};
// CONCATENATED MODULE: ./node_modules/vega-time/src/units.js
const units_YEAR = 'year';
const units_QUARTER = 'quarter';
const units_MONTH = 'month';
const units_WEEK = 'week';
const units_DATE = 'date';
const units_DAY = 'day';
const units_HOURS = 'hours';
const units_MINUTES = 'minutes';
const units_SECONDS = 'seconds';
const units_MILLISECONDS = 'milliseconds';
const units_UNITS = [
units_YEAR,
units_QUARTER,
units_MONTH,
units_WEEK,
units_DATE,
units_DAY,
units_HOURS,
units_MINUTES,
units_SECONDS,
units_MILLISECONDS
].reduce((o, u, i) => (o[u] = 1 + i, o), {});
function units_timeUnits(units) {
const u = Object(vega_util["i" /* array */])(units).slice(),
m = {};
// check validity
if (!u.length) Object(vega_util["n" /* error */])('Missing time unit.');
u.forEach(unit => {
if (Object(vega_util["v" /* hasOwnProperty */])(units_UNITS, unit)) {
m[unit] = 1;
} else {
Object(vega_util["n" /* error */])(`Invalid time unit: ${unit}.`);
}
});
if ((m[units_WEEK] || m[units_DAY]) && (m[units_QUARTER] || m[units_MONTH] || m[units_DATE])) {
Object(vega_util["n" /* error */])(`Incompatible time units: ${units}`);
}
// ensure proper sort order
u.sort((a, b) => units_UNITS[a] - units_UNITS[b]);
return u;
}
// CONCATENATED MODULE: ./node_modules/vega-time/src/floor.js
const floor_t0 = new Date;
function floor_floor(units, step, fn, newDate) {
const s = step || 1,
b = Object(vega_util["U" /* peek */])(units),
_ = (unit, p, key) => floor_skip(fn[key || unit], unit === b && s, p);
const t = new Date,
u = Object(vega_util["Da" /* toSet */])(units),
y = u[units_YEAR] ? _(units_YEAR) : Object(vega_util["l" /* constant */])(2012),
m = u[units_MONTH] ? _(units_MONTH)
: u[units_QUARTER] ? _(units_QUARTER)
: vega_util["Ka" /* zero */],
d = u[units_WEEK] && u[units_DAY] ? _(units_DAY, 1, units_WEEK + units_DAY)
: u[units_WEEK] ? _(units_WEEK, 1)
: u[units_DAY] ? _(units_DAY, 1)
: u[units_DATE] ? _(units_DATE, 1)
: vega_util["O" /* one */],
H = u[units_HOURS] ? _(units_HOURS) : vega_util["Ka" /* zero */],
M = u[units_MINUTES] ? _(units_MINUTES) : vega_util["Ka" /* zero */],
S = u[units_SECONDS] ? _(units_SECONDS) : vega_util["Ka" /* zero */],
L = u[units_MILLISECONDS] ? _(units_MILLISECONDS) : vega_util["Ka" /* zero */];
return function(v) {
t.setTime(+v);
const year = y(t);
return newDate(year, m(t), d(t, year), H(t), M(t), S(t), L(t));
};
}
function floor_skip(f, step, phase) {
return step <= 1 ? f
: phase ? (d, y) => phase + step * Math.floor((f(d, y) - phase) / step)
: (d, y) => step * Math.floor(f(d, y) / step);
}
// returns the day of the year based on week number, day of week,
// and the day of the week for the first day of the year
function floor_weekday(week, day, firstDay) {
return day + week * 7 - (firstDay + 6) % 7;
}
// -- LOCAL TIME --
const floor_localGet = {
[units_YEAR]: d => d.getFullYear(),
[units_QUARTER]: d => 3 * ~~(d.getMonth() / 3),
[units_MONTH]: d => d.getMonth(),
[units_DATE]: d => d.getDate(),
[units_HOURS]: d => d.getHours(),
[units_MINUTES]: d => d.getMinutes(),
[units_SECONDS]: d => d.getSeconds(),
[units_MILLISECONDS]: d => d.getMilliseconds(),
[units_DAY]: (d, y) => floor_weekday(1, d.getDay(), floor_localFirst(y)),
[units_WEEK]: (d, y) => floor_weekday(floor_localWeekNum(d), 0, floor_localFirst(y)),
[units_WEEK + units_DAY]: (d, y) => floor_weekday(floor_localWeekNum(d), d.getDay(), floor_localFirst(y))
};
function floor_localYear(y) {
floor_t0.setFullYear(y);
floor_t0.setMonth(0);
floor_t0.setDate(1);
floor_t0.setHours(0, 0, 0, 0);
return floor_t0;
}
function floor_localWeekNum(d) {
return week_sunday.count(floor_localYear(d.getFullYear()) - 1, d);
}
function floor_localFirst(y) {
return floor_localYear(y).getDay();
}
function floor_localDate(y, m, d, H, M, S, L) {
if (0 <= y && y < 100) {
var date = new Date(-1, m, d, H, M, S, L);
date.setFullYear(y);
return date;
}
return new Date(y, m, d, H, M, S, L);
}
function floor_timeFloor(units, step) {
return floor_floor(units, step || 1, floor_localGet, floor_localDate);
}
// -- UTC TIME --
const floor_utcGet = {
[units_YEAR]: d => d.getUTCFullYear(),
[units_QUARTER]: d => 3 * ~~(d.getUTCMonth() / 3),
[units_MONTH]: d => d.getUTCMonth(),
[units_DATE]: d => d.getUTCDate(),
[units_HOURS]: d => d.getUTCHours(),
[units_MINUTES]: d => d.getUTCMinutes(),
[units_SECONDS]: d => d.getUTCSeconds(),
[units_MILLISECONDS]: d => d.getUTCMilliseconds(),
[units_DAY]: (d, y) => floor_weekday(1, d.getUTCDay(), floor_utcFirst(y)),
[units_WEEK]: (d, y) => floor_weekday(floor_utcWeekNum(d), 0, floor_utcFirst(y)),
[units_WEEK + units_DAY]: (d, y) => floor_weekday(floor_utcWeekNum(d), d.getUTCDay(), floor_utcFirst(y))
};
function floor_utcWeekNum(d) {
const y = Date.UTC(d.getUTCFullYear(), 0, 1);
return utcWeek_utcSunday.count(y - 1, d);
}
function floor_utcFirst(y) {
floor_t0.setTime(Date.UTC(y, 0, 1));
return floor_t0.getUTCDay();
}
function floor_utcDate(y, m, d, H, M, S, L) {
if (0 <= y && y < 100) {
var date = new Date(Date.UTC(-1, m, d, H, M, S, L));
date.setUTCFullYear(d.y);
return date;
}
return new Date(Date.UTC(y, m, d, H, M, S, L));
}
function floor_utcFloor(units, step) {
return floor_floor(units, step || 1, floor_utcGet, floor_utcDate);
}
// CONCATENATED MODULE: ./node_modules/d3-time/src/month.js
var month_month = newInterval(function(date) {
date.setDate(1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setMonth(date.getMonth() + step);
}, function(start, end) {
return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
return date.getMonth();
});
/* harmony default export */ var src_month = (month_month);
var month_months = month_month.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/hour.js
var hour_hour = newInterval(function(date) {
date.setTime(date - date.getMilliseconds() - date.getSeconds() * duration_durationSecond - date.getMinutes() * duration_durationMinute);
}, function(date, step) {
date.setTime(+date + step * duration_durationHour);
}, function(start, end) {
return (end - start) / duration_durationHour;
}, function(date) {
return date.getHours();
});
/* harmony default export */ var src_hour = (hour_hour);
var hour_hours = hour_hour.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/minute.js
var minute_minute = newInterval(function(date) {
date.setTime(date - date.getMilliseconds() - date.getSeconds() * duration_durationSecond);
}, function(date, step) {
date.setTime(+date + step * duration_durationMinute);
}, function(start, end) {
return (end - start) / duration_durationMinute;
}, function(date) {
return date.getMinutes();
});
/* harmony default export */ var src_minute = (minute_minute);
var minute_minutes = minute_minute.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/second.js
var second_second = newInterval(function(date) {
date.setTime(date - date.getMilliseconds());
}, function(date, step) {
date.setTime(+date + step * duration_durationSecond);
}, function(start, end) {
return (end - start) / duration_durationSecond;
}, function(date) {
return date.getUTCSeconds();
});
/* harmony default export */ var src_second = (second_second);
var second_seconds = second_second.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/millisecond.js
var millisecond_millisecond = newInterval(function() {
// noop
}, function(date, step) {
date.setTime(+date + step);
}, function(start, end) {
return end - start;
});
// An optimized implementation for this simple case.
millisecond_millisecond.every = function(k) {
k = Math.floor(k);
if (!isFinite(k) || !(k > 0)) return null;
if (!(k > 1)) return millisecond_millisecond;
return newInterval(function(date) {
date.setTime(Math.floor(date / k) * k);
}, function(date, step) {
date.setTime(+date + step * k);
}, function(start, end) {
return (end - start) / k;
});
};
/* harmony default export */ var src_millisecond = (millisecond_millisecond);
var millisecond_milliseconds = millisecond_millisecond.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/utcMonth.js
var utcMonth_utcMonth = newInterval(function(date) {
date.setUTCDate(1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
return date.getUTCMonth();
});
/* harmony default export */ var src_utcMonth = (utcMonth_utcMonth);
var utcMonth_utcMonths = utcMonth_utcMonth.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/utcHour.js
var utcHour_utcHour = newInterval(function(date) {
date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
date.setTime(+date + step * duration_durationHour);
}, function(start, end) {
return (end - start) / duration_durationHour;
}, function(date) {
return date.getUTCHours();
});
/* harmony default export */ var src_utcHour = (utcHour_utcHour);
var utcHour_utcHours = utcHour_utcHour.range;
// CONCATENATED MODULE: ./node_modules/d3-time/src/utcMinute.js
var utcMinute_utcMinute = newInterval(function(date) {
date.setUTCSeconds(0, 0);
}, function(date, step) {
date.setTime(+date + step * duration_durationMinute);
}, function(start, end) {
return (end - start) / duration_durationMinute;
}, function(date) {
return date.getUTCMinutes();
});
/* harmony default export */ var src_utcMinute = (utcMinute_utcMinute);
var utcMinute_utcMinutes = utcMinute_utcMinute.range;
// CONCATENATED MODULE: ./node_modules/vega-time/src/interval.js
const interval_timeIntervals = {
[units_YEAR]: src_year,
[units_QUARTER]: src_month.every(3),
[units_MONTH]: src_month,
[units_WEEK]: week_sunday,
[units_DATE]: src_day,
[units_DAY]: src_day,
[units_HOURS]: src_hour,
[units_MINUTES]: src_minute,
[units_SECONDS]: src_second,
[units_MILLISECONDS]: src_millisecond
};
const interval_utcIntervals = {
[units_YEAR]: src_utcYear,
[units_QUARTER]: src_utcMonth.every(3),
[units_MONTH]: src_utcMonth,
[units_WEEK]: utcWeek_utcSunday,
[units_DATE]: src_utcDay,
[units_DAY]: src_utcDay,
[units_HOURS]: src_utcHour,
[units_MINUTES]: src_utcMinute,
[units_SECONDS]: src_second,
[units_MILLISECONDS]: src_millisecond
};
function interval_timeInterval(unit) {
return interval_timeIntervals[unit];
}
function interval_utcInterval(unit) {
return interval_utcIntervals[unit];
}
function interval_offset(ival, date, step) {
return ival ? ival.offset(date, step) : undefined;
}
function interval_timeOffset(unit, date, step) {
return interval_offset(interval_timeInterval(unit), date, step);
}
function interval_utcOffset(unit, date, step) {
return interval_offset(interval_utcInterval(unit), date, step);
}
function interval_sequence(ival, start, stop, step) {
return ival ? ival.range(start, stop, step) : undefined;
}
function interval_timeSequence(unit, start, stop, step) {
return interval_sequence(interval_timeInterval(unit), start, stop, step);
}
function interval_utcSequence(unit, start, stop, step) {
return interval_sequence(interval_utcInterval(unit), start, stop, step);
}
// CONCATENATED MODULE: ./node_modules/vega-time/src/format.js
const format_defaultSpecifiers = {
[units_YEAR]: '%Y ',
[units_QUARTER]: 'Q%q ',
[units_MONTH]: '%b ',
[units_DATE]: '%d ',
[units_WEEK]: 'W%U ',
[units_DAY]: '%a ',
[units_HOURS]: '%H:00',
[units_MINUTES]: '00:%M',
[units_SECONDS]: ':%S',
[units_MILLISECONDS]: '.%L',
[`${units_YEAR}-${units_MONTH}`]: '%Y-%m ',
[`${units_YEAR}-${units_MONTH}-${units_DATE}`]: '%Y-%m-%d ',
[`${units_HOURS}-${units_MINUTES}`]: '%H:%M'
}
function format_timeUnitSpecifier(units, specifiers) {
const s = Object(vega_util["o" /* extend */])({}, format_defaultSpecifiers, specifiers),
u = units_timeUnits(units),
n = u.length;
let fmt = '', start = 0, end, key;
for (start=0; start<n; ) {
for (end=u.length; end > start; --end) {
key = u.slice(start, end).join('-');
if (s[key] != null) {
fmt += s[key];
start = end;
break;
}
}
}
return fmt.trim();
}
function format_timeFormat(specifier) {
return format_formatter(defaultLocale_timeFormat, interval_timeInterval, specifier);
}
function format_utcFormat(specifier) {
return format_formatter(defaultLocale_utcFormat, interval_utcInterval, specifier);
}
function format_formatter(format, interval, specifier) {
return Object(vega_util["H" /* isString */])(specifier)
? format(specifier)
: format_multiFormat(format, interval, specifier);
}
function format_multiFormat(format, interval, spec) {
spec = spec || {};
if (!Object(vega_util["F" /* isObject */])(spec)) {
Object(vega_util["n" /* error */])(`Invalid time multi-format specifier: ${spec}`);
}
const second = interval(units_SECONDS),
minute = interval(units_MINUTES),
hour = interval(units_HOURS),
day = interval(units_DATE),
week = interval(units_WEEK),
month = interval(units_MONTH),
quarter = interval(units_QUARTER),
year = interval(units_YEAR),
L = format(spec[units_MILLISECONDS] || '.%L'),
S = format(spec[units_SECONDS] || ':%S'),
M = format(spec[units_MINUTES] || '%I:%M'),
H = format(spec[units_HOURS] || '%I %p'),
d = format(spec[units_DATE] || spec[units_DAY] || '%a %d'),
w = format(spec[units_WEEK] || '%b %d'),
m = format(spec[units_MONTH] || '%B'),
q = format(spec[units_QUARTER] || '%B'),
y = format(spec[units_YEAR] || '%Y');
return function(date) {
return (second(date) < date ? L
: minute(date) < date ? S
: hour(date) < date ? M
: day(date) < date ? H
: month(date) < date ? (week(date) < date ? d : w)
: year(date) < date ? (quarter(date) < date ? m : q)
: y)(date);
};
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/bisector.js
/* harmony default export */ var bisector = (function(compare) {
if (compare.length === 1) compare = bisector_ascendingComparator(compare);
return {
left: function(a, x, lo, hi) {
if (lo == null) lo = 0;
if (hi == null) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
},
right: function(a, x, lo, hi) {
if (lo == null) lo = 0;
if (hi == null) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) > 0) hi = mid;
else lo = mid + 1;
}
return lo;
}
};
});
function bisector_ascendingComparator(f) {
return function(d, x) {
return src_ascending(f(d), x);
};
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/ticks.js
var e10 = Math.sqrt(50),
e5 = Math.sqrt(10),
e2 = Math.sqrt(2);
/* harmony default export */ var src_ticks = (function(start, stop, count) {
var reverse,
i = -1,
n,
ticks,
step;
stop = +stop, start = +start, count = +count;
if (start === stop && count > 0) return [start];
if (reverse = stop < start) n = start, start = stop, stop = n;
if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];
if (step > 0) {
start = Math.ceil(start / step);
stop = Math.floor(stop / step);
ticks = new Array(n = Math.ceil(stop - start + 1));
while (++i < n) ticks[i] = (start + i) * step;
} else {
start = Math.floor(start * step);
stop = Math.ceil(stop * step);
ticks = new Array(n = Math.ceil(start - stop + 1));
while (++i < n) ticks[i] = (start - i) / step;
}
if (reverse) ticks.reverse();
return ticks;
});
function tickIncrement(start, stop, count) {
var step = (stop - start) / Math.max(0, count),
power = Math.floor(Math.log(step) / Math.LN10),
error = step / Math.pow(10, power);
return power >= 0
? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)
: -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}
function tickStep(start, stop, count) {
var step0 = Math.abs(stop - start) / Math.max(0, count),
step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
error = step0 / step1;
if (error >= e10) step1 *= 10;
else if (error >= e5) step1 *= 5;
else if (error >= e2) step1 *= 2;
return stop < start ? -step1 : step1;
}
// CONCATENATED MODULE: ./node_modules/vega-time/src/bin.js
const bin_durationSecond = 1000,
bin_durationMinute = bin_durationSecond * 60,
bin_durationHour = bin_durationMinute * 60,
bin_durationDay = bin_durationHour * 24,
bin_durationWeek = bin_durationDay * 7,
bin_durationMonth = bin_durationDay * 30,
bin_durationYear = bin_durationDay * 365;
const bin_Milli = [units_YEAR, units_MONTH, units_DATE, units_HOURS, units_MINUTES, units_SECONDS, units_MILLISECONDS],
bin_Seconds = bin_Milli.slice(0, -1),
bin_Minutes = bin_Seconds.slice(0, -1),
bin_Hours = bin_Minutes.slice(0, -1),
bin_Day = bin_Hours.slice(0, -1),
bin_Week = [units_YEAR, units_WEEK],
bin_Month = [units_YEAR, units_MONTH],
bin_Year = [units_YEAR];
const bin_intervals = [
[bin_Seconds, 1, bin_durationSecond],
[bin_Seconds, 5, 5 * bin_durationSecond],
[bin_Seconds, 15, 15 * bin_durationSecond],
[bin_Seconds, 30, 30 * bin_durationSecond],
[bin_Minutes, 1, bin_durationMinute],
[bin_Minutes, 5, 5 * bin_durationMinute],
[bin_Minutes, 15, 15 * bin_durationMinute],
[bin_Minutes, 30, 30 * bin_durationMinute],
[ bin_Hours, 1, bin_durationHour ],
[ bin_Hours, 3, 3 * bin_durationHour ],
[ bin_Hours, 6, 6 * bin_durationHour ],
[ bin_Hours, 12, 12 * bin_durationHour ],
[ bin_Day, 1, bin_durationDay ],
[ bin_Week, 1, bin_durationWeek ],
[ bin_Month, 1, bin_durationMonth ],
[ bin_Month, 3, 3 * bin_durationMonth ],
[ bin_Year, 1, bin_durationYear ]
];
/* harmony default export */ var vega_time_src_bin = (function(opt) {
const ext = opt.extent,
max = opt.maxbins || 40,
target = Math.abs(Object(vega_util["X" /* span */])(ext)) / max;
let i = bisector(i => i[2]).right(bin_intervals, target),
units, step;
if (i === bin_intervals.length) {
units = bin_Year,
step = tickStep(ext[0] / bin_durationYear, ext[1] / bin_durationYear, max);
} else if (i) {
i = bin_intervals[target / bin_intervals[i - 1][2] < bin_intervals[i][2] / target ? i - 1 : i];
units = i[0];
step = i[1];
} else {
units = bin_Milli;
step = Math.max(tickStep(ext[0], ext[1], max), 1);
}
return {units, step};
});
// CONCATENATED MODULE: ./node_modules/vega-time/index.js
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/TimeUnit.js
/**
* Discretize dates to specific time units.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The data field containing date/time values.
*/
function TimeUnit_TimeUnit(params) {
Transform_Transform.call(this, null, params);
}
const TimeUnit_OUTPUT = ['unit0', 'unit1'];
TimeUnit_TimeUnit.Definition = {
"type": "TimeUnit",
"metadata": {"modifies": true},
"params": [
{ "name": "field", "type": "field", "required": true },
{ "name": "interval", "type": "boolean", "default": true },
{ "name": "units", "type": "string", "array": true },
{ "name": "step", "type": "number", "default": 1 },
{ "name": "maxbins", "type": "number", "default": 40 },
{ "name": "extent", "type": "date", "array": true},
{ "name": "timezone", "type": "enum", "default": "local", "values": ["local", "utc"] },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": TimeUnit_OUTPUT }
]
};
var TimeUnit_prototype = Object(vega_util["y" /* inherits */])(TimeUnit_TimeUnit, Transform_Transform);
TimeUnit_prototype.transform = function(_, pulse) {
var field = _.field,
band = _.interval !== false,
utc = _.timezone === 'utc',
floor = this._floor(_, pulse),
offset = (utc ? interval_utcInterval : interval_timeInterval)(floor.unit).offset,
as = _.as || TimeUnit_OUTPUT,
u0 = as[0],
u1 = as[1],
min = floor.start || Infinity,
max = floor.stop || -Infinity,
step = floor.step,
flag = pulse.ADD;
if (_.modified() || pulse.modified(Object(vega_util["g" /* accessorFields */])(field))) {
pulse = pulse.reflow(true);
flag = pulse.SOURCE;
min = Infinity;
max = -Infinity;
}
pulse.visit(flag, function(t) {
var v = field(t), a, b;
if (v == null) {
t[u0] = null;
if (band) t[u1] = null;
} else {
t[u0] = a = b = floor(v);
if (band) t[u1] = b = offset(a, step);
if (a < min) min = a;
if (b > max) max = b;
}
});
floor.start = min;
floor.stop = max;
return pulse.modifies(band ? as : u0);
};
TimeUnit_prototype._floor = function(_, pulse) {
const utc = _.timezone === 'utc';
// get parameters
let {units, step} = _.units
? {units: _.units, step: _.step || 1}
: vega_time_src_bin({
extent: _.extent || Object(vega_util["p" /* extent */])(pulse.materialize(pulse.SOURCE).source, _.field),
maxbins: _.maxbins
});
// check / standardize time units
units = units_timeUnits(units);
const prev = this.value || {},
floor = (utc ? floor_utcFloor : floor_timeFloor)(units, step);
floor.unit = Object(vega_util["U" /* peek */])(units);
floor.units = units;
floor.step = step;
floor.start = prev.start;
floor.stop = prev.stop;
return this.value = floor;
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/TupleIndex.js
/**
* An index that maps from unique, string-coerced, field values to tuples.
* Assumes that the field serves as a unique key with no duplicate values.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The field accessor to index.
*/
function TupleIndex_TupleIndex(params) {
Transform_Transform.call(this, Object(vega_util["s" /* fastmap */])(), params);
}
var TupleIndex_prototype = Object(vega_util["y" /* inherits */])(TupleIndex_TupleIndex, Transform_Transform);
TupleIndex_prototype.transform = function(_, pulse) {
var df = pulse.dataflow,
field = _.field,
index = this.value,
mod = true;
function set(t) { index.set(field(t), t); }
if (_.modified('field') || pulse.modified(field.fields)) {
index.clear();
pulse.visit(pulse.SOURCE, set);
} else if (pulse.changed()) {
pulse.visit(pulse.REM, function(t) { index.delete(field(t)); });
pulse.visit(pulse.ADD, set);
} else {
mod = false;
}
this.modified(mod);
if (index.empty > df.cleanThreshold) df.runAfter(index.clean);
return pulse.fork();
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Values.js
/**
* Extracts an array of values. Assumes the source data has already been
* reduced as needed (e.g., by an upstream Aggregate transform).
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The domain field to extract.
* @param {function(*,*): number} [params.sort] - An optional
* comparator function for sorting the values. The comparator will be
* applied to backing tuples prior to value extraction.
*/
function Values_Values(params) {
Transform_Transform.call(this, null, params);
}
var Values_prototype = Object(vega_util["y" /* inherits */])(Values_Values, Transform_Transform);
Values_prototype.transform = function(_, pulse) {
var run = !this.value
|| _.modified('field')
|| _.modified('sort')
|| pulse.changed()
|| (_.sort && pulse.modified(_.sort.fields));
if (run) {
this.value = (_.sort
? pulse.source.slice().sort(stableCompare(_.sort))
: pulse.source).map(_.field);
}
};
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/WindowOps.js
function WindowOps_WindowOp(op, field, param, as) {
let fn = WindowOps_WindowOps[op](field, param);
return {
init: fn.init || vega_util["Ka" /* zero */],
update: function(w, t) { t[as] = fn.next(w); }
};
}
const WindowOps_WindowOps = {
row_number: function() {
return {
next: w => w.index + 1
};
},
rank: function() {
let rank;
return {
init: () => rank = 1,
next: w => {
let i = w.index,
data = w.data;
return (i && w.compare(data[i - 1], data[i])) ? (rank = i + 1) : rank;
}
};
},
dense_rank: function() {
let drank;
return {
init: () => drank = 1,
next: w => {
let i = w.index,
d = w.data;
return (i && w.compare(d[i - 1], d[i])) ? ++drank : drank;
}
};
},
percent_rank: function() {
let rank = WindowOps_WindowOps.rank(),
next = rank.next;
return {
init: rank.init,
next: w => (next(w) - 1) / (w.data.length - 1)
};
},
cume_dist: function() {
let cume;
return {
init: () => cume = 0,
next: w => {
let i = w.index,
d = w.data,
c = w.compare;
if (cume < i) {
while (i + 1 < d.length && !c(d[i], d[i + 1])) ++i;
cume = i;
}
return (1 + cume) / d.length;
}
};
},
ntile: function(field, num) {
num = +num;
if (!(num > 0)) Object(vega_util["n" /* error */])('ntile num must be greater than zero.');
let cume = WindowOps_WindowOps.cume_dist(),
next = cume.next;
return {
init: cume.init,
next: w => Math.ceil(num * next(w))
};
},
lag: function(field, offset) {
offset = +offset || 1;
return {
next: w => {
let i = w.index - offset;
return i >= 0 ? field(w.data[i]) : null;
}
};
},
lead: function(field, offset) {
offset = +offset || 1;
return {
next: w => {
let i = w.index + offset,
d = w.data;
return i < d.length ? field(d[i]) : null;
}
};
},
first_value: function(field) {
return {
next: w => field(w.data[w.i0])
};
},
last_value: function(field) {
return {
next: w => field(w.data[w.i1 - 1])
}
},
nth_value: function(field, nth) {
nth = +nth;
if (!(nth > 0)) Object(vega_util["n" /* error */])('nth_value nth must be greater than zero.');
return {
next: w => {
let i = w.i0 + (nth - 1);
return i < w.i1 ? field(w.data[i]) : null;
}
}
},
prev_value: function(field) {
let prev;
return {
init: () => prev = null,
next: w => {
let v = field(w.data[w.index]);
return v != null ? (prev = v) : prev;
}
}
},
next_value: function(field) {
let v, i;
return {
init: () => (v = null, i = -1),
next: w => {
let d = w.data;
return w.index <= i ? v
: (i = WindowOps_find(field, d, w.index)) < 0
? (i = d.length, v = null)
: (v = field(d[i]));
}
};
},
};
function WindowOps_find(field, data, index) {
for (let n = data.length; index < n; ++index) {
let v = field(data[index]);
if (v != null) return index;
}
return -1;
}
var WindowOps_ValidWindowOps = Object.keys(WindowOps_WindowOps);
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/util/WindowState.js
function WindowState_WindowState(_) {
let self = this,
ops = Object(vega_util["i" /* array */])(_.ops),
fields = Object(vega_util["i" /* array */])(_.fields),
params = Object(vega_util["i" /* array */])(_.params),
as = Object(vega_util["i" /* array */])(_.as),
outputs = self.outputs = [],
windows = self.windows = [],
inputs = {},
map = {},
countOnly = true,
counts = [],
measures = [];
function visitInputs(f) {
Object(vega_util["i" /* array */])(Object(vega_util["g" /* accessorFields */])(f)).forEach(_ => inputs[_] = 1);
}
visitInputs(_.sort);
ops.forEach(function(op, i) {
let field = fields[i],
mname = Object(vega_util["h" /* accessorName */])(field),
name = AggregateOps_measureName(op, mname, as[i]);
visitInputs(field);
outputs.push(name);
// Window operation
if (Object(vega_util["v" /* hasOwnProperty */])(WindowOps_WindowOps, op)) {
windows.push(WindowOps_WindowOp(op, fields[i], params[i], name));
}
// Aggregate operation
else {
if (field == null && op !== 'count') {
Object(vega_util["n" /* error */])('Null aggregate field specified.');
}
if (op === 'count') {
counts.push(name);
return;
}
countOnly = false;
let m = map[mname];
if (!m) {
m = (map[mname] = []);
m.field = field;
measures.push(m);
}
m.push(AggregateOps_createMeasure(op, name));
}
});
if (counts.length || measures.length) {
self.cell = WindowState_cell(measures, counts, countOnly);
}
self.inputs = Object.keys(inputs);
}
const WindowState_prototype = WindowState_WindowState.prototype;
WindowState_prototype.init = function() {
this.windows.forEach(_ => _.init());
if (this.cell) this.cell.init();
};
WindowState_prototype.update = function(w, t) {
let self = this,
cell = self.cell,
wind = self.windows,
data = w.data,
m = wind && wind.length,
j;
if (cell) {
for (j=w.p0; j<w.i0; ++j) cell.rem(data[j]);
for (j=w.p1; j<w.i1; ++j) cell.add(data[j]);
cell.set(t);
}
for (j=0; j<m; ++j) wind[j].update(w, t);
};
function WindowState_cell(measures, counts, countOnly) {
measures = measures.map(m => AggregateOps_compileMeasures(m, m.field));
let cell = {
num: 0,
agg: null,
store: false,
count: counts
};
if (!countOnly) {
var n = measures.length,
a = cell.agg = Array(n),
i = 0;
for (; i<n; ++i) a[i] = new measures[i](cell);
}
if (cell.store) {
var store = cell.data = new TupleStore_TupleStore();
}
cell.add = function(t) {
cell.num += 1;
if (countOnly) return;
if (store) store.add(t);
for (let i=0; i<n; ++i) {
a[i].add(a[i].get(t), t);
}
};
cell.rem = function(t) {
cell.num -= 1;
if (countOnly) return;
if (store) store.rem(t);
for (let i=0; i<n; ++i) {
a[i].rem(a[i].get(t), t);
}
};
cell.set = function(t) {
let i, n;
// consolidate stored values
if (store) store.values();
// update tuple properties
for (i=0, n=counts.length; i<n; ++i) t[counts[i]] = cell.num;
if (!countOnly) for (i=0, n=a.length; i<n; ++i) a[i].set(t);
};
cell.init = function() {
cell.num = 0;
if (store) store.reset();
for (let i=0; i<n; ++i) a[i].init();
};
return cell;
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/src/Window.js
/**
* Perform window calculations and write results to the input stream.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(*,*): number} [params.sort] - A comparator function for sorting tuples within a window.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors by which to partition tuples into separate windows.
* @param {Array<string>} params.ops - An array of strings indicating window operations to perform.
* @param {Array<function(object): *>} [params.fields] - An array of accessors
* for data fields to use as inputs to window operations.
* @param {Array<*>} [params.params] - An array of parameter values for window operations.
* @param {Array<string>} [params.as] - An array of output field names for window operations.
* @param {Array<number>} [params.frame] - Window frame definition as two-element array.
* @param {boolean} [params.ignorePeers=false] - If true, base window frame boundaries on row
* number alone, ignoring peers with identical sort values. If false (default),
* the window boundaries will be adjusted to include peer values.
*/
function Window_Window(params) {
Transform_Transform.call(this, {}, params);
this._mlen = 0;
this._mods = [];
}
Window_Window.Definition = {
"type": "Window",
"metadata": {"modifies": true},
"params": [
{ "name": "sort", "type": "compare" },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "ops", "type": "enum", "array": true, "values": WindowOps_ValidWindowOps.concat(AggregateOps_ValidAggregateOps) },
{ "name": "params", "type": "number", "null": true, "array": true },
{ "name": "fields", "type": "field", "null": true, "array": true },
{ "name": "as", "type": "string", "null": true, "array": true },
{ "name": "frame", "type": "number", "null": true, "array": true, "length": 2, "default": [null, 0] },
{ "name": "ignorePeers", "type": "boolean", "default": false }
]
};
var Window_prototype = Object(vega_util["y" /* inherits */])(Window_Window, Transform_Transform);
Window_prototype.transform = function(_, pulse) {
var self = this,
state = self.state,
mod = _.modified(),
cmp = stableCompare(_.sort),
i, n;
this.stamp = pulse.stamp;
// initialize window state
if (!state || mod) {
state = self.state = new WindowState_WindowState(_);
}
// retrieve group for a tuple
var key = groupkey(_.groupby);
function group(t) { return self.group(key(t)); }
// partition input tuples
if (mod || pulse.modified(state.inputs)) {
self.value = {};
pulse.visit(pulse.SOURCE, function(t) { group(t).add(t); });
} else {
pulse.visit(pulse.REM, function(t) { group(t).remove(t); });
pulse.visit(pulse.ADD, function(t) { group(t).add(t); });
}
// perform window calculations for each modified partition
for (i=0, n=self._mlen; i<n; ++i) {
Window_processPartition(self._mods[i], state, cmp, _);
}
self._mlen = 0;
self._mods = [];
// TODO don't reflow everything?
return pulse.reflow(mod).modifies(state.outputs);
};
Window_prototype.group = function(key) {
var self = this,
group = self.value[key];
if (!group) {
group = self.value[key] = SortedList(tupleid);
group.stamp = -1;
}
if (group.stamp < self.stamp) {
group.stamp = self.stamp;
self._mods[self._mlen++] = group;
}
return group;
};
function Window_processPartition(list, state, cmp, _) {
var sort = _.sort,
range = sort && !_.ignorePeers,
frame = _.frame || [null, 0],
data = list.data(cmp), // use cmp for stable sort
n = data.length,
i = 0,
b = range ? bisector(sort) : null,
w = {
i0: 0, i1: 0, p0: 0, p1: 0, index: 0,
data: data, compare: sort || Object(vega_util["l" /* constant */])(-1)
};
for (state.init(); i<n; ++i) {
Window_setWindow(w, frame, i, n);
if (range) Window_adjustRange(w, b);
state.update(w, data[i]);
}
}
function Window_setWindow(w, f, i, n) {
w.p0 = w.i0;
w.p1 = w.i1;
w.i0 = f[0] == null ? 0 : Math.max(0, i - Math.abs(f[0]));
w.i1 = f[1] == null ? n : Math.min(n, i + Math.abs(f[1]) + 1);
w.index = i;
}
// if frame type is 'range', adjust window for peer values
function Window_adjustRange(w, bisect) {
var r0 = w.i0,
r1 = w.i1 - 1,
c = w.compare,
d = w.data,
n = d.length - 1;
if (r0 > 0 && !c(d[r0], d[r0-1])) w.i0 = bisect.left(d, d[r0]);
if (r1 < n && !c(d[r1], d[r1+1])) w.i1 = bisect.right(d, d[r1]);
}
// CONCATENATED MODULE: ./node_modules/vega-transforms/index.js
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/constants.js
const Top = 'top';
const Left = 'left';
const Right = 'right';
const Bottom = 'bottom';
const TopLeft = 'top-left';
const TopRight = 'top-right';
const BottomLeft = 'bottom-left';
const BottomRight = 'bottom-right';
const Start = 'start';
const Middle = 'middle';
const End = 'end';
const constants_X = 'x';
const constants_Y = 'y';
const Group = 'group';
const AxisRole = 'axis';
const TitleRole = 'title';
const FrameRole = 'frame';
const ScopeRole = 'scope';
const LegendRole = 'legend';
const RowHeader = 'row-header';
const RowFooter = 'row-footer';
const RowTitle = 'row-title';
const ColHeader = 'column-header';
const ColFooter = 'column-footer';
const ColTitle = 'column-title';
const Padding = 'padding';
const Symbols = 'symbol';
const Fit = 'fit';
const FitX = 'fit-x';
const FitY = 'fit-y';
const Pad = 'pad';
const constants_None = 'none';
const All = 'all';
const Each = 'each';
const Flush = 'flush';
const Column = 'column';
const Row = 'row';
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/Bounds.js
function Bounds(b) {
this.clear();
if (b) this.union(b);
}
var Bounds_prototype = Bounds.prototype;
Bounds_prototype.clone = function() {
return new Bounds(this);
};
Bounds_prototype.clear = function() {
this.x1 = +Number.MAX_VALUE;
this.y1 = +Number.MAX_VALUE;
this.x2 = -Number.MAX_VALUE;
this.y2 = -Number.MAX_VALUE;
return this;
};
Bounds_prototype.empty = function() {
return (
this.x1 === +Number.MAX_VALUE &&
this.y1 === +Number.MAX_VALUE &&
this.x2 === -Number.MAX_VALUE &&
this.y2 === -Number.MAX_VALUE
);
};
Bounds_prototype.equals = function(b) {
return (
this.x1 === b.x1 &&
this.y1 === b.y1 &&
this.x2 === b.x2 &&
this.y2 === b.y2
);
};
Bounds_prototype.set = function(x1, y1, x2, y2) {
if (x2 < x1) {
this.x2 = x1;
this.x1 = x2;
} else {
this.x1 = x1;
this.x2 = x2;
}
if (y2 < y1) {
this.y2 = y1;
this.y1 = y2;
} else {
this.y1 = y1;
this.y2 = y2;
}
return this;
};
Bounds_prototype.add = function(x, y) {
if (x < this.x1) this.x1 = x;
if (y < this.y1) this.y1 = y;
if (x > this.x2) this.x2 = x;
if (y > this.y2) this.y2 = y;
return this;
};
Bounds_prototype.expand = function(d) {
this.x1 -= d;
this.y1 -= d;
this.x2 += d;
this.y2 += d;
return this;
};
Bounds_prototype.round = function() {
this.x1 = Math.floor(this.x1);
this.y1 = Math.floor(this.y1);
this.x2 = Math.ceil(this.x2);
this.y2 = Math.ceil(this.y2);
return this;
};
Bounds_prototype.scale = function(s) {
this.x1 *= s;
this.y1 *= s;
this.x2 *= s;
this.y2 *= s;
return this;
};
Bounds_prototype.translate = function(dx, dy) {
this.x1 += dx;
this.x2 += dx;
this.y1 += dy;
this.y2 += dy;
return this;
};
Bounds_prototype.rotate = function(angle, x, y) {
const p = this.rotatedPoints(angle, x, y);
return this.clear()
.add(p[0], p[1])
.add(p[2], p[3])
.add(p[4], p[5])
.add(p[6], p[7]);
};
Bounds_prototype.rotatedPoints = function(angle, x, y) {
var {x1, y1, x2, y2} = this,
cos = Math.cos(angle),
sin = Math.sin(angle),
cx = x - x*cos + y*sin,
cy = y - x*sin - y*cos;
return [
cos*x1 - sin*y1 + cx, sin*x1 + cos*y1 + cy,
cos*x1 - sin*y2 + cx, sin*x1 + cos*y2 + cy,
cos*x2 - sin*y1 + cx, sin*x2 + cos*y1 + cy,
cos*x2 - sin*y2 + cx, sin*x2 + cos*y2 + cy
];
};
Bounds_prototype.union = function(b) {
if (b.x1 < this.x1) this.x1 = b.x1;
if (b.y1 < this.y1) this.y1 = b.y1;
if (b.x2 > this.x2) this.x2 = b.x2;
if (b.y2 > this.y2) this.y2 = b.y2;
return this;
};
Bounds_prototype.intersect = function(b) {
if (b.x1 > this.x1) this.x1 = b.x1;
if (b.y1 > this.y1) this.y1 = b.y1;
if (b.x2 < this.x2) this.x2 = b.x2;
if (b.y2 < this.y2) this.y2 = b.y2;
return this;
};
Bounds_prototype.encloses = function(b) {
return b && (
this.x1 <= b.x1 &&
this.x2 >= b.x2 &&
this.y1 <= b.y1 &&
this.y2 >= b.y2
);
};
Bounds_prototype.alignsWith = function(b) {
return b && (
this.x1 == b.x1 ||
this.x2 == b.x2 ||
this.y1 == b.y1 ||
this.y2 == b.y2
);
};
Bounds_prototype.intersects = function(b) {
return b && !(
this.x2 < b.x1 ||
this.x1 > b.x2 ||
this.y2 < b.y1 ||
this.y1 > b.y2
);
};
Bounds_prototype.contains = function(x, y) {
return !(
x < this.x1 ||
x > this.x2 ||
y < this.y1 ||
y > this.y2
);
};
Bounds_prototype.width = function() {
return this.x2 - this.x1;
};
Bounds_prototype.height = function() {
return this.y2 - this.y1;
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/Gradient.js
var gradient_id = 0;
const patternPrefix = 'p_';
function isGradient(value) {
return value && value.gradient;
}
function gradientRef(g, defs, base) {
let id = g.id,
type = g.gradient,
prefix = type === 'radial' ? patternPrefix : '';
// check id, assign default values as needed
if (!id) {
id = g.id = 'gradient_' + (gradient_id++);
if (type === 'radial') {
g.x1 = Gradient_get(g.x1, 0.5);
g.y1 = Gradient_get(g.y1, 0.5);
g.r1 = Gradient_get(g.r1, 0);
g.x2 = Gradient_get(g.x2, 0.5);
g.y2 = Gradient_get(g.y2, 0.5);
g.r2 = Gradient_get(g.r2, 0.5);
prefix = patternPrefix;
} else {
g.x1 = Gradient_get(g.x1, 0);
g.y1 = Gradient_get(g.y1, 0);
g.x2 = Gradient_get(g.x2, 1);
g.y2 = Gradient_get(g.y2, 0);
}
}
// register definition
defs[id] = g;
// return url reference
return 'url(' + (base || '') + '#' + prefix + id + ')';
}
function Gradient_get(val, def) {
return val != null ? val : def;
}
/* harmony default export */ var Gradient = (function(p0, p1) {
var stops = [], gradient;
return gradient = {
gradient: 'linear',
x1: p0 ? p0[0] : 0,
y1: p0 ? p0[1] : 0,
x2: p1 ? p1[0] : 1,
y2: p1 ? p1[1] : 0,
stops: stops,
stop: function(offset, color) {
stops.push({offset: offset, color: color});
return gradient;
}
};
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/Item.js
function Item_Item(mark) {
this.mark = mark;
this.bounds = (this.bounds || new Bounds());
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/GroupItem.js
function GroupItem_GroupItem(mark) {
Item_Item.call(this, mark);
this.items = (this.items || []);
}
Object(vega_util["y" /* inherits */])(GroupItem_GroupItem, Item_Item);
// CONCATENATED MODULE: ./node_modules/vega-canvas/src/domCanvas.js
function domCanvas(w, h) {
if (typeof document !== 'undefined' && document.createElement) {
var c = document.createElement('canvas');
if (c && c.getContext) {
c.width = w;
c.height = h;
return c;
}
}
return null;
}
function domImage() {
return typeof Image !== 'undefined' ? Image : null;
}
// CONCATENATED MODULE: ./node_modules/vega-canvas/index.browser.js
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/ResourceLoader.js
function ResourceLoader_ResourceLoader(customLoader) {
this._pending = 0;
this._loader = customLoader || index_browser_loader();
}
var ResourceLoader_prototype = ResourceLoader_ResourceLoader.prototype;
ResourceLoader_prototype.pending = function() {
return this._pending;
};
function ResourceLoader_increment(loader) {
loader._pending += 1;
}
function ResourceLoader_decrement(loader) {
loader._pending -= 1;
}
ResourceLoader_prototype.sanitizeURL = function(uri) {
var loader = this;
ResourceLoader_increment(loader);
return loader._loader.sanitize(uri, {context:'href'})
.then(function(opt) {
ResourceLoader_decrement(loader);
return opt;
})
.catch(function() {
ResourceLoader_decrement(loader);
return null;
});
};
ResourceLoader_prototype.loadImage = function(uri) {
const loader = this,
Image = domImage();
ResourceLoader_increment(loader);
return loader._loader
.sanitize(uri, {context: 'image'})
.then(function(opt) {
const url = opt.href;
if (!url || !Image) throw {url: url};
const img = new Image();
// set crossOrigin only if cors is defined; empty string sets anonymous mode
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/crossOrigin
const cors = Object(vega_util["v" /* hasOwnProperty */])(opt, 'crossOrigin') ? opt.crossOrigin : 'anonymous';
if (cors != null) img.crossOrigin = cors;
// attempt to load image resource
img.onload = () => ResourceLoader_decrement(loader);
img.onerror = () => ResourceLoader_decrement(loader);
img.src = url;
return img;
})
.catch(function(e) {
ResourceLoader_decrement(loader);
return {complete: false, width: 0, height: 0, src: e && e.url || ''};
});
};
ResourceLoader_prototype.ready = function() {
var loader = this;
return new Promise(function(accept) {
function poll(value) {
if (!loader.pending()) accept(value);
else setTimeout(function() { poll(true); }, 10);
}
poll(false);
});
};
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/basis.js
function basis_point(that, x, y) {
that._context.bezierCurveTo(
(2 * that._x0 + that._x1) / 3,
(2 * that._y0 + that._y1) / 3,
(that._x0 + 2 * that._x1) / 3,
(that._y0 + 2 * that._y1) / 3,
(that._x0 + 4 * that._x1 + x) / 6,
(that._y0 + 4 * that._y1 + y) / 6
);
}
function Basis(context) {
this._context = context;
}
Basis.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 =
this._y0 = this._y1 = NaN;
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 3: basis_point(this, this._x1, this._y1); // proceed
case 2: this._context.lineTo(this._x1, this._y1); break;
}
if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; break;
case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed
default: basis_point(this, x, y); break;
}
this._x0 = this._x1, this._x1 = x;
this._y0 = this._y1, this._y1 = y;
}
};
/* harmony default export */ var basis = (function(context) {
return new Basis(context);
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/noop.js
/* harmony default export */ var src_noop = (function() {});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/basisClosed.js
function basisClosed_BasisClosed(context) {
this._context = context;
}
basisClosed_BasisClosed.prototype = {
areaStart: src_noop,
areaEnd: src_noop,
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =
this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 1: {
this._context.moveTo(this._x2, this._y2);
this._context.closePath();
break;
}
case 2: {
this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
this._context.closePath();
break;
}
case 3: {
this.point(this._x2, this._y2);
this.point(this._x3, this._y3);
this.point(this._x4, this._y4);
break;
}
}
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._x2 = x, this._y2 = y; break;
case 1: this._point = 2; this._x3 = x, this._y3 = y; break;
case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;
default: basis_point(this, x, y); break;
}
this._x0 = this._x1, this._x1 = x;
this._y0 = this._y1, this._y1 = y;
}
};
/* harmony default export */ var basisClosed = (function(context) {
return new basisClosed_BasisClosed(context);
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/basisOpen.js
function basisOpen_BasisOpen(context) {
this._context = context;
}
basisOpen_BasisOpen.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 =
this._y0 = this._y1 = NaN;
this._point = 0;
},
lineEnd: function() {
if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; break;
case 1: this._point = 2; break;
case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;
case 3: this._point = 4; // proceed
default: basis_point(this, x, y); break;
}
this._x0 = this._x1, this._x1 = x;
this._y0 = this._y1, this._y1 = y;
}
};
/* harmony default export */ var basisOpen = (function(context) {
return new basisOpen_BasisOpen(context);
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/bundle.js
function bundle_Bundle(context, beta) {
this._basis = new Basis(context);
this._beta = beta;
}
bundle_Bundle.prototype = {
lineStart: function() {
this._x = [];
this._y = [];
this._basis.lineStart();
},
lineEnd: function() {
var x = this._x,
y = this._y,
j = x.length - 1;
if (j > 0) {
var x0 = x[0],
y0 = y[0],
dx = x[j] - x0,
dy = y[j] - y0,
i = -1,
t;
while (++i <= j) {
t = i / j;
this._basis.point(
this._beta * x[i] + (1 - this._beta) * (x0 + t * dx),
this._beta * y[i] + (1 - this._beta) * (y0 + t * dy)
);
}
}
this._x = this._y = null;
this._basis.lineEnd();
},
point: function(x, y) {
this._x.push(+x);
this._y.push(+y);
}
};
/* harmony default export */ var curve_bundle = ((function custom(beta) {
function bundle(context) {
return beta === 1 ? new Basis(context) : new bundle_Bundle(context, beta);
}
bundle.beta = function(beta) {
return custom(+beta);
};
return bundle;
})(0.85));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/cardinal.js
function cardinal_point(that, x, y) {
that._context.bezierCurveTo(
that._x1 + that._k * (that._x2 - that._x0),
that._y1 + that._k * (that._y2 - that._y0),
that._x2 + that._k * (that._x1 - x),
that._y2 + that._k * (that._y1 - y),
that._x2,
that._y2
);
}
function Cardinal(context, tension) {
this._context = context;
this._k = (1 - tension) / 6;
}
Cardinal.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 =
this._y0 = this._y1 = this._y2 = NaN;
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 2: this._context.lineTo(this._x2, this._y2); break;
case 3: cardinal_point(this, this._x1, this._y1); break;
}
if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; this._x1 = x, this._y1 = y; break;
case 2: this._point = 3; // proceed
default: cardinal_point(this, x, y); break;
}
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
/* harmony default export */ var cardinal = ((function custom(tension) {
function cardinal(context) {
return new Cardinal(context, tension);
}
cardinal.tension = function(tension) {
return custom(+tension);
};
return cardinal;
})(0));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/cardinalOpen.js
function cardinalOpen_CardinalOpen(context, tension) {
this._context = context;
this._k = (1 - tension) / 6;
}
cardinalOpen_CardinalOpen.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 =
this._y0 = this._y1 = this._y2 = NaN;
this._point = 0;
},
lineEnd: function() {
if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; break;
case 1: this._point = 2; break;
case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
case 3: this._point = 4; // proceed
default: cardinal_point(this, x, y); break;
}
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
/* harmony default export */ var cardinalOpen = ((function custom(tension) {
function cardinal(context) {
return new cardinalOpen_CardinalOpen(context, tension);
}
cardinal.tension = function(tension) {
return custom(+tension);
};
return cardinal;
})(0));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/cardinalClosed.js
function cardinalClosed_CardinalClosed(context, tension) {
this._context = context;
this._k = (1 - tension) / 6;
}
cardinalClosed_CardinalClosed.prototype = {
areaStart: src_noop,
areaEnd: src_noop,
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 1: {
this._context.moveTo(this._x3, this._y3);
this._context.closePath();
break;
}
case 2: {
this._context.lineTo(this._x3, this._y3);
this._context.closePath();
break;
}
case 3: {
this.point(this._x3, this._y3);
this.point(this._x4, this._y4);
this.point(this._x5, this._y5);
break;
}
}
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
default: cardinal_point(this, x, y); break;
}
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
/* harmony default export */ var cardinalClosed = ((function custom(tension) {
function cardinal(context) {
return new cardinalClosed_CardinalClosed(context, tension);
}
cardinal.tension = function(tension) {
return custom(+tension);
};
return cardinal;
})(0));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/math.js
var abs = Math.abs;
var atan2 = Math.atan2;
var math_cos = Math.cos;
var math_max = Math.max;
var math_min = Math.min;
var math_sin = Math.sin;
var math_sqrt = Math.sqrt;
var math_epsilon = 1e-12;
var pi = Math.PI;
var halfPi = pi / 2;
var math_tau = 2 * pi;
function acos(x) {
return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
}
function asin(x) {
return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);
}
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/catmullRom.js
function catmullRom_point(that, x, y) {
var x1 = that._x1,
y1 = that._y1,
x2 = that._x2,
y2 = that._y2;
if (that._l01_a > math_epsilon) {
var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,
n = 3 * that._l01_a * (that._l01_a + that._l12_a);
x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
}
if (that._l23_a > math_epsilon) {
var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,
m = 3 * that._l23_a * (that._l23_a + that._l12_a);
x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;
y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;
}
that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);
}
function catmullRom_CatmullRom(context, alpha) {
this._context = context;
this._alpha = alpha;
}
catmullRom_CatmullRom.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 =
this._y0 = this._y1 = this._y2 = NaN;
this._l01_a = this._l12_a = this._l23_a =
this._l01_2a = this._l12_2a = this._l23_2a =
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 2: this._context.lineTo(this._x2, this._y2); break;
case 3: this.point(this._x2, this._y2); break;
}
if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
if (this._point) {
var x23 = this._x2 - x,
y23 = this._y2 - y;
this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
}
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; break;
case 2: this._point = 3; // proceed
default: catmullRom_point(this, x, y); break;
}
this._l01_a = this._l12_a, this._l12_a = this._l23_a;
this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
/* harmony default export */ var curve_catmullRom = ((function custom(alpha) {
function catmullRom(context) {
return alpha ? new catmullRom_CatmullRom(context, alpha) : new Cardinal(context, 0);
}
catmullRom.alpha = function(alpha) {
return custom(+alpha);
};
return catmullRom;
})(0.5));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/catmullRomClosed.js
function catmullRomClosed_CatmullRomClosed(context, alpha) {
this._context = context;
this._alpha = alpha;
}
catmullRomClosed_CatmullRomClosed.prototype = {
areaStart: src_noop,
areaEnd: src_noop,
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =
this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
this._l01_a = this._l12_a = this._l23_a =
this._l01_2a = this._l12_2a = this._l23_2a =
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 1: {
this._context.moveTo(this._x3, this._y3);
this._context.closePath();
break;
}
case 2: {
this._context.lineTo(this._x3, this._y3);
this._context.closePath();
break;
}
case 3: {
this.point(this._x3, this._y3);
this.point(this._x4, this._y4);
this.point(this._x5, this._y5);
break;
}
}
},
point: function(x, y) {
x = +x, y = +y;
if (this._point) {
var x23 = this._x2 - x,
y23 = this._y2 - y;
this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
}
switch (this._point) {
case 0: this._point = 1; this._x3 = x, this._y3 = y; break;
case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;
case 2: this._point = 3; this._x5 = x, this._y5 = y; break;
default: catmullRom_point(this, x, y); break;
}
this._l01_a = this._l12_a, this._l12_a = this._l23_a;
this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
/* harmony default export */ var catmullRomClosed = ((function custom(alpha) {
function catmullRom(context) {
return alpha ? new catmullRomClosed_CatmullRomClosed(context, alpha) : new cardinalClosed_CardinalClosed(context, 0);
}
catmullRom.alpha = function(alpha) {
return custom(+alpha);
};
return catmullRom;
})(0.5));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/catmullRomOpen.js
function catmullRomOpen_CatmullRomOpen(context, alpha) {
this._context = context;
this._alpha = alpha;
}
catmullRomOpen_CatmullRomOpen.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 =
this._y0 = this._y1 = this._y2 = NaN;
this._l01_a = this._l12_a = this._l23_a =
this._l01_2a = this._l12_2a = this._l23_2a =
this._point = 0;
},
lineEnd: function() {
if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
if (this._point) {
var x23 = this._x2 - x,
y23 = this._y2 - y;
this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
}
switch (this._point) {
case 0: this._point = 1; break;
case 1: this._point = 2; break;
case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;
case 3: this._point = 4; // proceed
default: catmullRom_point(this, x, y); break;
}
this._l01_a = this._l12_a, this._l12_a = this._l23_a;
this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;
this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
/* harmony default export */ var catmullRomOpen = ((function custom(alpha) {
function catmullRom(context) {
return alpha ? new catmullRomOpen_CatmullRomOpen(context, alpha) : new cardinalOpen_CardinalOpen(context, 0);
}
catmullRom.alpha = function(alpha) {
return custom(+alpha);
};
return catmullRom;
})(0.5));
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/linear.js
function Linear(context) {
this._context = context;
}
Linear.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; // proceed
default: this._context.lineTo(x, y); break;
}
}
};
/* harmony default export */ var curve_linear = (function(context) {
return new Linear(context);
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/linearClosed.js
function linearClosed_LinearClosed(context) {
this._context = context;
}
linearClosed_LinearClosed.prototype = {
areaStart: src_noop,
areaEnd: src_noop,
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
if (this._point) this._context.closePath();
},
point: function(x, y) {
x = +x, y = +y;
if (this._point) this._context.lineTo(x, y);
else this._point = 1, this._context.moveTo(x, y);
}
};
/* harmony default export */ var linearClosed = (function(context) {
return new linearClosed_LinearClosed(context);
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/monotone.js
function monotone_sign(x) {
return x < 0 ? -1 : 1;
}
// Calculate the slopes of the tangents (Hermite-type interpolation) based on
// the following paper: Steffen, M. 1990. A Simple Method for Monotonic
// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
// NOV(II), P. 443, 1990.
function slope3(that, x2, y2) {
var h0 = that._x1 - that._x0,
h1 = x2 - that._x1,
s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),
s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),
p = (s0 * h1 + s1 * h0) / (h0 + h1);
return (monotone_sign(s0) + monotone_sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}
// Calculate a one-sided slope.
function slope2(that, t) {
var h = that._x1 - that._x0;
return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
// "you can express cubic Hermite interpolation in terms of cubic Bézier curves
// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
function monotone_point(that, t0, t1) {
var x0 = that._x0,
y0 = that._y0,
x1 = that._x1,
y1 = that._y1,
dx = (x1 - x0) / 3;
that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}
function MonotoneX(context) {
this._context = context;
}
MonotoneX.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 =
this._y0 = this._y1 =
this._t0 = NaN;
this._point = 0;
},
lineEnd: function() {
switch (this._point) {
case 2: this._context.lineTo(this._x1, this._y1); break;
case 3: monotone_point(this, this._t0, slope2(this, this._t0)); break;
}
if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
this._line = 1 - this._line;
},
point: function(x, y) {
var t1 = NaN;
x = +x, y = +y;
if (x === this._x1 && y === this._y1) return; // Ignore coincident points.
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; break;
case 2: this._point = 3; monotone_point(this, slope2(this, t1 = slope3(this, x, y)), t1); break;
default: monotone_point(this, this._t0, t1 = slope3(this, x, y)); break;
}
this._x0 = this._x1, this._x1 = x;
this._y0 = this._y1, this._y1 = y;
this._t0 = t1;
}
}
function MonotoneY(context) {
this._context = new ReflectContext(context);
}
(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {
MonotoneX.prototype.point.call(this, y, x);
};
function ReflectContext(context) {
this._context = context;
}
ReflectContext.prototype = {
moveTo: function(x, y) { this._context.moveTo(y, x); },
closePath: function() { this._context.closePath(); },
lineTo: function(x, y) { this._context.lineTo(y, x); },
bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }
};
function monotoneX(context) {
return new MonotoneX(context);
}
function monotoneY(context) {
return new MonotoneY(context);
}
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/natural.js
function Natural(context) {
this._context = context;
}
Natural.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x = [];
this._y = [];
},
lineEnd: function() {
var x = this._x,
y = this._y,
n = x.length;
if (n) {
this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);
if (n === 2) {
this._context.lineTo(x[1], y[1]);
} else {
var px = controlPoints(x),
py = controlPoints(y);
for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
}
}
}
if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();
this._line = 1 - this._line;
this._x = this._y = null;
},
point: function(x, y) {
this._x.push(+x);
this._y.push(+y);
}
};
// See https://www.particleincell.com/2012/bezier-splines/ for derivation.
function controlPoints(x) {
var i,
n = x.length - 1,
m,
a = new Array(n),
b = new Array(n),
r = new Array(n);
a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];
for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];
for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
a[n - 1] = r[n - 1] / b[n - 1];
for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];
b[n - 1] = (x[n] + a[n - 1]) / 2;
for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];
return [a, b];
}
/* harmony default export */ var natural = (function(context) {
return new Natural(context);
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/curve/step.js
function Step(context, t) {
this._context = context;
this._t = t;
}
Step.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x = this._y = NaN;
this._point = 0;
},
lineEnd: function() {
if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
},
point: function(x, y) {
x = +x, y = +y;
switch (this._point) {
case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
case 1: this._point = 2; // proceed
default: {
if (this._t <= 0) {
this._context.lineTo(this._x, y);
this._context.lineTo(x, y);
} else {
var x1 = this._x * (1 - this._t) + x * this._t;
this._context.lineTo(x1, this._y);
this._context.lineTo(x1, y);
}
break;
}
}
this._x = x, this._y = y;
}
};
/* harmony default export */ var curve_step = (function(context) {
return new Step(context, 0.5);
});
function stepBefore(context) {
return new Step(context, 0);
}
function stepAfter(context) {
return new Step(context, 1);
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/curves.js
var curves_lookup = {
'basis': {
curve: basis
},
'basis-closed': {
curve: basisClosed
},
'basis-open': {
curve: basisOpen
},
'bundle': {
curve: curve_bundle,
tension: 'beta',
value: 0.85
},
'cardinal': {
curve: cardinal,
tension: 'tension',
value: 0
},
'cardinal-open': {
curve: cardinalOpen,
tension: 'tension',
value: 0
},
'cardinal-closed': {
curve: cardinalClosed,
tension: 'tension',
value: 0
},
'catmull-rom': {
curve: curve_catmullRom,
tension: 'alpha',
value: 0.5
},
'catmull-rom-closed': {
curve: catmullRomClosed,
tension: 'alpha',
value: 0.5
},
'catmull-rom-open': {
curve: catmullRomOpen,
tension: 'alpha',
value: 0.5
},
'linear': {
curve: curve_linear
},
'linear-closed': {
curve: linearClosed
},
'monotone': {
horizontal: monotoneY,
vertical: monotoneX
},
'natural': {
curve: natural
},
'step': {
curve: curve_step
},
'step-after': {
curve: stepAfter
},
'step-before': {
curve: stepBefore
}
};
function curves_curves(type, orientation, tension) {
var entry = Object(vega_util["v" /* hasOwnProperty */])(curves_lookup, type) && curves_lookup[type],
curve = null;
if (entry) {
curve = entry.curve || entry[orientation || 'vertical'];
if (entry.tension && tension != null) {
curve = curve[entry.tension](tension);
}
}
return curve;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/parse.js
// Path parsing and rendering code adapted from fabric.js -- Thanks!
var cmdlen = { m:2, l:2, h:1, v:1, c:6, s:4, q:4, t:2, a:7 },
regexp = [/([MLHVCSQTAZmlhvcsqtaz])/g, /###/, /(\d)([-+])/g, /\s|,|###/];
/* harmony default export */ var path_parse = (function(pathstr) {
var result = [],
path,
curr,
chunks,
parsed, param,
cmd, len, i, j, n, m;
// First, break path into command sequence
path = pathstr
.slice()
.replace(regexp[0], '###$1')
.split(regexp[1])
.slice(1);
// Next, parse each command in turn
for (i=0, n=path.length; i<n; ++i) {
curr = path[i];
chunks = curr
.slice(1)
.trim()
.replace(regexp[2],'$1###$2')
.split(regexp[3]);
cmd = curr.charAt(0);
parsed = [cmd];
for (j=0, m=chunks.length; j<m; ++j) {
if ((param = +chunks[j]) === param) { // not NaN
parsed.push(param);
}
}
len = cmdlen[cmd.toLowerCase()];
if (parsed.length-1 > len) {
for (j=1, m=parsed.length; j<m; j+=len) {
result.push([cmd].concat(parsed.slice(j, j+len)));
}
}
else {
result.push(parsed);
}
}
return result;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/constants.js
const DegToRad = Math.PI / 180;
const Epsilon = 1e-14;
const HalfPi = Math.PI / 2;
const Tau = Math.PI * 2;
const HalfSqrt3 = Math.sqrt(3) / 2;
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/arc.js
var arc_segmentCache = {};
var arc_bezierCache = {};
var arc_join = [].join;
// Copied from Inkscape svgtopdf, thanks!
function arc_segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) {
var key = arc_join.call(arguments);
if (arc_segmentCache[key]) {
return arc_segmentCache[key];
}
var th = rotateX * DegToRad;
var sin_th = Math.sin(th);
var cos_th = Math.cos(th);
rx = Math.abs(rx);
ry = Math.abs(ry);
var px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
var py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
var pl = (px*px) / (rx*rx) + (py*py) / (ry*ry);
if (pl > 1) {
pl = Math.sqrt(pl);
rx *= pl;
ry *= pl;
}
var a00 = cos_th / rx;
var a01 = sin_th / rx;
var a10 = (-sin_th) / ry;
var a11 = (cos_th) / ry;
var x0 = a00 * ox + a01 * oy;
var y0 = a10 * ox + a11 * oy;
var x1 = a00 * x + a01 * y;
var y1 = a10 * x + a11 * y;
var d = (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0);
var sfactor_sq = 1 / d - 0.25;
if (sfactor_sq < 0) sfactor_sq = 0;
var sfactor = Math.sqrt(sfactor_sq);
if (sweep == large) sfactor = -sfactor;
var xc = 0.5 * (x0 + x1) - sfactor * (y1-y0);
var yc = 0.5 * (y0 + y1) + sfactor * (x1-x0);
var th0 = Math.atan2(y0-yc, x0-xc);
var th1 = Math.atan2(y1-yc, x1-xc);
var th_arc = th1-th0;
if (th_arc < 0 && sweep === 1) {
th_arc += Tau;
} else if (th_arc > 0 && sweep === 0) {
th_arc -= Tau;
}
var segs = Math.ceil(Math.abs(th_arc / (HalfPi + 0.001)));
var result = [];
for (var i=0; i<segs; ++i) {
var th2 = th0 + i * th_arc / segs;
var th3 = th0 + (i+1) * th_arc / segs;
result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
}
return (arc_segmentCache[key] = result);
}
function arc_bezier(params) {
var key = arc_join.call(params);
if (arc_bezierCache[key]) {
return arc_bezierCache[key];
}
var cx = params[0],
cy = params[1],
th0 = params[2],
th1 = params[3],
rx = params[4],
ry = params[5],
sin_th = params[6],
cos_th = params[7];
var a00 = cos_th * rx;
var a01 = -sin_th * ry;
var a10 = sin_th * rx;
var a11 = cos_th * ry;
var cos_th0 = Math.cos(th0);
var sin_th0 = Math.sin(th0);
var cos_th1 = Math.cos(th1);
var sin_th1 = Math.sin(th1);
var th_half = 0.5 * (th1 - th0);
var sin_th_h2 = Math.sin(th_half * 0.5);
var t = (8/3) * sin_th_h2 * sin_th_h2 / Math.sin(th_half);
var x1 = cx + cos_th0 - t * sin_th0;
var y1 = cy + sin_th0 + t * cos_th0;
var x3 = cx + cos_th1;
var y3 = cy + sin_th1;
var x2 = x3 + t * sin_th1;
var y2 = y3 - t * cos_th1;
return (arc_bezierCache[key] = [
a00 * x1 + a01 * y1, a10 * x1 + a11 * y1,
a00 * x2 + a01 * y2, a10 * x2 + a11 * y2,
a00 * x3 + a01 * y3, a10 * x3 + a11 * y3
]);
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/render.js
var render_temp = ['l', 0, 0, 0, 0, 0, 0, 0];
function render_scale(current, sX, sY) {
var c = (render_temp[0] = current[0]);
if (c === 'a' || c === 'A') {
render_temp[1] = sX * current[1];
render_temp[2] = sY * current[2];
render_temp[3] = current[3];
render_temp[4] = current[4];
render_temp[5] = current[5];
render_temp[6] = sX * current[6];
render_temp[7] = sY * current[7];
} else if (c === 'h' || c === 'H') {
render_temp[1] = sX * current[1];
} else if (c === 'v' || c === 'V') {
render_temp[1] = sY * current[1];
} else {
for (var i=1, n=current.length; i<n; ++i) {
render_temp[i] = (i % 2 == 1 ? sX : sY) * current[i];
}
}
return render_temp;
}
/* harmony default export */ var path_render = (function(context, path, l, t, sX, sY) {
var current, // current instruction
previous = null,
x = 0, // current x
y = 0, // current y
controlX = 0, // current control point x
controlY = 0, // current control point y
tempX,
tempY,
tempControlX,
tempControlY;
if (l == null) l = 0;
if (t == null) t = 0;
if (sX == null) sX = 1;
if (sY == null) sY = sX;
if (context.beginPath) context.beginPath();
for (var i=0, len=path.length; i<len; ++i) {
current = path[i];
if (sX !== 1 || sY !== 1) {
current = render_scale(current, sX, sY);
}
switch (current[0]) { // first letter
case 'l': // lineto, relative
x += current[1];
y += current[2];
context.lineTo(x + l, y + t);
break;
case 'L': // lineto, absolute
x = current[1];
y = current[2];
context.lineTo(x + l, y + t);
break;
case 'h': // horizontal lineto, relative
x += current[1];
context.lineTo(x + l, y + t);
break;
case 'H': // horizontal lineto, absolute
x = current[1];
context.lineTo(x + l, y + t);
break;
case 'v': // vertical lineto, relative
y += current[1];
context.lineTo(x + l, y + t);
break;
case 'V': // verical lineto, absolute
y = current[1];
context.lineTo(x + l, y + t);
break;
case 'm': // moveTo, relative
x += current[1];
y += current[2];
context.moveTo(x + l, y + t);
break;
case 'M': // moveTo, absolute
x = current[1];
y = current[2];
context.moveTo(x + l, y + t);
break;
case 'c': // bezierCurveTo, relative
tempX = x + current[5];
tempY = y + current[6];
controlX = x + current[3];
controlY = y + current[4];
context.bezierCurveTo(
x + current[1] + l, // x1
y + current[2] + t, // y1
controlX + l, // x2
controlY + t, // y2
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
break;
case 'C': // bezierCurveTo, absolute
x = current[5];
y = current[6];
controlX = current[3];
controlY = current[4];
context.bezierCurveTo(
current[1] + l,
current[2] + t,
controlX + l,
controlY + t,
x + l,
y + t
);
break;
case 's': // shorthand cubic bezierCurveTo, relative
// transform to absolute x,y
tempX = x + current[3];
tempY = y + current[4];
// calculate reflection of previous control points
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
context.bezierCurveTo(
controlX + l,
controlY + t,
x + current[1] + l,
y + current[2] + t,
tempX + l,
tempY + t
);
// set control point to 2nd one of this command
// the first control point is assumed to be the reflection of
// the second control point on the previous command relative
// to the current point.
controlX = x + current[1];
controlY = y + current[2];
x = tempX;
y = tempY;
break;
case 'S': // shorthand cubic bezierCurveTo, absolute
tempX = current[3];
tempY = current[4];
// calculate reflection of previous control points
controlX = 2*x - controlX;
controlY = 2*y - controlY;
context.bezierCurveTo(
controlX + l,
controlY + t,
current[1] + l,
current[2] + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
// set control point to 2nd one of this command
// the first control point is assumed to be the reflection of
// the second control point on the previous command relative
// to the current point.
controlX = current[1];
controlY = current[2];
break;
case 'q': // quadraticCurveTo, relative
// transform to absolute x,y
tempX = x + current[3];
tempY = y + current[4];
controlX = x + current[1];
controlY = y + current[2];
context.quadraticCurveTo(
controlX + l,
controlY + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
break;
case 'Q': // quadraticCurveTo, absolute
tempX = current[3];
tempY = current[4];
context.quadraticCurveTo(
current[1] + l,
current[2] + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
controlX = current[1];
controlY = current[2];
break;
case 't': // shorthand quadraticCurveTo, relative
// transform to absolute x,y
tempX = x + current[1];
tempY = y + current[2];
if (previous[0].match(/[QqTt]/) === null) {
// If there is no previous command or if the previous command was not a Q, q, T or t,
// assume the control point is coincident with the current point
controlX = x;
controlY = y;
}
else if (previous[0] === 't') {
// calculate reflection of previous control points for t
controlX = 2 * x - tempControlX;
controlY = 2 * y - tempControlY;
}
else if (previous[0] === 'q') {
// calculate reflection of previous control points for q
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
}
tempControlX = controlX;
tempControlY = controlY;
context.quadraticCurveTo(
controlX + l,
controlY + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
controlX = x + current[1];
controlY = y + current[2];
break;
case 'T':
tempX = current[1];
tempY = current[2];
// calculate reflection of previous control points
controlX = 2 * x - controlX;
controlY = 2 * y - controlY;
context.quadraticCurveTo(
controlX + l,
controlY + t,
tempX + l,
tempY + t
);
x = tempX;
y = tempY;
break;
case 'a':
render_drawArc(context, x + l, y + t, [
current[1],
current[2],
current[3],
current[4],
current[5],
current[6] + x + l,
current[7] + y + t
]);
x += current[6];
y += current[7];
break;
case 'A':
render_drawArc(context, x + l, y + t, [
current[1],
current[2],
current[3],
current[4],
current[5],
current[6] + l,
current[7] + t
]);
x = current[6];
y = current[7];
break;
case 'z':
case 'Z':
context.closePath();
break;
}
previous = current;
}
});
function render_drawArc(context, x, y, coords) {
var seg = arc_segments(
coords[5], // end x
coords[6], // end y
coords[0], // radius x
coords[1], // radius y
coords[3], // large flag
coords[4], // sweep flag
coords[2], // rotation
x, y
);
for (var i=0; i<seg.length; ++i) {
var bez = arc_bezier(seg[i]);
context.bezierCurveTo(bez[0], bez[1], bez[2], bez[3], bez[4], bez[5]);
}
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/symbols.js
var symbols_Tan30 = 0.5773502691896257;
var symbols_builtins = {
'circle': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2;
context.moveTo(r, 0);
context.arc(0, 0, r, 0, Tau);
}
},
'cross': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
s = r / 2.5;
context.moveTo(-r, -s);
context.lineTo(-r, s);
context.lineTo(-s, s);
context.lineTo(-s, r);
context.lineTo(s, r);
context.lineTo(s, s);
context.lineTo(r, s);
context.lineTo(r, -s);
context.lineTo(s, -s);
context.lineTo(s, -r);
context.lineTo(-s, -r);
context.lineTo(-s, -s);
context.closePath();
}
},
'diamond': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2;
context.moveTo(-r, 0);
context.lineTo(0, -r);
context.lineTo(r, 0);
context.lineTo(0, r);
context.closePath();
}
},
'square': {
draw: function(context, size) {
var w = Math.sqrt(size),
x = -w / 2;
context.rect(x, x, w, w);
}
},
'arrow': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
s = r / 7,
t = r / 2.5,
v = r / 8;
context.moveTo(-s, r);
context.lineTo(s, r);
context.lineTo(s, -v);
context.lineTo(t, -v);
context.lineTo(0, -r);
context.lineTo(-t, -v);
context.lineTo(-s, -v);
context.closePath();
}
},
'wedge': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
h = HalfSqrt3 * r,
o = (h - r * symbols_Tan30),
b = r / 4;
context.moveTo(0, -h - o);
context.lineTo(-b, h - o);
context.lineTo(b, h - o);
context.closePath();
}
},
'triangle': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
h = HalfSqrt3 * r,
o = (h - r * symbols_Tan30);
context.moveTo(0, -h - o);
context.lineTo(-r, h - o);
context.lineTo(r, h - o);
context.closePath();
}
},
'triangle-up': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
h = HalfSqrt3 * r;
context.moveTo(0, -h);
context.lineTo(-r, h);
context.lineTo(r, h);
context.closePath();
}
},
'triangle-down': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
h = HalfSqrt3 * r;
context.moveTo(0, h);
context.lineTo(-r, -h);
context.lineTo(r, -h);
context.closePath();
}
},
'triangle-right': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
h = HalfSqrt3 * r;
context.moveTo(h, 0);
context.lineTo(-h, -r);
context.lineTo(-h, r);
context.closePath();
}
},
'triangle-left': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2,
h = HalfSqrt3 * r;
context.moveTo(-h, 0);
context.lineTo(h, -r);
context.lineTo(h, r);
context.closePath();
}
},
'stroke': {
draw: function(context, size) {
var r = Math.sqrt(size) / 2;
context.moveTo(-r, 0);
context.lineTo(r, 0);
}
}
};
function symbols_symbols(_) {
return Object(vega_util["v" /* hasOwnProperty */])(symbols_builtins, _) ? symbols_builtins[_] : symbols_customSymbol(_);
}
var symbols_custom = {};
function symbols_customSymbol(path) {
if (!Object(vega_util["v" /* hasOwnProperty */])(symbols_custom, path)) {
var parsed = path_parse(path);
symbols_custom[path] = {
draw: function(context, size) {
path_render(context, parsed, 0, 0, Math.sqrt(size) / 2);
}
};
}
return symbols_custom[path];
}
// CONCATENATED MODULE: ./node_modules/d3-path/src/path.js
var path_pi = Math.PI,
path_tau = 2 * path_pi,
path_epsilon = 1e-6,
tauEpsilon = path_tau - path_epsilon;
function Path() {
this._x0 = this._y0 = // start of current subpath
this._x1 = this._y1 = null; // end of current subpath
this._ = "";
}
function path_path() {
return new Path;
}
Path.prototype = path_path.prototype = {
constructor: Path,
moveTo: function(x, y) {
this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
},
closePath: function() {
if (this._x1 !== null) {
this._x1 = this._x0, this._y1 = this._y0;
this._ += "Z";
}
},
lineTo: function(x, y) {
this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
},
quadraticCurveTo: function(x1, y1, x, y) {
this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
},
bezierCurveTo: function(x1, y1, x2, y2, x, y) {
this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y);
},
arcTo: function(x1, y1, x2, y2, r) {
x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
var x0 = this._x1,
y0 = this._y1,
x21 = x2 - x1,
y21 = y2 - y1,
x01 = x0 - x1,
y01 = y0 - y1,
l01_2 = x01 * x01 + y01 * y01;
// Is the radius negative? Error.
if (r < 0) throw new Error("negative radius: " + r);
// Is this path empty? Move to (x1,y1).
if (this._x1 === null) {
this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
}
// Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
else if (!(l01_2 > path_epsilon));
// Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
// Equivalently, is (x1,y1) coincident with (x2,y2)?
// Or, is the radius zero? Line to (x1,y1).
else if (!(Math.abs(y01 * x21 - y21 * x01) > path_epsilon) || !r) {
this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
}
// Otherwise, draw an arc!
else {
var x20 = x2 - x0,
y20 = y2 - y0,
l21_2 = x21 * x21 + y21 * y21,
l20_2 = x20 * x20 + y20 * y20,
l21 = Math.sqrt(l21_2),
l01 = Math.sqrt(l01_2),
l = r * Math.tan((path_pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
t01 = l / l01,
t21 = l / l21;
// If the start tangent is not coincident with (x0,y0), line to.
if (Math.abs(t01 - 1) > path_epsilon) {
this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01);
}
this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
}
},
arc: function(x, y, r, a0, a1, ccw) {
x = +x, y = +y, r = +r, ccw = !!ccw;
var dx = r * Math.cos(a0),
dy = r * Math.sin(a0),
x0 = x + dx,
y0 = y + dy,
cw = 1 ^ ccw,
da = ccw ? a0 - a1 : a1 - a0;
// Is the radius negative? Error.
if (r < 0) throw new Error("negative radius: " + r);
// Is this path empty? Move to (x0,y0).
if (this._x1 === null) {
this._ += "M" + x0 + "," + y0;
}
// Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
else if (Math.abs(this._x1 - x0) > path_epsilon || Math.abs(this._y1 - y0) > path_epsilon) {
this._ += "L" + x0 + "," + y0;
}
// Is this arc empty? Were done.
if (!r) return;
// Does the angle go the wrong way? Flip the direction.
if (da < 0) da = da % path_tau + path_tau;
// Is this a complete circle? Draw two arcs to complete the circle.
if (da > tauEpsilon) {
this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0);
}
// Is this arc non-empty? Draw an arc!
else if (da > path_epsilon) {
this._ += "A" + r + "," + r + ",0," + (+(da >= path_pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1));
}
},
rect: function(x, y, w, h) {
this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z";
},
toString: function() {
return this._;
}
};
/* harmony default export */ var src_path = (path_path);
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/rectangle.js
// See http://spencermortensen.com/articles/bezier-circle/
const rectangle_C = 0.448084975506; // C = 1 - c
function rectangle_rectangleX(d) {
return d.x;
}
function rectangle_rectangleY(d) {
return d.y;
}
function rectangle_rectangleWidth(d) {
return d.width;
}
function rectangle_rectangleHeight(d) {
return d.height;
}
function rectangle_number(_) {
return typeof _ === 'function' ? _ : () => +_;
}
function rectangle_clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}
/* harmony default export */ var path_rectangle = (function() {
var x = rectangle_rectangleX,
y = rectangle_rectangleY,
width = rectangle_rectangleWidth,
height = rectangle_rectangleHeight,
crTL = rectangle_number(0),
crTR = crTL,
crBL = crTL,
crBR = crTL,
context = null;
function rectangle(_, x0, y0) {
var buffer,
x1 = x0 != null ? x0 : +x.call(this, _),
y1 = y0 != null ? y0 : +y.call(this, _),
w = +width.call(this, _),
h = +height.call(this, _),
s = Math.min(w, h) / 2,
tl = rectangle_clamp(+crTL.call(this, _), 0, s),
tr = rectangle_clamp(+crTR.call(this, _), 0, s),
bl = rectangle_clamp(+crBL.call(this, _), 0, s),
br = rectangle_clamp(+crBR.call(this, _), 0, s);
if (!context) context = buffer = src_path();
if (tl <= 0 && tr <= 0 && bl <= 0 && br <= 0) {
context.rect(x1, y1, w, h);
} else {
var x2 = x1 + w,
y2 = y1 + h;
context.moveTo(x1 + tl, y1);
context.lineTo(x2 - tr, y1);
context.bezierCurveTo(x2 - rectangle_C * tr, y1, x2, y1 + rectangle_C * tr, x2, y1 + tr);
context.lineTo(x2, y2 - br);
context.bezierCurveTo(x2, y2 - rectangle_C * br, x2 - rectangle_C * br, y2, x2 - br, y2);
context.lineTo(x1 + bl, y2);
context.bezierCurveTo(x1 + rectangle_C * bl, y2, x1, y2 - rectangle_C * bl, x1, y2 - bl);
context.lineTo(x1, y1 + tl);
context.bezierCurveTo(x1, y1 + rectangle_C * tl, x1 + rectangle_C * tl, y1, x1 + tl, y1);
context.closePath();
}
if (buffer) {
context = null;
return buffer + '' || null;
}
}
rectangle.x = function(_) {
if (arguments.length) {
x = rectangle_number(_);
return rectangle;
} else {
return x;
}
};
rectangle.y = function(_) {
if (arguments.length) {
y = rectangle_number(_);
return rectangle;
} else {
return y;
}
};
rectangle.width = function(_) {
if (arguments.length) {
width = rectangle_number(_);
return rectangle;
} else {
return width;
}
};
rectangle.height = function(_) {
if (arguments.length) {
height = rectangle_number(_);
return rectangle;
} else {
return height;
}
};
rectangle.cornerRadius = function(tl, tr, br, bl) {
if (arguments.length) {
crTL = rectangle_number(tl);
crTR = tr != null ? rectangle_number(tr) : crTL;
crBR = br != null ? rectangle_number(br) : crTL;
crBL = bl != null ? rectangle_number(bl) : crTR;
return rectangle;
} else {
return crTL;
}
};
rectangle.context = function(_) {
if (arguments.length) {
context = _ == null ? null : _;
return rectangle;
} else {
return context;
}
};
return rectangle;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/trail.js
/* harmony default export */ var path_trail = (function() {
var x,
y,
size,
defined,
context = null,
ready, x1, y1, r1;
function point(x2, y2, w2) {
var r2 = w2 / 2;
if (ready) {
var ux = y1 - y2,
uy = x2 - x1;
if (ux || uy) {
// get normal vector
var ud = Math.sqrt(ux * ux + uy * uy),
rx = (ux /= ud) * r1,
ry = (uy /= ud) * r1,
t = Math.atan2(uy, ux);
// draw segment
context.moveTo(x1 - rx, y1 - ry);
context.lineTo(x2 - ux * r2, y2 - uy * r2);
context.arc(x2, y2, r2, t - Math.PI, t);
context.lineTo(x1 + rx, y1 + ry);
context.arc(x1, y1, r1, t, t + Math.PI);
} else {
context.arc(x2, y2, r2, 0, Tau);
}
context.closePath();
} else {
ready = 1;
}
x1 = x2;
y1 = y2;
r1 = r2;
}
function trail(data) {
var i,
n = data.length,
d,
defined0 = false,
buffer;
if (context == null) context = buffer = src_path();
for (i = 0; i <= n; ++i) {
if (!(i < n && defined(d = data[i], i, data)) === defined0) {
if (defined0 = !defined0) ready = 0;
}
if (defined0) point(+x(d, i, data), +y(d, i, data), +size(d, i, data));
}
if (buffer) {
context = null;
return buffer + '' || null;
}
}
trail.x = function(_) {
if (arguments.length) {
x = _;
return trail;
} else {
return x;
}
};
trail.y = function(_) {
if (arguments.length) {
y = _;
return trail;
} else {
return y;
}
};
trail.size = function(_) {
if (arguments.length) {
size = _;
return trail;
} else {
return size;
}
};
trail.defined = function(_) {
if (arguments.length) {
defined = _;
return trail;
} else {
return defined;
}
};
trail.context = function(_) {
if (arguments.length) {
if (_ == null) {
context = null;
} else {
context = _;
}
return trail;
} else {
return context;
}
};
return trail;
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/constant.js
/* harmony default export */ var d3_shape_src_constant = (function(x) {
return function constant() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/arc.js
function arc_arcInnerRadius(d) {
return d.innerRadius;
}
function arc_arcOuterRadius(d) {
return d.outerRadius;
}
function arc_arcStartAngle(d) {
return d.startAngle;
}
function arc_arcEndAngle(d) {
return d.endAngle;
}
function arc_arcPadAngle(d) {
return d && d.padAngle; // Note: optional!
}
function arc_intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
var x10 = x1 - x0, y10 = y1 - y0,
x32 = x3 - x2, y32 = y3 - y2,
t = y32 * x10 - x32 * y10;
if (t * t < math_epsilon) return;
t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
return [x0 + t * x10, y0 + t * y10];
}
// Compute perpendicular offset line of length rc.
// http://mathworld.wolfram.com/Circle-LineIntersection.html
function arc_cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
var x01 = x0 - x1,
y01 = y0 - y1,
lo = (cw ? rc : -rc) / math_sqrt(x01 * x01 + y01 * y01),
ox = lo * y01,
oy = -lo * x01,
x11 = x0 + ox,
y11 = y0 + oy,
x10 = x1 + ox,
y10 = y1 + oy,
x00 = (x11 + x10) / 2,
y00 = (y11 + y10) / 2,
dx = x10 - x11,
dy = y10 - y11,
d2 = dx * dx + dy * dy,
r = r1 - rc,
D = x11 * y10 - x10 * y11,
d = (dy < 0 ? -1 : 1) * math_sqrt(math_max(0, r * r * d2 - D * D)),
cx0 = (D * dy - dx * d) / d2,
cy0 = (-D * dx - dy * d) / d2,
cx1 = (D * dy + dx * d) / d2,
cy1 = (-D * dx + dy * d) / d2,
dx0 = cx0 - x00,
dy0 = cy0 - y00,
dx1 = cx1 - x00,
dy1 = cy1 - y00;
// Pick the closer of the two intersection points.
// TODO Is there a faster way to determine which intersection to use?
if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
return {
cx: cx0,
cy: cy0,
x01: -ox,
y01: -oy,
x11: cx0 * (r1 / r - 1),
y11: cy0 * (r1 / r - 1)
};
}
/* harmony default export */ var src_arc = (function() {
var innerRadius = arc_arcInnerRadius,
outerRadius = arc_arcOuterRadius,
cornerRadius = d3_shape_src_constant(0),
padRadius = null,
startAngle = arc_arcStartAngle,
endAngle = arc_arcEndAngle,
padAngle = arc_arcPadAngle,
context = null;
function arc() {
var buffer,
r,
r0 = +innerRadius.apply(this, arguments),
r1 = +outerRadius.apply(this, arguments),
a0 = startAngle.apply(this, arguments) - halfPi,
a1 = endAngle.apply(this, arguments) - halfPi,
da = abs(a1 - a0),
cw = a1 > a0;
if (!context) context = buffer = src_path();
// Ensure that the outer radius is always larger than the inner radius.
if (r1 < r0) r = r1, r1 = r0, r0 = r;
// Is it a point?
if (!(r1 > math_epsilon)) context.moveTo(0, 0);
// Or is it a circle or annulus?
else if (da > math_tau - math_epsilon) {
context.moveTo(r1 * math_cos(a0), r1 * math_sin(a0));
context.arc(0, 0, r1, a0, a1, !cw);
if (r0 > math_epsilon) {
context.moveTo(r0 * math_cos(a1), r0 * math_sin(a1));
context.arc(0, 0, r0, a1, a0, cw);
}
}
// Or is it a circular or annular sector?
else {
var a01 = a0,
a11 = a1,
a00 = a0,
a10 = a1,
da0 = da,
da1 = da,
ap = padAngle.apply(this, arguments) / 2,
rp = (ap > math_epsilon) && (padRadius ? +padRadius.apply(this, arguments) : math_sqrt(r0 * r0 + r1 * r1)),
rc = math_min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),
rc0 = rc,
rc1 = rc,
t0,
t1;
// Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
if (rp > math_epsilon) {
var p0 = asin(rp / r0 * math_sin(ap)),
p1 = asin(rp / r1 * math_sin(ap));
if ((da0 -= p0 * 2) > math_epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;
else da0 = 0, a00 = a10 = (a0 + a1) / 2;
if ((da1 -= p1 * 2) > math_epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;
else da1 = 0, a01 = a11 = (a0 + a1) / 2;
}
var x01 = r1 * math_cos(a01),
y01 = r1 * math_sin(a01),
x10 = r0 * math_cos(a10),
y10 = r0 * math_sin(a10);
// Apply rounded corners?
if (rc > math_epsilon) {
var x11 = r1 * math_cos(a11),
y11 = r1 * math_sin(a11),
x00 = r0 * math_cos(a00),
y00 = r0 * math_sin(a00),
oc;
// Restrict the corner radius according to the sector angle.
if (da < pi && (oc = arc_intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {
var ax = x01 - oc[0],
ay = y01 - oc[1],
bx = x11 - oc[0],
by = y11 - oc[1],
kc = 1 / math_sin(acos((ax * bx + ay * by) / (math_sqrt(ax * ax + ay * ay) * math_sqrt(bx * bx + by * by))) / 2),
lc = math_sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
rc0 = math_min(rc, (r0 - lc) / (kc - 1));
rc1 = math_min(rc, (r1 - lc) / (kc + 1));
}
}
// Is the sector collapsed to a line?
if (!(da1 > math_epsilon)) context.moveTo(x01, y01);
// Does the sectors outer ring have rounded corners?
else if (rc1 > math_epsilon) {
t0 = arc_cornerTangents(x00, y00, x01, y01, r1, rc1, cw);
t1 = arc_cornerTangents(x11, y11, x10, y10, r1, rc1, cw);
context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);
// Have the corners merged?
if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);
// Otherwise, draw the two corners and the ring.
else {
context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);
context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
}
}
// Or is the outer ring just a circular arc?
else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);
// Is there no inner ring, and its a circular sector?
// Or perhaps its an annular sector collapsed due to padding?
if (!(r0 > math_epsilon) || !(da0 > math_epsilon)) context.lineTo(x10, y10);
// Does the sectors inner ring (or point) have rounded corners?
else if (rc0 > math_epsilon) {
t0 = arc_cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);
t1 = arc_cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);
context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);
// Have the corners merged?
if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);
// Otherwise, draw the two corners and the ring.
else {
context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);
context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);
context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);
}
}
// Or is the inner ring just a circular arc?
else context.arc(0, 0, r0, a10, a00, cw);
}
context.closePath();
if (buffer) return context = null, buffer + "" || null;
}
arc.centroid = function() {
var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,
a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
return [math_cos(a) * r, math_sin(a) * r];
};
arc.innerRadius = function(_) {
return arguments.length ? (innerRadius = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : innerRadius;
};
arc.outerRadius = function(_) {
return arguments.length ? (outerRadius = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : outerRadius;
};
arc.cornerRadius = function(_) {
return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : cornerRadius;
};
arc.padRadius = function(_) {
return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : padRadius;
};
arc.startAngle = function(_) {
return arguments.length ? (startAngle = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : startAngle;
};
arc.endAngle = function(_) {
return arguments.length ? (endAngle = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : endAngle;
};
arc.padAngle = function(_) {
return arguments.length ? (padAngle = typeof _ === "function" ? _ : d3_shape_src_constant(+_), arc) : padAngle;
};
arc.context = function(_) {
return arguments.length ? ((context = _ == null ? null : _), arc) : context;
};
return arc;
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/point.js
function point_x(p) {
return p[0];
}
function point_y(p) {
return p[1];
}
// CONCATENATED MODULE: ./node_modules/d3-shape/src/line.js
/* harmony default export */ var src_line = (function() {
var x = point_x,
y = point_y,
defined = d3_shape_src_constant(true),
context = null,
curve = curve_linear,
output = null;
function line(data) {
var i,
n = data.length,
d,
defined0 = false,
buffer;
if (context == null) output = curve(buffer = src_path());
for (i = 0; i <= n; ++i) {
if (!(i < n && defined(d = data[i], i, data)) === defined0) {
if (defined0 = !defined0) output.lineStart();
else output.lineEnd();
}
if (defined0) output.point(+x(d, i, data), +y(d, i, data));
}
if (buffer) return output = null, buffer + "" || null;
}
line.x = function(_) {
return arguments.length ? (x = typeof _ === "function" ? _ : d3_shape_src_constant(+_), line) : x;
};
line.y = function(_) {
return arguments.length ? (y = typeof _ === "function" ? _ : d3_shape_src_constant(+_), line) : y;
};
line.defined = function(_) {
return arguments.length ? (defined = typeof _ === "function" ? _ : d3_shape_src_constant(!!_), line) : defined;
};
line.curve = function(_) {
return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
};
line.context = function(_) {
return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
};
return line;
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/area.js
/* harmony default export */ var src_area = (function() {
var x0 = point_x,
x1 = null,
y0 = d3_shape_src_constant(0),
y1 = point_y,
defined = d3_shape_src_constant(true),
context = null,
curve = curve_linear,
output = null;
function area(data) {
var i,
j,
k,
n = data.length,
d,
defined0 = false,
buffer,
x0z = new Array(n),
y0z = new Array(n);
if (context == null) output = curve(buffer = src_path());
for (i = 0; i <= n; ++i) {
if (!(i < n && defined(d = data[i], i, data)) === defined0) {
if (defined0 = !defined0) {
j = i;
output.areaStart();
output.lineStart();
} else {
output.lineEnd();
output.lineStart();
for (k = i - 1; k >= j; --k) {
output.point(x0z[k], y0z[k]);
}
output.lineEnd();
output.areaEnd();
}
}
if (defined0) {
x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);
output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);
}
}
if (buffer) return output = null, buffer + "" || null;
}
function arealine() {
return src_line().defined(defined).curve(curve).context(context);
}
area.x = function(_) {
return arguments.length ? (x0 = typeof _ === "function" ? _ : d3_shape_src_constant(+_), x1 = null, area) : x0;
};
area.x0 = function(_) {
return arguments.length ? (x0 = typeof _ === "function" ? _ : d3_shape_src_constant(+_), area) : x0;
};
area.x1 = function(_) {
return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : d3_shape_src_constant(+_), area) : x1;
};
area.y = function(_) {
return arguments.length ? (y0 = typeof _ === "function" ? _ : d3_shape_src_constant(+_), y1 = null, area) : y0;
};
area.y0 = function(_) {
return arguments.length ? (y0 = typeof _ === "function" ? _ : d3_shape_src_constant(+_), area) : y0;
};
area.y1 = function(_) {
return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : d3_shape_src_constant(+_), area) : y1;
};
area.lineX0 =
area.lineY0 = function() {
return arealine().x(x0).y(y0);
};
area.lineY1 = function() {
return arealine().x(x0).y(y1);
};
area.lineX1 = function() {
return arealine().x(x1).y(y0);
};
area.defined = function(_) {
return arguments.length ? (defined = typeof _ === "function" ? _ : d3_shape_src_constant(!!_), area) : defined;
};
area.curve = function(_) {
return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;
};
area.context = function(_) {
return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;
};
return area;
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/circle.js
/* harmony default export */ var symbol_circle = ({
draw: function(context, size) {
var r = Math.sqrt(size / pi);
context.moveTo(r, 0);
context.arc(0, 0, r, 0, math_tau);
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/cross.js
/* harmony default export */ var symbol_cross = ({
draw: function(context, size) {
var r = Math.sqrt(size / 5) / 2;
context.moveTo(-3 * r, -r);
context.lineTo(-r, -r);
context.lineTo(-r, -3 * r);
context.lineTo(r, -3 * r);
context.lineTo(r, -r);
context.lineTo(3 * r, -r);
context.lineTo(3 * r, r);
context.lineTo(r, r);
context.lineTo(r, 3 * r);
context.lineTo(-r, 3 * r);
context.lineTo(-r, r);
context.lineTo(-3 * r, r);
context.closePath();
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/diamond.js
var tan30 = Math.sqrt(1 / 3),
tan30_2 = tan30 * 2;
/* harmony default export */ var diamond = ({
draw: function(context, size) {
var y = Math.sqrt(size / tan30_2),
x = y * tan30;
context.moveTo(0, -y);
context.lineTo(x, 0);
context.lineTo(0, y);
context.lineTo(-x, 0);
context.closePath();
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/star.js
var star_ka = 0.89081309152928522810,
star_kr = Math.sin(pi / 10) / Math.sin(7 * pi / 10),
star_kx = Math.sin(math_tau / 10) * star_kr,
star_ky = -Math.cos(math_tau / 10) * star_kr;
/* harmony default export */ var star = ({
draw: function(context, size) {
var r = Math.sqrt(size * star_ka),
x = star_kx * r,
y = star_ky * r;
context.moveTo(0, -r);
context.lineTo(x, y);
for (var i = 1; i < 5; ++i) {
var a = math_tau * i / 5,
c = Math.cos(a),
s = Math.sin(a);
context.lineTo(s * r, -c * r);
context.lineTo(c * x - s * y, s * x + c * y);
}
context.closePath();
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/square.js
/* harmony default export */ var symbol_square = ({
draw: function(context, size) {
var w = Math.sqrt(size),
x = -w / 2;
context.rect(x, x, w, w);
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/triangle.js
var sqrt3 = Math.sqrt(3);
/* harmony default export */ var triangle = ({
draw: function(context, size) {
var y = -Math.sqrt(size / (sqrt3 * 3));
context.moveTo(0, y * 2);
context.lineTo(-sqrt3 * y, -y);
context.lineTo(sqrt3 * y, -y);
context.closePath();
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol/wye.js
var wye_c = -0.5,
wye_s = Math.sqrt(3) / 2,
wye_k = 1 / Math.sqrt(12),
wye_a = (wye_k / 2 + 1) * 3;
/* harmony default export */ var wye = ({
draw: function(context, size) {
var r = Math.sqrt(size / wye_a),
x0 = r / 2,
y0 = r * wye_k,
x1 = x0,
y1 = r * wye_k + r,
x2 = -x1,
y2 = y1;
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.lineTo(x2, y2);
context.lineTo(wye_c * x0 - wye_s * y0, wye_s * x0 + wye_c * y0);
context.lineTo(wye_c * x1 - wye_s * y1, wye_s * x1 + wye_c * y1);
context.lineTo(wye_c * x2 - wye_s * y2, wye_s * x2 + wye_c * y2);
context.lineTo(wye_c * x0 + wye_s * y0, wye_c * y0 - wye_s * x0);
context.lineTo(wye_c * x1 + wye_s * y1, wye_c * y1 - wye_s * x1);
context.lineTo(wye_c * x2 + wye_s * y2, wye_c * y2 - wye_s * x2);
context.closePath();
}
});
// CONCATENATED MODULE: ./node_modules/d3-shape/src/symbol.js
var symbol_symbols = [
symbol_circle,
symbol_cross,
diamond,
symbol_square,
star,
triangle,
wye
];
/* harmony default export */ var src_symbol = (function() {
var type = d3_shape_src_constant(symbol_circle),
size = d3_shape_src_constant(64),
context = null;
function symbol() {
var buffer;
if (!context) context = buffer = src_path();
type.apply(this, arguments).draw(context, +size.apply(this, arguments));
if (buffer) return context = null, buffer + "" || null;
}
symbol.type = function(_) {
return arguments.length ? (type = typeof _ === "function" ? _ : d3_shape_src_constant(_), symbol) : type;
};
symbol.size = function(_) {
return arguments.length ? (size = typeof _ === "function" ? _ : d3_shape_src_constant(+_), symbol) : size;
};
symbol.context = function(_) {
return arguments.length ? (context = _ == null ? null : _, symbol) : context;
};
return symbol;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/path/shapes.js
function shapes_value(a, b) {
return a != null ? a : b;
}
const shapes_x = item => item.x || 0,
shapes_y = item => item.y || 0,
shapes_w = item => item.width || 0,
shapes_h = item => item.height || 0,
shapes_xw = item => (item.x || 0) + (item.width || 0),
shapes_yh = item => (item.y || 0) + (item.height || 0),
shapes_sa = item => item.startAngle || 0,
shapes_ea = item => item.endAngle || 0,
shapes_pa = item => item.padAngle || 0,
shapes_ir = item => item.innerRadius || 0,
shapes_or = item => item.outerRadius || 0,
shapes_cr = item => item.cornerRadius || 0,
shapes_tl = item => shapes_value(item.cornerRadiusTopLeft, item.cornerRadius) || 0,
shapes_tr = item => shapes_value(item.cornerRadiusTopRight, item.cornerRadius) || 0,
shapes_br = item => shapes_value(item.cornerRadiusBottomRight, item.cornerRadius) || 0,
shapes_bl = item => shapes_value(item.cornerRadiusBottomLeft, item.cornerRadius) || 0,
shapes_sz = item => shapes_value(item.size, 64),
shapes_ts = item => item.size || 1,
shapes_def = item => !(item.defined === false),
shapes_type = item => symbols_symbols(item.shape || 'circle');
const shapes_arcShape = src_arc().startAngle(shapes_sa).endAngle(shapes_ea).padAngle(shapes_pa)
.innerRadius(shapes_ir).outerRadius(shapes_or).cornerRadius(shapes_cr),
shapes_areavShape = src_area().x(shapes_x).y1(shapes_y).y0(shapes_yh).defined(shapes_def),
shapes_areahShape = src_area().y(shapes_y).x1(shapes_x).x0(shapes_xw).defined(shapes_def),
shapes_lineShape = src_line().x(shapes_x).y(shapes_y).defined(shapes_def),
shapes_rectShape = path_rectangle().x(shapes_x).y(shapes_y).width(shapes_w).height(shapes_h)
.cornerRadius(shapes_tl, shapes_tr, shapes_br, shapes_bl),
shapes_symbolShape = src_symbol().type(shapes_type).size(shapes_sz),
shapes_trailShape = path_trail().x(shapes_x).y(shapes_y).defined(shapes_def).size(shapes_ts);
function shapes_hasCornerRadius(item) {
return item.cornerRadius
|| item.cornerRadiusTopLeft
|| item.cornerRadiusTopRight
|| item.cornerRadiusBottomRight
|| item.cornerRadiusBottomLeft;
}
function shapes_arc(context, item) {
return shapes_arcShape.context(context)(item);
}
function shapes_area(context, items) {
var item = items[0],
interp = item.interpolate || 'linear';
return (item.orient === 'horizontal' ? shapes_areahShape : shapes_areavShape)
.curve(curves_curves(interp, item.orient, item.tension))
.context(context)(items);
}
function shapes_line(context, items) {
var item = items[0],
interp = item.interpolate || 'linear';
return shapes_lineShape.curve(curves_curves(interp, item.orient, item.tension))
.context(context)(items);
}
function shapes_rectangle(context, item, x, y) {
return shapes_rectShape.context(context)(item, x, y);
}
function shapes_shape(context, item) {
return (item.mark.shape || item.shape)
.context(context)(item);
}
function shapes_symbol(context, item) {
return shapes_symbolShape.context(context)(item);
}
function shapes_trail(context, items) {
return shapes_trailShape.context(context)(items);
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/bound/boundStroke.js
/* harmony default export */ var boundStroke = (function(bounds, item, miter) {
if (item.stroke && item.opacity !== 0 && item.strokeOpacity !== 0) {
const sw = item.strokeWidth != null ? +item.strokeWidth : 1;
bounds.expand(sw + (miter ? miterAdjustment(item, sw) : 0));
}
return bounds;
});
function miterAdjustment(item, strokeWidth) {
// TODO: more sophisticated adjustment? Or miter support in boundContext?
return item.strokeJoin && item.strokeJoin !== 'miter' ? 0 : strokeWidth;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/bound/boundContext.js
var boundContext_bounds, boundContext_lx, boundContext_ly,
boundContext_circleThreshold = Tau - 1e-8;
function boundContext_context(_) {
boundContext_bounds = _;
return boundContext_context;
}
function boundContext_noop() {}
function boundContext_add(x, y) { boundContext_bounds.add(x, y); }
function boundContext_addL(x, y) { boundContext_add(boundContext_lx = x, boundContext_ly = y); }
function boundContext_addX(x) { boundContext_add(x, boundContext_bounds.y1); }
function boundContext_addY(y) { boundContext_add(boundContext_bounds.x1, y); }
boundContext_context.beginPath = boundContext_noop;
boundContext_context.closePath = boundContext_noop;
boundContext_context.moveTo = boundContext_addL;
boundContext_context.lineTo = boundContext_addL;
boundContext_context.rect = function(x, y, w, h) {
boundContext_add(x + w, y + h);
boundContext_addL(x, y);
};
boundContext_context.quadraticCurveTo = function(x1, y1, x2, y2) {
boundContext_quadExtrema(boundContext_lx, x1, x2, boundContext_addX);
boundContext_quadExtrema(boundContext_ly, y1, y2, boundContext_addY);
boundContext_addL(x2, y2);
};
function boundContext_quadExtrema(x0, x1, x2, cb) {
const t = (x0 - x1) / (x0 + x2 - 2 * x1);
if (0 < t && t < 1) cb(x0 + (x1 - x0) * t);
}
boundContext_context.bezierCurveTo = function(x1, y1, x2, y2, x3, y3) {
boundContext_cubicExtrema(boundContext_lx, x1, x2, x3, boundContext_addX);
boundContext_cubicExtrema(boundContext_ly, y1, y2, y3, boundContext_addY);
boundContext_addL(x3, y3);
};
function boundContext_cubicExtrema(x0, x1, x2, x3, cb) {
const a = x3 - x0 + 3 * x1 - 3 * x2,
b = x0 + x2 - 2 * x1,
c = x0 - x1;
let t0 = 0, t1 = 0, r;
// solve for parameter t
if (Math.abs(a) > Epsilon) {
// quadratic equation
r = b * b + c * a;
if (r >= 0) {
r = Math.sqrt(r);
t0 = (-b + r) / a;
t1 = (-b - r) / a;
}
} else {
// linear equation
t0 = 0.5 * c / b;
}
// calculate position
if (0 < t0 && t0 < 1) cb(boundContext_cubic(t0, x0, x1, x2, x3));
if (0 < t1 && t1 < 1) cb(boundContext_cubic(t1, x0, x1, x2, x3));
}
function boundContext_cubic(t, x0, x1, x2, x3) {
const s = 1 - t, s2 = s * s, t2 = t * t;
return (s2 * s * x0) + (3 * s2 * t * x1) + (3 * s * t2 * x2) + (t2 * t * x3);
}
boundContext_context.arc = function(cx, cy, r, sa, ea, ccw) {
// store last point on path
boundContext_lx = r * Math.cos(ea) + cx;
boundContext_ly = r * Math.sin(ea) + cy;
if (Math.abs(ea - sa) > boundContext_circleThreshold) {
// treat as full circle
boundContext_add(cx - r, cy - r);
boundContext_add(cx + r, cy + r);
} else {
const update = a => boundContext_add(r * Math.cos(a) + cx, r * Math.sin(a) + cy);
let s, i;
// sample end points
update(sa);
update(ea);
// sample interior points aligned with 90 degrees
if (ea !== sa) {
sa = sa % Tau; if (sa < 0) sa += Tau;
ea = ea % Tau; if (ea < 0) ea += Tau;
if (ea < sa) {
ccw = !ccw; // flip direction
s = sa; sa = ea; ea = s; // swap end-points
}
if (ccw) {
ea -= Tau;
s = sa - (sa % HalfPi);
for (i=0; i<4 && s>ea; ++i, s-=HalfPi) update(s);
} else {
s = sa - (sa % HalfPi) + HalfPi;
for (i=0; i<4 && s<ea; ++i, s=s+HalfPi) update(s);
}
}
}
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/context.js
var context_context = (context_context = domCanvas(1,1))
? context_context.getContext('2d')
: null;
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/intersect.js
const intersect_b = new Bounds();
function intersect_intersectPath(draw) {
return function(item, brush) {
// rely on (inaccurate) bounds intersection if no context
if (!context_context) return true;
// add path to offscreen graphics context
draw(context_context, item);
// get bounds intersection region
intersect_b.clear().union(item.bounds).intersect(brush).round();
const {x1, y1, x2, y2} = intersect_b;
// iterate over intersection region
// perform fine grained inclusion test
for (let y = y1; y <= y2; ++y) {
for (let x = x1; x <= x2; ++x) {
if (context_context.isPointInPath(x, y)) {
return true;
}
}
}
// false if no hits in intersection region
return false;
}
}
function intersect_intersectPoint(item, box) {
return box.contains(item.x || 0, item.y || 0);
}
function intersect_intersectRect(item, box) {
const x = item.x || 0,
y = item.y || 0,
w = item.width || 0,
h = item.height || 0;
return box.intersects(intersect_b.set(x, y, x + w, y + h));
}
function intersect_intersectRule(item, box) {
const x = item.x || 0,
y = item.y || 0,
x2 = item.x2 != null ? item.x2 : x,
y2 = item.y2 != null ? item.y2 : y;
return intersect_intersectBoxLine(box, x, y, x2, y2);
}
function intersect_intersectBoxLine(box, x, y, u, v) {
const {x1, y1, x2, y2} = box,
dx = u - x,
dy = v - y;
let t0 = 0, t1 = 1, p, q, r, e;
for (e=0; e<4; ++e) {
if (e === 0) { p = -dx; q = -(x1 - x); }
if (e === 1) { p = dx; q = (x2 - x); }
if (e === 2) { p = -dy; q = -(y1 - y); }
if (e === 3) { p = dy; q = (y2 - y); }
if (Math.abs(p) < 1e-10 && q < 0) return false;
r = q / p;
if (p < 0) {
if (r > t1) return false;
else if (r > t0) t0 = r;
} else if (p > 0) {
if (r < t0) return false;
else if (r < t1) t1 = r;
}
}
return true;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/blend.js
/* harmony default export */ var blend = (function(context, item) {
context.globalCompositeOperation = item.blend || 'source-over';
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/gradient.js
function gradient_v(value, dflt) {
return value == null ? dflt : value;
}
function gradient_addStops(gradient, stops) {
const n = stops.length;
for (let i=0; i<n; ++i) {
gradient.addColorStop(stops[i].offset, stops[i].color);
}
return gradient;
}
/* harmony default export */ var canvas_gradient = (function(context, spec, bounds) {
const w = bounds.width(),
h = bounds.height();
let gradient;
if (spec.gradient === 'radial') {
gradient = context.createRadialGradient(
bounds.x1 + gradient_v(spec.x1, 0.5) * w,
bounds.y1 + gradient_v(spec.y1, 0.5) * h,
Math.max(w, h) * gradient_v(spec.r1, 0),
bounds.x1 + gradient_v(spec.x2, 0.5) * w,
bounds.y1 + gradient_v(spec.y2, 0.5) * h,
Math.max(w, h) * gradient_v(spec.r2, 0.5)
);
} else { // linear gradient
const x1 = gradient_v(spec.x1, 0),
y1 = gradient_v(spec.y1, 0),
x2 = gradient_v(spec.x2, 1),
y2 = gradient_v(spec.y2, 0);
if (x1 === x2 || y1 === y2 || w === h) {
// axis aligned: use normal gradient
gradient = context.createLinearGradient(
bounds.x1 + x1 * w,
bounds.y1 + y1 * h,
bounds.x1 + x2 * w,
bounds.y1 + y2 * h
);
} else {
// not axis aligned: render gradient into a pattern (#2365)
// this allows us to use normalized bounding box coordinates
const image = domCanvas(Math.ceil(w), Math.ceil(h)),
ictx = image.getContext('2d');
ictx.scale(w, h);
ictx.fillStyle = gradient_addStops(
ictx.createLinearGradient(x1, y1, x2, y2),
spec.stops
);
ictx.fillRect(0, 0, w, h);
return context.createPattern(image, 'no-repeat');
}
}
return gradient_addStops(gradient, spec.stops);
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/color.js
/* harmony default export */ var canvas_color = (function(context, item, value) {
return isGradient(value)
? canvas_gradient(context, value, item.bounds)
: value;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/fill.js
/* harmony default export */ var canvas_fill = (function(context, item, opacity) {
opacity *= (item.fillOpacity==null ? 1 : item.fillOpacity);
if (opacity > 0) {
context.globalAlpha = opacity;
context.fillStyle = canvas_color(context, item, item.fill);
return true;
} else {
return false;
}
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/stroke.js
var stroke_Empty = [];
/* harmony default export */ var canvas_stroke = (function(context, item, opacity) {
var lw = (lw = item.strokeWidth) != null ? lw : 1;
if (lw <= 0) return false;
opacity *= (item.strokeOpacity==null ? 1 : item.strokeOpacity);
if (opacity > 0) {
context.globalAlpha = opacity;
context.strokeStyle = canvas_color(context, item, item.stroke);
context.lineWidth = lw;
context.lineCap = item.strokeCap || 'butt';
context.lineJoin = item.strokeJoin || 'miter';
context.miterLimit = item.strokeMiterLimit || 10;
if (context.setLineDash) {
context.setLineDash(item.strokeDash || stroke_Empty);
context.lineDashOffset = item.strokeDashOffset || 0;
}
return true;
} else {
return false;
}
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/visit.js
function visit_compare(a, b) {
return a.zindex - b.zindex || a.index - b.index;
}
function zorder(scene) {
if (!scene.zdirty) return scene.zitems;
var items = scene.items,
output = [], item, i, n;
for (i=0, n=items.length; i<n; ++i) {
item = items[i];
item.index = i;
if (item.zindex) output.push(item);
}
scene.zdirty = false;
return scene.zitems = output.sort(visit_compare);
}
function visit_visit(scene, visitor) {
var items = scene.items, i, n;
if (!items || !items.length) return;
var zitems = zorder(scene);
if (zitems && zitems.length) {
for (i=0, n=items.length; i<n; ++i) {
if (!items[i].zindex) visitor(items[i]);
}
items = zitems;
}
for (i=0, n=items.length; i<n; ++i) {
visitor(items[i]);
}
}
function pickVisit(scene, visitor) {
var items = scene.items, hit, i;
if (!items || !items.length) return null;
var zitems = zorder(scene);
if (zitems && zitems.length) items = zitems;
for (i=items.length; --i >= 0;) {
if (hit = visitor(items[i])) return hit;
}
if (items === zitems) {
for (items=scene.items, i=items.length; --i >= 0;) {
if (!items[i].zindex) {
if (hit = visitor(items[i])) return hit;
}
}
}
return null;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/draw.js
function draw_drawAll(path) {
return function(context, scene, bounds) {
visit_visit(scene, function(item) {
if (!bounds || bounds.intersects(item.bounds)) {
draw_drawPath(path, context, item, item);
}
});
};
}
function draw_drawOne(path) {
return function(context, scene, bounds) {
if (scene.items.length && (!bounds || bounds.intersects(scene.bounds))) {
draw_drawPath(path, context, scene.items[0], scene.items);
}
};
}
function draw_drawPath(path, context, item, items) {
var opacity = item.opacity == null ? 1 : item.opacity;
if (opacity === 0) return;
if (path(context, items)) return;
blend(context, item);
if (item.fill && canvas_fill(context, item, opacity)) {
context.fill();
}
if (item.stroke && canvas_stroke(context, item, opacity)) {
context.stroke();
}
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/pick.js
function pick_pick(test) {
test = test || vega_util["Ga" /* truthy */];
return function(context, scene, x, y, gx, gy) {
x *= context.pixelRatio;
y *= context.pixelRatio;
return pickVisit(scene, function(item) {
var b = item.bounds;
// first hit test against bounding box
if ((b && !b.contains(gx, gy)) || !b) return;
// if in bounding box, perform more careful test
if (test(context, item, x, y, gx, gy)) return item;
});
};
}
function pick_hitPath(path, filled) {
return function(context, o, x, y) {
var item = Array.isArray(o) ? o[0] : o,
fill = (filled == null) ? item.fill : filled,
stroke = item.stroke && context.isPointInStroke, lw, lc;
if (stroke) {
lw = item.strokeWidth;
lc = item.strokeCap;
context.lineWidth = lw != null ? lw : 1;
context.lineCap = lc != null ? lc : 'butt';
}
return path(context, o) ? false :
(fill && context.isPointInPath(x, y)) ||
(stroke && context.isPointInStroke(x, y));
};
}
function pick_pickPath(path) {
return pick_pick(pick_hitPath(path));
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/svg/transform.js
function transform_translate(x, y) {
return 'translate(' + x + ',' + y + ')';
}
function transform_rotate(a) {
return 'rotate(' + a + ')';
}
function transform_scale(scaleX, scaleY){
return 'scale('+ scaleX + ',' + scaleY+')';
}
function translateItem(item) {
return transform_translate(item.x || 0, item.y || 0);
}
function transformItem(item) {
return transform_translate(item.x || 0, item.y || 0)
+ (item.angle ? ' ' + transform_rotate(item.angle) : '')
+ (item.scaleX || item.scaleY ? ' ' + transform_scale(item.scaleX || 1, item.scaleY || 1) : '');
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/markItemPath.js
/* harmony default export */ var markItemPath = (function(type, shape, isect) {
function attr(emit, item) {
emit('transform', transformItem(item));
emit('d', shape(null, item));
}
function bound(bounds, item) {
var x = item.x || 0,
y = item.y || 0;
shape(boundContext_context(bounds), item);
boundStroke(bounds, item).translate(x, y);
if (item.angle) {
bounds.rotate(item.angle * DegToRad, x, y);
}
return bounds;
}
function draw(context, item) {
var x = item.x || 0,
y = item.y || 0,
a = item.angle || 0;
context.translate(x, y);
if (a) context.rotate(a *= DegToRad);
context.beginPath();
shape(context, item);
if (a) context.rotate(-a);
context.translate(-x, -y);
}
return {
type: type,
tag: 'path',
nested: false,
attr: attr,
bound: bound,
draw: draw_drawAll(draw),
pick: pick_pickPath(draw),
isect: isect || intersect_intersectPath(draw)
};
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/arc.js
/* harmony default export */ var marks_arc = (markItemPath('arc', shapes_arc));
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/pickPath.js
function pickArea(a, p) {
var v = a[0].orient === 'horizontal' ? p[1] : p[0],
z = a[0].orient === 'horizontal' ? 'y' : 'x',
i = a.length,
min = +Infinity, hit, d;
while (--i >= 0) {
if (a[i].defined === false) continue;
d = Math.abs(a[i][z] - v);
if (d < min) {
min = d;
hit = a[i];
}
}
return hit;
}
function pickLine(a, p) {
var t = Math.pow(a[0].strokeWidth || 1, 2),
i = a.length, dx, dy, dd;
while (--i >= 0) {
if (a[i].defined === false) continue;
dx = a[i].x - p[0];
dy = a[i].y - p[1];
dd = dx * dx + dy * dy;
if (dd < t) return a[i];
}
return null;
}
function pickTrail(a, p) {
var i = a.length, dx, dy, dd;
while (--i >= 0) {
if (a[i].defined === false) continue;
dx = a[i].x - p[0];
dy = a[i].y - p[1];
dd = dx * dx + dy * dy;
dx = a[i].size || 1;
if (dd < dx*dx) return a[i];
}
return null;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/markMultiItemPath.js
/* harmony default export */ var markMultiItemPath = (function(type, shape, tip) {
function attr(emit, item) {
var items = item.mark.items;
if (items.length) emit('d', shape(null, items));
}
function bound(bounds, mark) {
var items = mark.items;
if (items.length === 0) {
return bounds;
} else {
shape(boundContext_context(bounds), items);
return boundStroke(bounds, items[0]);
}
}
function draw(context, items) {
context.beginPath();
shape(context, items);
}
var hit = pick_hitPath(draw);
function pick(context, scene, x, y, gx, gy) {
var items = scene.items,
b = scene.bounds;
if (!items || !items.length || b && !b.contains(gx, gy)) {
return null;
}
x *= context.pixelRatio;
y *= context.pixelRatio;
return hit(context, items, x, y) ? items[0] : null;
}
return {
type: type,
tag: 'path',
nested: true,
attr: attr,
bound: bound,
draw: draw_drawOne(draw),
pick: pick,
isect: intersect_intersectPoint,
tip: tip
};
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/area.js
/* harmony default export */ var marks_area = (markMultiItemPath('area', shapes_area, pickArea));
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/clip.js
/* harmony default export */ var canvas_clip = (function(context, scene) {
var clip = scene.clip;
context.save();
if (Object(vega_util["D" /* isFunction */])(clip)) {
context.beginPath();
clip(context);
context.clip();
} else {
clip_clipGroup(context, scene.group);
}
});
function clip_clipGroup(context, group) {
context.beginPath();
shapes_hasCornerRadius(group)
? shapes_rectangle(context, group, 0, 0)
: context.rect(0, 0, group.width || 0, group.height || 0);
context.clip();
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/svg/clip.js
var clip_clip_id = 1;
function clip_resetSVGClipId() {
clip_clip_id = 1;
}
/* harmony default export */ var svg_clip = (function(renderer, item, size) {
var clip = item.clip,
defs = renderer._defs,
id = item.clip_id || (item.clip_id = 'clip' + clip_clip_id++),
c = defs.clipping[id] || (defs.clipping[id] = {id: id});
if (Object(vega_util["D" /* isFunction */])(clip)) {
c.path = clip(null);
} else if (shapes_hasCornerRadius(size)) {
c.path = shapes_rectangle(null, size, 0, 0);
} else {
c.width = size.width || 0;
c.height = size.height || 0;
}
return 'url(#' + id + ')';
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/group.js
function group_offset(item) {
var sw = (sw = item.strokeWidth) != null ? sw : 1;
return item.strokeOffset != null ? item.strokeOffset
: item.stroke && sw > 0.5 && sw < 1.5 ? 0.5 - Math.abs(sw - 1)
: 0;
}
function group_attr(emit, item) {
emit('transform', translateItem(item));
}
function group_emitRectangle(emit, item) {
var off = group_offset(item);
emit('d', shapes_rectangle(null, item, off, off));
}
function group_background(emit, item) {
emit('class', 'background');
group_emitRectangle(emit, item);
}
function group_foreground(emit, item) {
emit('class', 'foreground');
if (item.strokeForeground) {
group_emitRectangle(emit, item);
} else {
emit('d', '');
}
}
function group_content(emit, item, renderer) {
var url = item.clip ? svg_clip(renderer, item, item) : null;
emit('clip-path', url);
}
function group_bound(bounds, group) {
if (!group.clip && group.items) {
var items = group.items;
for (var j=0, m=items.length; j<m; ++j) {
bounds.union(items[j].bounds);
}
}
if ((group.clip || group.width || group.height) && !group.noBound) {
bounds.add(0, 0).add(group.width || 0, group.height || 0);
}
boundStroke(bounds, group);
return bounds.translate(group.x || 0, group.y || 0);
}
function group_rectanglePath(context, group, x, y) {
var off = group_offset(group);
context.beginPath();
shapes_rectangle(context, group, (x || 0) + off, (y || 0) + off);
}
var group_hitBackground = pick_hitPath(group_rectanglePath);
var group_hitForeground = pick_hitPath(group_rectanglePath, false);
function group_draw(context, scene, bounds) {
var renderer = this;
visit_visit(scene, function(group) {
var gx = group.x || 0,
gy = group.y || 0,
fore = group.strokeForeground,
opacity = group.opacity == null ? 1 : group.opacity;
// draw group background
if ((group.stroke || group.fill) && opacity) {
group_rectanglePath(context, group, gx, gy);
blend(context, group);
if (group.fill && canvas_fill(context, group, opacity)) {
context.fill();
}
if (group.stroke && !fore && canvas_stroke(context, group, opacity)) {
context.stroke();
}
}
// setup graphics context, set clip and bounds
context.save();
context.translate(gx, gy);
if (group.clip) clip_clipGroup(context, group);
if (bounds) bounds.translate(-gx, -gy);
// draw group contents
visit_visit(group, function(item) {
renderer.draw(context, item, bounds);
});
// restore graphics context
if (bounds) bounds.translate(gx, gy);
context.restore();
// draw group foreground
if (fore && group.stroke && opacity) {
group_rectanglePath(context, group, gx, gy);
blend(context, group);
if (canvas_stroke(context, group, opacity)) {
context.stroke();
}
}
});
}
function group_pick(context, scene, x, y, gx, gy) {
if (scene.bounds && !scene.bounds.contains(gx, gy) || !scene.items) {
return null;
}
var handler = this,
cx = x * context.pixelRatio,
cy = y * context.pixelRatio;
return pickVisit(scene, function(group) {
var hit, fore, ix, dx, dy, dw, dh, b, c;
// first hit test bounding box
b = group.bounds;
if (b && !b.contains(gx, gy)) return;
// passed bounds check, test rectangular clip
dx = group.x || 0;
dy = group.y || 0;
dw = dx + (group.width || 0);
dh = dy + (group.height || 0);
c = group.clip;
if (c && (gx < dx || gx > dw || gy < dx || gy > dh)) return;
// adjust coordinate system
context.save();
context.translate(dx, dy);
dx = gx - dx;
dy = gy - dy;
// test background for rounded corner clip
if (c && shapes_hasCornerRadius(group) && !group_hitBackground(context, group, cx, cy)) {
context.restore();
return null;
}
fore = group.strokeForeground;
ix = scene.interactive !== false;
// hit test against group foreground
if (ix && fore && group.stroke
&& group_hitForeground(context, group, cx, cy)) {
context.restore();
return group;
}
// hit test against contained marks
hit = pickVisit(group, function(mark) {
return group_pickMark(mark, dx, dy)
? handler.pick(mark, x, y, dx, dy)
: null;
});
// hit test against group background
if (!hit && ix && (group.fill || (!fore && group.stroke))
&& group_hitBackground(context, group, cx, cy)) {
hit = group;
}
// restore state and return
context.restore();
return hit || null;
});
}
function group_pickMark(mark, x, y) {
return (mark.interactive !== false || mark.marktype === 'group')
&& mark.bounds && mark.bounds.contains(x, y);
}
/* harmony default export */ var marks_group = ({
type: 'group',
tag: 'g',
nested: false,
attr: group_attr,
bound: group_bound,
draw: group_draw,
pick: group_pick,
isect: intersect_intersectRect,
content: group_content,
background: group_background,
foreground: group_foreground
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/image.js
function image_getImage(item, renderer) {
var image = item.image;
if (!image || item.url && item.url !== image.url) {
image = {complete: false, width: 0, height: 0};
renderer.loadImage(item.url).then(image => {
item.image = image;
item.image.url = item.url;
});
}
return image;
}
function image_imageWidth(item, image) {
return item.width != null ? item.width
: !image || !image.width ? 0
: item.aspect !== false && item.height ? item.height * image.width / image.height
: image.width;
}
function image_imageHeight(item, image) {
return item.height != null ? item.height
: !image || !image.height ? 0
: item.aspect !== false && item.width ? item.width * image.height / image.width
: image.height;
}
function image_imageXOffset(align, w) {
return align === 'center' ? w / 2 : align === 'right' ? w : 0;
}
function image_imageYOffset(baseline, h) {
return baseline === 'middle' ? h / 2 : baseline === 'bottom' ? h : 0;
}
function image_attr(emit, item, renderer) {
var image = image_getImage(item, renderer),
x = item.x || 0,
y = item.y || 0,
w = image_imageWidth(item, image),
h = image_imageHeight(item, image),
a = item.aspect === false ? 'none' : 'xMidYMid';
x -= image_imageXOffset(item.align, w);
y -= image_imageYOffset(item.baseline, h);
if (!image.src && image.toDataURL) {
emit('href', image.toDataURL(), 'http://www.w3.org/1999/xlink', 'xlink:href');
} else {
emit('href', image.src || '', 'http://www.w3.org/1999/xlink', 'xlink:href');
}
emit('transform', transform_translate(x, y));
emit('width', w);
emit('height', h);
emit('preserveAspectRatio', a);
}
function image_bound(bounds, item) {
var image = item.image,
x = item.x || 0,
y = item.y || 0,
w = image_imageWidth(item, image),
h = image_imageHeight(item, image);
x -= image_imageXOffset(item.align, w);
y -= image_imageYOffset(item.baseline, h);
return bounds.set(x, y, x + w, y + h);
}
function image_draw(context, scene, bounds) {
var renderer = this;
visit_visit(scene, function(item) {
if (bounds && !bounds.intersects(item.bounds)) return; // bounds check
var image = image_getImage(item, renderer),
x = item.x || 0,
y = item.y || 0,
w = image_imageWidth(item, image),
h = image_imageHeight(item, image),
opacity, ar0, ar1, t;
x -= image_imageXOffset(item.align, w);
y -= image_imageYOffset(item.baseline, h);
if (item.aspect !== false) {
ar0 = image.width / image.height;
ar1 = item.width / item.height;
if (ar0 === ar0 && ar1 === ar1 && ar0 !== ar1) {
if (ar1 < ar0) {
t = w / ar0;
y += (h - t) / 2;
h = t;
} else {
t = h * ar0;
x += (w - t) / 2;
w = t;
}
}
}
if (image.complete || image.toDataURL) {
blend(context, item);
context.globalAlpha = (opacity = item.opacity) != null ? opacity : 1;
context.imageSmoothingEnabled = item.smooth !== false;
context.drawImage(image, x, y, w, h);
}
});
}
/* harmony default export */ var marks_image = ({
type: 'image',
tag: 'image',
nested: false,
attr: image_attr,
bound: image_bound,
draw: image_draw,
pick: pick_pick(),
isect: vega_util["Ga" /* truthy */], // bounds check is sufficient
get: image_getImage,
xOffset: image_imageXOffset,
yOffset: image_imageYOffset
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/line.js
/* harmony default export */ var marks_line = (markMultiItemPath('line', shapes_line, pickLine));
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/path.js
function path_attr(emit, item) {
var sx = item.scaleX || 1,
sy = item.scaleY || 1;
if (sx !== 1 || sy !== 1) {
emit('vector-effect', 'non-scaling-stroke');
}
emit('transform', transformItem(item));
emit('d', item.path);
}
function marks_path_path(context, item) {
var path = item.path;
if (path == null) return true;
var x = item.x || 0,
y = item.y || 0,
sx = item.scaleX || 1,
sy = item.scaleY || 1,
a = (item.angle || 0) * DegToRad,
cache = item.pathCache;
if (!cache || cache.path !== path) {
(item.pathCache = cache = path_parse(path)).path = path;
}
if (a && context.rotate && context.translate) {
context.translate(x, y);
context.rotate(a);
path_render(context, cache, 0, 0, sx, sy);
context.rotate(-a);
context.translate(-x, -y);
} else {
path_render(context, cache, x, y, sx, sy);
}
}
function path_bound(bounds, item) {
marks_path_path(boundContext_context(bounds), item)
? bounds.set(0, 0, 0, 0)
: boundStroke(bounds, item, true);
if (item.angle) {
bounds.rotate(item.angle * DegToRad, item.x || 0, item.y || 0);
}
return bounds;
}
/* harmony default export */ var marks_path = ({
type: 'path',
tag: 'path',
nested: false,
attr: path_attr,
bound: path_bound,
draw: draw_drawAll(marks_path_path),
pick: pick_pickPath(marks_path_path),
isect: intersect_intersectPath(marks_path_path)
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/rect.js
function rect_attr(emit, item) {
emit('d', shapes_rectangle(null, item));
}
function rect_bound(bounds, item) {
var x, y;
return boundStroke(bounds.set(
x = item.x || 0,
y = item.y || 0,
(x + item.width) || 0,
(y + item.height) || 0
), item);
}
function rect_draw(context, item) {
context.beginPath();
shapes_rectangle(context, item);
}
/* harmony default export */ var marks_rect = ({
type: 'rect',
tag: 'path',
nested: false,
attr: rect_attr,
bound: rect_bound,
draw: draw_drawAll(rect_draw),
pick: pick_pickPath(rect_draw),
isect: intersect_intersectRect
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/rule.js
function rule_attr(emit, item) {
emit('transform', translateItem(item));
emit('x2', item.x2 != null ? item.x2 - (item.x || 0) : 0);
emit('y2', item.y2 != null ? item.y2 - (item.y || 0) : 0);
}
function rule_bound(bounds, item) {
var x1, y1;
return boundStroke(bounds.set(
x1 = item.x || 0,
y1 = item.y || 0,
item.x2 != null ? item.x2 : x1,
item.y2 != null ? item.y2 : y1
), item);
}
function rule_path(context, item, opacity) {
var x1, y1, x2, y2;
if (item.stroke && canvas_stroke(context, item, opacity)) {
x1 = item.x || 0;
y1 = item.y || 0;
x2 = item.x2 != null ? item.x2 : x1;
y2 = item.y2 != null ? item.y2 : y1;
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
return true;
}
return false;
}
function rule_draw(context, scene, bounds) {
visit_visit(scene, function(item) {
if (bounds && !bounds.intersects(item.bounds)) return; // bounds check
var opacity = item.opacity == null ? 1 : item.opacity;
if (opacity && rule_path(context, item, opacity)) {
blend(context, item);
context.stroke();
}
});
}
function rule_hit(context, item, x, y) {
if (!context.isPointInStroke) return false;
return rule_path(context, item, 1) && context.isPointInStroke(x, y);
}
/* harmony default export */ var marks_rule = ({
type: 'rule',
tag: 'line',
nested: false,
attr: rule_attr,
bound: rule_bound,
draw: rule_draw,
pick: pick_pick(rule_hit),
isect: intersect_intersectRule
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/shape.js
/* harmony default export */ var marks_shape = (markItemPath('shape', shapes_shape));
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/symbol.js
/* harmony default export */ var marks_symbol = (markItemPath('symbol', shapes_symbol, intersect_intersectPoint));
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/text.js
// memoize text width measurement
const text_widthCache = Object(vega_util["L" /* lruCache */])();
var text_textMetrics = {
height: text_fontSize,
measureWidth: text_measureWidth,
estimateWidth: text_estimateWidth,
width: text_estimateWidth,
canvas: text_useCanvas
};
text_useCanvas(true);
function text_useCanvas(use) {
text_textMetrics.width = (use && context_context) ? text_measureWidth : text_estimateWidth;
}
// make dumb, simple estimate if no canvas is available
function text_estimateWidth(item, text) {
return util_text_estimateWidth(text_textValue(item, text), text_fontSize(item));
}
function util_text_estimateWidth(text, currentFontHeight) {
return ~~(0.8 * text.length * currentFontHeight);
}
// measure text width if canvas is available
function text_measureWidth(item, text) {
return text_fontSize(item) <= 0 || !(text = text_textValue(item, text)) ? 0
: util_text_measureWidth(text, text_font(item));
}
function util_text_measureWidth(text, currentFont) {
const key = `(${currentFont}) ${text}`;
let width = text_widthCache.get(key);
if (width === undefined) {
context_context.font = currentFont;
width = context_context.measureText(text).width;
text_widthCache.set(key, width);
}
return width;
}
function text_fontSize(item) {
return item.fontSize != null ? (+item.fontSize || 0) : 11;
}
function text_lineHeight(item) {
return item.lineHeight != null ? item.lineHeight : (text_fontSize(item) + 2);
}
function text_lineArray(_) {
return Object(vega_util["A" /* isArray */])(_) ? _.length > 1 ? _ : _[0] : _;
}
function text_textLines(item) {
return text_lineArray(
item.lineBreak && item.text && !Object(vega_util["A" /* isArray */])(item.text)
? item.text.split(item.lineBreak)
: item.text
);
}
function text_multiLineOffset(item) {
const tl = text_textLines(item);
return (Object(vega_util["A" /* isArray */])(tl) ? (tl.length - 1) : 0) * text_lineHeight(item);
}
function text_textValue(item, line) {
const text = line == null ? '' : (line + '').trim();
return item.limit > 0 && text.length ? text_truncate(item, text) : text;
}
function text_widthGetter(item) {
if (text_textMetrics.width === text_measureWidth) {
// we are using canvas
const currentFont = text_font(item);
return text => util_text_measureWidth(text, currentFont);
} else {
// we are relying on estimates
const currentFontHeight = text_fontSize(item);
return text => util_text_estimateWidth(text, currentFontHeight);
}
}
function text_truncate(item, text) {
var limit = +item.limit,
width = text_widthGetter(item);
if (width(text) < limit) return text;
var ellipsis = item.ellipsis || '\u2026',
rtl = item.dir === 'rtl',
lo = 0,
hi = text.length, mid;
limit -= width(ellipsis);
if (rtl) {
while (lo < hi) {
mid = (lo + hi >>> 1);
if (width(text.slice(mid)) > limit) lo = mid + 1;
else hi = mid;
}
return ellipsis + text.slice(lo);
} else {
while (lo < hi) {
mid = 1 + (lo + hi >>> 1);
if (width(text.slice(0, mid)) < limit) lo = mid;
else hi = mid - 1;
}
return text.slice(0, lo) + ellipsis;
}
}
function text_fontFamily(item, quote) {
var font = item.font;
return (quote && font
? String(font).replace(/"/g, '\'')
: font) || 'sans-serif';
}
function text_font(item, quote) {
return '' +
(item.fontStyle ? item.fontStyle + ' ' : '') +
(item.fontVariant ? item.fontVariant + ' ' : '') +
(item.fontWeight ? item.fontWeight + ' ' : '') +
text_fontSize(item) + 'px ' +
text_fontFamily(item, quote);
}
function text_offset(item) {
// perform our own font baseline calculation
// why? not all browsers support SVG 1.1 'alignment-baseline' :(
// this also ensures consistent layout across renderers
var baseline = item.baseline,
h = text_fontSize(item);
return Math.round(
baseline === 'top' ? 0.79 * h :
baseline === 'middle' ? 0.30 * h :
baseline === 'bottom' ? -0.21 * h :
baseline === 'line-top' ? 0.29 * h + 0.5 * text_lineHeight(item) :
baseline === 'line-bottom' ? 0.29 * h - 0.5 * text_lineHeight(item) : 0
);
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/text.js
var text_textAlign = {
'left': 'start',
'center': 'middle',
'right': 'end'
};
var text_tempBounds = new Bounds();
function text_anchorPoint(item) {
var x = item.x || 0,
y = item.y || 0,
r = item.radius || 0, t;
if (r) {
t = (item.theta || 0) - HalfPi;
x += r * Math.cos(t);
y += r * Math.sin(t);
}
text_tempBounds.x1 = x;
text_tempBounds.y1 = y;
return text_tempBounds;
}
function text_attr(emit, item) {
var dx = item.dx || 0,
dy = (item.dy || 0) + text_offset(item),
p = text_anchorPoint(item),
x = p.x1,
y = p.y1,
a = item.angle || 0, t;
emit('text-anchor', text_textAlign[item.align] || 'start');
if (a) {
t = transform_translate(x, y) + ' ' + transform_rotate(a);
if (dx || dy) t += ' ' + transform_translate(dx, dy);
} else {
t = transform_translate(x + dx, y + dy);
}
emit('transform', t);
}
function text_bound(bounds, item, mode) {
var h = text_textMetrics.height(item),
a = item.align,
p = text_anchorPoint(item),
x = p.x1,
y = p.y1,
dx = item.dx || 0,
dy = (item.dy || 0) + text_offset(item) - Math.round(0.8*h), // use 4/5 offset
tl = text_textLines(item),
w;
// get dimensions
if (Object(vega_util["A" /* isArray */])(tl)) {
// multi-line text
h += text_lineHeight(item) * (tl.length - 1);
w = tl.reduce((w, t) => Math.max(w, text_textMetrics.width(item, t)), 0);
} else {
// single-line text
w = text_textMetrics.width(item, tl);
}
// horizontal alignment
if (a === 'center') {
dx -= (w / 2);
} else if (a === 'right') {
dx -= w;
} else {
// left by default, do nothing
}
bounds.set(dx+=x, dy+=y, dx+w, dy+h);
if (item.angle && !mode) {
bounds.rotate(item.angle * DegToRad, x, y);
} else if (mode === 2) {
return bounds.rotatedPoints(item.angle * DegToRad, x, y);
}
return bounds;
}
function text_draw(context, scene, bounds) {
visit_visit(scene, function(item) {
var opacity = item.opacity == null ? 1 : item.opacity,
p, x, y, i, lh, tl, str;
if (bounds && !bounds.intersects(item.bounds) || // bounds check
opacity === 0 || item.fontSize <= 0 ||
item.text == null || item.text.length === 0) return;
context.font = text_font(item);
context.textAlign = item.align || 'left';
p = text_anchorPoint(item);
x = p.x1,
y = p.y1;
if (item.angle) {
context.save();
context.translate(x, y);
context.rotate(item.angle * DegToRad);
x = y = 0; // reset x, y
}
x += (item.dx || 0);
y += (item.dy || 0) + text_offset(item);
tl = text_textLines(item);
blend(context, item);
if (Object(vega_util["A" /* isArray */])(tl)) {
lh = text_lineHeight(item);
for (i=0; i<tl.length; ++i) {
str = text_textValue(item, tl[i]);
if (item.fill && canvas_fill(context, item, opacity)) {
context.fillText(str, x, y);
}
if (item.stroke && canvas_stroke(context, item, opacity)) {
context.strokeText(str, x, y);
}
y += lh;
}
} else {
str = text_textValue(item, tl);
if (item.fill && canvas_fill(context, item, opacity)) {
context.fillText(str, x, y);
}
if (item.stroke && canvas_stroke(context, item, opacity)) {
context.strokeText(str, x, y);
}
}
if (item.angle) context.restore();
});
}
function text_hit(context, item, x, y, gx, gy) {
if (item.fontSize <= 0) return false;
if (!item.angle) return true; // bounds sufficient if no rotation
// project point into space of unrotated bounds
var p = text_anchorPoint(item),
ax = p.x1,
ay = p.y1,
b = text_bound(text_tempBounds, item, 1),
a = -item.angle * DegToRad,
cos = Math.cos(a),
sin = Math.sin(a),
px = cos * gx - sin * gy + (ax - cos * ax + sin * ay),
py = sin * gx + cos * gy + (ay - sin * ax - cos * ay);
return b.contains(px, py);
}
function text_intersectText(item, box) {
var p = text_bound(text_tempBounds, item, 2);
return intersect_intersectBoxLine(box, p[0], p[1], p[2], p[3])
|| intersect_intersectBoxLine(box, p[0], p[1], p[4], p[5])
|| intersect_intersectBoxLine(box, p[4], p[5], p[6], p[7])
|| intersect_intersectBoxLine(box, p[2], p[3], p[6], p[7]);
}
/* harmony default export */ var marks_text = ({
type: 'text',
tag: 'text',
nested: false,
attr: text_attr,
bound: text_bound,
draw: text_draw,
pick: pick_pick(text_hit),
isect: text_intersectText
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/trail.js
/* harmony default export */ var marks_trail = (markMultiItemPath('trail', shapes_trail, pickTrail));
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/marks/index.js
/* harmony default export */ var src_marks = ({
arc: marks_arc,
area: marks_area,
group: marks_group,
image: marks_image,
line: marks_line,
path: marks_path,
rect: marks_rect,
rule: marks_rule,
shape: marks_shape,
symbol: marks_symbol,
text: marks_text,
trail: marks_trail
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/bound/boundItem.js
/* harmony default export */ var bound_boundItem = (function(item, func, opt) {
var type = src_marks[item.mark.marktype],
bound = func || type.bound;
if (type.nested) item = item.mark;
return bound(item.bounds || (item.bounds = new Bounds()), item, opt);
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/bound/boundMark.js
var boundMark_DUMMY = {mark: null};
/* harmony default export */ var boundMark = (function(mark, bounds, opt) {
var type = src_marks[mark.marktype],
bound = type.bound,
items = mark.items,
hasItems = items && items.length,
i, n, item, b;
if (type.nested) {
if (hasItems) {
item = items[0];
} else {
// no items, fake it
boundMark_DUMMY.mark = mark;
item = boundMark_DUMMY;
}
b = bound_boundItem(item, bound, opt);
bounds = bounds && bounds.union(b) || b;
return bounds;
}
bounds = bounds
|| mark.bounds && mark.bounds.clear()
|| new Bounds();
if (hasItems) {
for (i=0, n=items.length; i<n; ++i) {
bounds.union(bound_boundItem(items[i], bound, opt));
}
}
return mark.bounds = bounds;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/serialize.js
var serialize_keys = [
'marktype', 'name', 'role', 'interactive', 'clip', 'items', 'zindex',
'x', 'y', 'width', 'height', 'align', 'baseline', // layout
'fill', 'fillOpacity', 'opacity', 'blend', // fill
'stroke', 'strokeOpacity', 'strokeWidth', 'strokeCap', // stroke
'strokeDash', 'strokeDashOffset', // stroke dash
'strokeForeground', 'strokeOffset', // group
'startAngle', 'endAngle', 'innerRadius', 'outerRadius', // arc
'cornerRadius', 'padAngle', // arc, rect
'cornerRadiusTopLeft', 'cornerRadiusTopRight', // rect, group
'cornerRadiusBottomLeft', 'cornerRadiusBottomRight',
'interpolate', 'tension', 'orient', 'defined', // area, line
'url', 'aspect', 'smooth', // image
'path', 'scaleX', 'scaleY', // path
'x2', 'y2', // rule
'size', 'shape', // symbol
'text', 'angle', 'theta', 'radius', 'dir', 'dx', 'dy', // text
'ellipsis', 'limit', 'lineBreak', 'lineHeight',
'font', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant' // font
];
function serialize_sceneToJSON(scene, indent) {
return JSON.stringify(scene, serialize_keys, indent);
}
function serialize_sceneFromJSON(json) {
var scene = (typeof json === 'string' ? JSON.parse(json) : json);
return serialize_initialize(scene);
}
function serialize_initialize(scene) {
var type = scene.marktype,
items = scene.items,
parent, i, n;
if (items) {
for (i=0, n=items.length; i<n; ++i) {
parent = type ? 'mark' : 'group';
items[i][parent] = scene;
if (items[i].zindex) items[i][parent].zdirty = true;
if ('group' === (type || parent)) serialize_initialize(items[i]);
}
}
if (type) boundMark(scene);
return scene;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/Scenegraph.js
function Scenegraph_Scenegraph(scene) {
if (arguments.length) {
this.root = serialize_sceneFromJSON(scene);
} else {
this.root = Scenegraph_createMark({
marktype: 'group',
name: 'root',
role: 'frame'
});
this.root.items = [new GroupItem_GroupItem(this.root)];
}
}
var Scenegraph_prototype = Scenegraph_Scenegraph.prototype;
Scenegraph_prototype.toJSON = function(indent) {
return serialize_sceneToJSON(this.root, indent || 0);
};
Scenegraph_prototype.mark = function(markdef, group, index) {
group = group || this.root.items[0];
var mark = Scenegraph_createMark(markdef, group);
group.items[index] = mark;
if (mark.zindex) mark.group.zdirty = true;
return mark;
};
function Scenegraph_createMark(def, group) {
return {
bounds: new Bounds(),
clip: !!def.clip,
group: group,
interactive: def.interactive === false ? false : true,
items: [],
marktype: def.marktype,
name: def.name || undefined,
role: def.role || undefined,
zindex: def.zindex || 0
};
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/dom.js
// create a new DOM element
function domCreate(doc, tag, ns) {
if (!doc && typeof document !== 'undefined' && document.createElement) {
doc = document;
}
return doc
? (ns ? doc.createElementNS(ns, tag) : doc.createElement(tag))
: null;
}
// find first child element with matching tag
function domFind(el, tag) {
tag = tag.toLowerCase();
var nodes = el.childNodes, i = 0, n = nodes.length;
for (; i<n; ++i) if (nodes[i].tagName.toLowerCase() === tag) {
return nodes[i];
}
}
// retrieve child element at given index
// create & insert if doesn't exist or if tags do not match
function domChild(el, index, tag, ns) {
var a = el.childNodes[index], b;
if (!a || a.tagName.toLowerCase() !== tag.toLowerCase()) {
b = a || null;
a = domCreate(el.ownerDocument, tag, ns);
el.insertBefore(a, b);
}
return a;
}
// remove all child elements at or above the given index
function domClear(el, index) {
var nodes = el.childNodes,
curr = nodes.length;
while (curr > index) el.removeChild(nodes[--curr]);
return el;
}
// generate css class name for mark
function cssClass(mark) {
return 'mark-' + mark.marktype
+ (mark.role ? ' role-' + mark.role : '')
+ (mark.name ? ' ' + mark.name : '');
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/point.js
/* harmony default export */ var util_point = (function(event, el) {
var rect = el.getBoundingClientRect();
return [
event.clientX - rect.left - (el.clientLeft || 0),
event.clientY - rect.top - (el.clientTop || 0)
];
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/resolveItem.js
/* harmony default export */ var resolveItem = (function(item, event, el, origin) {
var mark = item && item.mark,
mdef, p;
if (mark && (mdef = src_marks[mark.marktype]).tip) {
p = util_point(event, el);
p[0] -= origin[0];
p[1] -= origin[1];
while (item = item.mark.group) {
p[0] -= item.x || 0;
p[1] -= item.y || 0;
}
item = mdef.tip(mark.items, p);
}
return item;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/Handler.js
/**
* Create a new Handler instance.
* @param {object} [customLoader] - Optional loader instance for
* href URL sanitization. If not specified, a standard loader
* instance will be generated.
* @param {function} [customTooltip] - Optional tooltip handler
* function for custom tooltip display.
* @constructor
*/
function Handler_Handler(customLoader, customTooltip) {
this._active = null;
this._handlers = {};
this._loader = customLoader || index_browser_loader();
this._tooltip = customTooltip || Handler_defaultTooltip;
}
// The default tooltip display handler.
// Sets the HTML title attribute on the visualization container.
function Handler_defaultTooltip(handler, event, item, value) {
handler.element().setAttribute('title', value || '');
}
var Handler_prototype = Handler_Handler.prototype;
/**
* Initialize a new Handler instance.
* @param {DOMElement} el - The containing DOM element for the display.
* @param {Array<number>} origin - The origin of the display, in pixels.
* The coordinate system will be translated to this point.
* @param {object} [obj] - Optional context object that should serve as
* the "this" context for event callbacks.
* @return {Handler} - This handler instance.
*/
Handler_prototype.initialize = function(el, origin, obj) {
this._el = el;
this._obj = obj || null;
return this.origin(origin);
};
/**
* Returns the parent container element for a visualization.
* @return {DOMElement} - The containing DOM element.
*/
Handler_prototype.element = function() {
return this._el;
};
/**
* Returns the scene element (e.g., canvas or SVG) of the visualization
* Subclasses must override if the first child is not the scene element.
* @return {DOMElement} - The scene (e.g., canvas or SVG) element.
*/
Handler_prototype.canvas = function() {
return this._el && this._el.firstChild;
};
/**
* Get / set the origin coordinates of the visualization.
*/
Handler_prototype.origin = function(origin) {
if (arguments.length) {
this._origin = origin || [0, 0];
return this;
} else {
return this._origin.slice();
}
};
/**
* Get / set the scenegraph root.
*/
Handler_prototype.scene = function(scene) {
if (!arguments.length) return this._scene;
this._scene = scene;
return this;
};
/**
* Add an event handler. Subclasses should override this method.
*/
Handler_prototype.on = function(/*type, handler*/) {};
/**
* Remove an event handler. Subclasses should override this method.
*/
Handler_prototype.off = function(/*type, handler*/) {};
/**
* Utility method for finding the array index of an event handler.
* @param {Array} h - An array of registered event handlers.
* @param {string} type - The event type.
* @param {function} handler - The event handler instance to find.
* @return {number} - The handler's array index or -1 if not registered.
*/
Handler_prototype._handlerIndex = function(h, type, handler) {
for (var i = h ? h.length : 0; --i>=0;) {
if (h[i].type === type && (!handler || h[i].handler === handler)) {
return i;
}
}
return -1;
};
/**
* Returns an array with registered event handlers.
* @param {string} [type] - The event type to query. Any annotations
* are ignored; for example, for the argument "click.foo", ".foo" will
* be ignored and the method returns all "click" handlers. If type is
* null or unspecified, this method returns handlers for all types.
* @return {Array} - A new array containing all registered event handlers.
*/
Handler_prototype.handlers = function(type) {
var h = this._handlers, a = [], k;
if (type) {
a.push.apply(a, h[this.eventName(type)]);
} else {
for (k in h) { a.push.apply(a, h[k]); }
}
return a;
};
/**
* Parses an event name string to return the specific event type.
* For example, given "click.foo" returns "click"
* @param {string} name - The input event type string.
* @return {string} - A string with the event type only.
*/
Handler_prototype.eventName = function(name) {
var i = name.indexOf('.');
return i < 0 ? name : name.slice(0,i);
};
/**
* Handle hyperlink navigation in response to an item.href value.
* @param {Event} event - The event triggering hyperlink navigation.
* @param {Item} item - The scenegraph item.
* @param {string} href - The URL to navigate to.
*/
Handler_prototype.handleHref = function(event, item, href) {
this._loader
.sanitize(href, {context:'href'})
.then(function(opt) {
var e = new MouseEvent(event.type, event),
a = domCreate(null, 'a');
for (var name in opt) a.setAttribute(name, opt[name]);
a.dispatchEvent(e);
})
.catch(function() { /* do nothing */ });
};
/**
* Handle tooltip display in response to an item.tooltip value.
* @param {Event} event - The event triggering tooltip display.
* @param {Item} item - The scenegraph item.
* @param {boolean} show - A boolean flag indicating whether
* to show or hide a tooltip for the given item.
*/
Handler_prototype.handleTooltip = function(event, item, show) {
if (item && item.tooltip != null) {
item = resolveItem(item, event, this.canvas(), this._origin);
var value = (show && item && item.tooltip) || null;
this._tooltip.call(this._obj, this, event, item, value);
}
};
/**
* Returns the size of a scenegraph item and its position relative
* to the viewport.
* @param {Item} item - The scenegraph item.
* @return {object} - A bounding box object (compatible with the
* DOMRect type) consisting of x, y, width, heigh, top, left,
* right, and bottom properties.
*/
Handler_prototype.getItemBoundingClientRect = function(item) {
if (!(el = this.canvas())) return;
var el, rect = el.getBoundingClientRect(),
origin = this._origin,
itemBounds = item.bounds,
x = itemBounds.x1 + origin[0] + rect.left,
y = itemBounds.y1 + origin[1] + rect.top,
w = itemBounds.width(),
h = itemBounds.height();
// translate coordinate for each parent group
while (item.mark && (item = item.mark.group)) {
x += item.x || 0;
y += item.y || 0;
}
// return DOMRect-compatible bounding box
return {
x: x,
y: y,
width: w,
height: h,
left: x,
top: y,
right: x + w,
bottom: y + h
};
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/Renderer.js
/**
* Create a new Renderer instance.
* @param {object} [loader] - Optional loader instance for
* image and href URL sanitization. If not specified, a
* standard loader instance will be generated.
* @constructor
*/
function Renderer_Renderer(loader) {
this._el = null;
this._bgcolor = null;
this._loader = new ResourceLoader_ResourceLoader(loader);
}
var Renderer_prototype = Renderer_Renderer.prototype;
/**
* Initialize a new Renderer instance.
* @param {DOMElement} el - The containing DOM element for the display.
* @param {number} width - The coordinate width of the display, in pixels.
* @param {number} height - The coordinate height of the display, in pixels.
* @param {Array<number>} origin - The origin of the display, in pixels.
* The coordinate system will be translated to this point.
* @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
* the width and height to determine the final pixel size.
* @return {Renderer} - This renderer instance.
*/
Renderer_prototype.initialize = function(el, width, height, origin, scaleFactor) {
this._el = el;
return this.resize(width, height, origin, scaleFactor);
};
/**
* Returns the parent container element for a visualization.
* @return {DOMElement} - The containing DOM element.
*/
Renderer_prototype.element = function() {
return this._el;
};
/**
* Returns the scene element (e.g., canvas or SVG) of the visualization
* Subclasses must override if the first child is not the scene element.
* @return {DOMElement} - The scene (e.g., canvas or SVG) element.
*/
Renderer_prototype.canvas = function() {
return this._el && this._el.firstChild;
};
/**
* Get / set the background color.
*/
Renderer_prototype.background = function(bgcolor) {
if (arguments.length === 0) return this._bgcolor;
this._bgcolor = bgcolor;
return this;
};
/**
* Resize the display.
* @param {number} width - The new coordinate width of the display, in pixels.
* @param {number} height - The new coordinate height of the display, in pixels.
* @param {Array<number>} origin - The new origin of the display, in pixels.
* The coordinate system will be translated to this point.
* @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
* the width and height to determine the final pixel size.
* @return {Renderer} - This renderer instance;
*/
Renderer_prototype.resize = function(width, height, origin, scaleFactor) {
this._width = width;
this._height = height;
this._origin = origin || [0, 0];
this._scale = scaleFactor || 1;
return this;
};
/**
* Report a dirty item whose bounds should be redrawn.
* This base class method does nothing. Subclasses that perform
* incremental should implement this method.
* @param {Item} item - The dirty item whose bounds should be redrawn.
*/
Renderer_prototype.dirty = function(/*item*/) {
};
/**
* Render an input scenegraph, potentially with a set of dirty items.
* This method will perform an immediate rendering with available resources.
* The renderer may also need to perform image loading to perform a complete
* render. This process can lead to asynchronous re-rendering of the scene
* after this method returns. To receive notification when rendering is
* complete, use the renderAsync method instead.
* @param {object} scene - The root mark of a scenegraph to render.
* @return {Renderer} - This renderer instance.
*/
Renderer_prototype.render = function(scene) {
var r = this;
// bind arguments into a render call, and cache it
// this function may be subsequently called for async redraw
r._call = function() { r._render(scene); };
// invoke the renderer
r._call();
// clear the cached call for garbage collection
// async redraws will stash their own copy
r._call = null;
return r;
};
/**
* Internal rendering method. Renderer subclasses should override this
* method to actually perform rendering.
* @param {object} scene - The root mark of a scenegraph to render.
*/
Renderer_prototype._render = function(/*scene*/) {
// subclasses to override
};
/**
* Asynchronous rendering method. Similar to render, but returns a Promise
* that resolves when all rendering is completed. Sometimes a renderer must
* perform image loading to get a complete rendering. The returned
* Promise will not resolve until this process completes.
* @param {object} scene - The root mark of a scenegraph to render.
* @return {Promise} - A Promise that resolves when rendering is complete.
*/
Renderer_prototype.renderAsync = function(scene) {
var r = this.render(scene);
return this._ready
? this._ready.then(function() { return r; })
: Promise.resolve(r);
};
/**
* Internal method for asynchronous resource loading.
* Proxies method calls to the ImageLoader, and tracks loading
* progress to invoke a re-render once complete.
* @param {string} method - The method name to invoke on the ImageLoader.
* @param {string} uri - The URI for the requested resource.
* @return {Promise} - A Promise that resolves to the requested resource.
*/
Renderer_prototype._load = function(method, uri) {
var r = this,
p = r._loader[method](uri);
if (!r._ready) {
// re-render the scene when loading completes
var call = r._call;
r._ready = r._loader.ready()
.then(function(redraw) {
if (redraw) call();
r._ready = null;
});
}
return p;
};
/**
* Sanitize a URL to include as a hyperlink in the rendered scene.
* This method proxies a call to ImageLoader.sanitizeURL, but also tracks
* image loading progress and invokes a re-render once complete.
* @param {string} uri - The URI string to sanitize.
* @return {Promise} - A Promise that resolves to the sanitized URL.
*/
Renderer_prototype.sanitizeURL = function(uri) {
return this._load('sanitizeURL', uri);
};
/**
* Requests an image to include in the rendered scene.
* This method proxies a call to ImageLoader.loadImage, but also tracks
* image loading progress and invokes a re-render once complete.
* @param {string} uri - The URI string of the image.
* @return {Promise} - A Promise that resolves to the loaded Image.
*/
Renderer_prototype.loadImage = function(uri) {
return this._load('loadImage', uri);
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/events.js
var Events = [
'keydown',
'keypress',
'keyup',
'dragenter',
'dragleave',
'dragover',
'mousedown',
'mouseup',
'mousemove',
'mouseout',
'mouseover',
'click',
'dblclick',
'wheel',
'mousewheel',
'touchstart',
'touchmove',
'touchend'
];
var TooltipShowEvent = 'mousemove';
var TooltipHideEvent = 'mouseout';
var HrefEvent = 'click';
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/CanvasHandler.js
function CanvasHandler_CanvasHandler(loader, tooltip) {
Handler_Handler.call(this, loader, tooltip);
this._down = null;
this._touch = null;
this._first = true;
}
var CanvasHandler_prototype = Object(vega_util["y" /* inherits */])(CanvasHandler_CanvasHandler, Handler_Handler);
CanvasHandler_prototype.initialize = function(el, origin, obj) {
// add event listeners
var canvas = this._canvas = el && domFind(el, 'canvas');
if (canvas) {
var that = this;
this.events.forEach(function(type) {
canvas.addEventListener(type, function(evt) {
if (CanvasHandler_prototype[type]) {
CanvasHandler_prototype[type].call(that, evt);
} else {
that.fire(type, evt);
}
});
});
}
return Handler_Handler.prototype.initialize.call(this, el, origin, obj);
};
// return the backing canvas instance
CanvasHandler_prototype.canvas = function() {
return this._canvas;
};
// retrieve the current canvas context
CanvasHandler_prototype.context = function() {
return this._canvas.getContext('2d');
};
// supported events
CanvasHandler_prototype.events = Events;
// to keep old versions of firefox happy
CanvasHandler_prototype.DOMMouseScroll = function(evt) {
this.fire('mousewheel', evt);
};
function CanvasHandler_move(moveEvent, overEvent, outEvent) {
return function(evt) {
var a = this._active,
p = this.pickEvent(evt);
if (p === a) {
// active item and picked item are the same
this.fire(moveEvent, evt); // fire move
} else {
// active item and picked item are different
if (!a || !a.exit) {
// fire out for prior active item
// suppress if active item was removed from scene
this.fire(outEvent, evt);
}
this._active = p; // set new active item
this.fire(overEvent, evt); // fire over for new active item
this.fire(moveEvent, evt); // fire move for new active item
}
};
}
function CanvasHandler_inactive(type) {
return function(evt) {
this.fire(type, evt);
this._active = null;
};
}
CanvasHandler_prototype.mousemove = CanvasHandler_move('mousemove', 'mouseover', 'mouseout');
CanvasHandler_prototype.dragover = CanvasHandler_move('dragover', 'dragenter', 'dragleave');
CanvasHandler_prototype.mouseout = CanvasHandler_inactive('mouseout');
CanvasHandler_prototype.dragleave = CanvasHandler_inactive('dragleave');
CanvasHandler_prototype.mousedown = function(evt) {
this._down = this._active;
this.fire('mousedown', evt);
};
CanvasHandler_prototype.click = function(evt) {
if (this._down === this._active) {
this.fire('click', evt);
this._down = null;
}
};
CanvasHandler_prototype.touchstart = function(evt) {
this._touch = this.pickEvent(evt.changedTouches[0]);
if (this._first) {
this._active = this._touch;
this._first = false;
}
this.fire('touchstart', evt, true);
};
CanvasHandler_prototype.touchmove = function(evt) {
this.fire('touchmove', evt, true);
};
CanvasHandler_prototype.touchend = function(evt) {
this.fire('touchend', evt, true);
this._touch = null;
};
// fire an event
CanvasHandler_prototype.fire = function(type, evt, touch) {
var a = touch ? this._touch : this._active,
h = this._handlers[type], i, len;
// set event type relative to scenegraph items
evt.vegaType = type;
// handle hyperlinks and tooltips first
if (type === HrefEvent && a && a.href) {
this.handleHref(evt, a, a.href);
} else if (type === TooltipShowEvent || type === TooltipHideEvent) {
this.handleTooltip(evt, a, type !== TooltipHideEvent);
}
// invoke all registered handlers
if (h) {
for (i=0, len=h.length; i<len; ++i) {
h[i].handler.call(this._obj, evt, a);
}
}
};
// add an event handler
CanvasHandler_prototype.on = function(type, handler) {
var name = this.eventName(type),
h = this._handlers,
i = this._handlerIndex(h[name], type, handler);
if (i < 0) {
(h[name] || (h[name] = [])).push({
type: type,
handler: handler
});
}
return this;
};
// remove an event handler
CanvasHandler_prototype.off = function(type, handler) {
var name = this.eventName(type),
h = this._handlers[name],
i = this._handlerIndex(h, type, handler);
if (i >= 0) {
h.splice(i, 1);
}
return this;
};
CanvasHandler_prototype.pickEvent = function(evt) {
var p = util_point(evt, this._canvas),
o = this._origin;
return this.pick(this._scene, p[0], p[1], p[0] - o[0], p[1] - o[1]);
};
// find the scenegraph item at the current mouse position
// x, y -- the absolute x, y mouse coordinates on the canvas element
// gx, gy -- the relative coordinates within the current group
CanvasHandler_prototype.pick = function(scene, x, y, gx, gy) {
var g = this.context(),
mark = src_marks[scene.marktype];
return mark.pick.call(this, g, scene, x, y, gx, gy);
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/canvas/resize.js
function devicePixelRatio() {
return typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
}
var pixelRatio = devicePixelRatio();
/* harmony default export */ var resize = (function(canvas, width, height, origin, scaleFactor, opt) {
const inDOM = typeof HTMLElement !== 'undefined'
&& canvas instanceof HTMLElement
&& canvas.parentNode != null,
context = canvas.getContext('2d'),
ratio = inDOM ? pixelRatio : scaleFactor;
canvas.width = width * ratio;
canvas.height = height * ratio;
for (const key in opt) {
context[key] = opt[key];
}
if (inDOM && ratio !== 1) {
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}
context.pixelRatio = ratio;
context.setTransform(
ratio, 0, 0, ratio,
ratio * origin[0],
ratio * origin[1]
);
return canvas;
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/CanvasRenderer.js
function CanvasRenderer_CanvasRenderer(loader) {
Renderer_Renderer.call(this, loader);
this._redraw = false;
this._dirty = new Bounds();
}
var CanvasRenderer_prototype = Object(vega_util["y" /* inherits */])(CanvasRenderer_CanvasRenderer, Renderer_Renderer),
CanvasRenderer_base = Renderer_Renderer.prototype,
CanvasRenderer_tempBounds = new Bounds();
CanvasRenderer_prototype.initialize = function(el, width, height, origin, scaleFactor, options) {
this._options = options;
this._canvas = domCanvas(1, 1, options && options.type); // instantiate a small canvas
if (el) {
domClear(el, 0).appendChild(this._canvas);
this._canvas.setAttribute('class', 'marks');
}
// this method will invoke resize to size the canvas appropriately
return CanvasRenderer_base.initialize.call(this, el, width, height, origin, scaleFactor);
};
CanvasRenderer_prototype.resize = function(width, height, origin, scaleFactor) {
CanvasRenderer_base.resize.call(this, width, height, origin, scaleFactor);
resize(this._canvas, this._width, this._height,
this._origin, this._scale, this._options && this._options.context);
this._redraw = true;
return this;
};
CanvasRenderer_prototype.canvas = function() {
return this._canvas;
};
CanvasRenderer_prototype.context = function() {
return this._canvas ? this._canvas.getContext('2d') : null;
};
CanvasRenderer_prototype.dirty = function(item) {
var b = CanvasRenderer_translate(item.bounds, item.mark.group);
this._dirty.union(b);
};
function CanvasRenderer_clipToBounds(g, b, origin) {
// expand bounds by 1 pixel, then round to pixel boundaries
b.expand(1).round();
// align to base pixel grid in case of non-integer scaling (#2425)
if (g.pixelRatio % 1) {
b.scale(g.pixelRatio).round().scale(1 / g.pixelRatio);
}
// to avoid artifacts translate if origin has fractional pixels
b.translate(-(origin[0] % 1), -(origin[1] % 1));
// set clip path
g.beginPath();
g.rect(b.x1, b.y1, b.width(), b.height());
g.clip();
return b;
}
function CanvasRenderer_viewBounds(origin, width, height) {
return CanvasRenderer_tempBounds
.set(0, 0, width, height)
.translate(-origin[0], -origin[1]);
}
function CanvasRenderer_translate(bounds, group) {
if (group == null) return bounds;
var b = CanvasRenderer_tempBounds.clear().union(bounds);
for (; group != null; group = group.mark.group) {
b.translate(group.x || 0, group.y || 0);
}
return b;
}
CanvasRenderer_prototype._render = function(scene) {
var g = this.context(),
o = this._origin,
w = this._width,
h = this._height,
b = this._dirty;
// setup
g.save();
if (this._redraw || b.empty()) {
this._redraw = false;
b = CanvasRenderer_viewBounds(o, w, h).expand(1);
} else {
b = CanvasRenderer_clipToBounds(g, b.intersect(CanvasRenderer_viewBounds(o, w, h)), o, w, h);
}
this.clear(-o[0], -o[1], w, h);
// render
this.draw(g, scene, b);
// takedown
g.restore();
this._dirty.clear();
return this;
};
CanvasRenderer_prototype.draw = function(ctx, scene, bounds) {
var mark = src_marks[scene.marktype];
if (scene.clip) canvas_clip(ctx, scene);
mark.draw.call(this, ctx, scene, bounds);
if (scene.clip) ctx.restore();
};
CanvasRenderer_prototype.clear = function(x, y, w, h) {
var g = this.context();
g.clearRect(x, y, w, h);
if (this._bgcolor != null) {
g.fillStyle = this._bgcolor;
g.fillRect(x, y, w, h);
}
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/SVGHandler.js
function SVGHandler_SVGHandler(loader, tooltip) {
Handler_Handler.call(this, loader, tooltip);
var h = this;
h._hrefHandler = SVGHandler_listener(h, function(evt, item) {
if (item && item.href) h.handleHref(evt, item, item.href);
});
h._tooltipHandler = SVGHandler_listener(h, function(evt, item) {
h.handleTooltip(evt, item, evt.type !== TooltipHideEvent);
});
}
var SVGHandler_prototype = Object(vega_util["y" /* inherits */])(SVGHandler_SVGHandler, Handler_Handler);
SVGHandler_prototype.initialize = function(el, origin, obj) {
var svg = this._svg;
if (svg) {
svg.removeEventListener(HrefEvent, this._hrefHandler);
svg.removeEventListener(TooltipShowEvent, this._tooltipHandler);
svg.removeEventListener(TooltipHideEvent, this._tooltipHandler);
}
this._svg = svg = el && domFind(el, 'svg');
if (svg) {
svg.addEventListener(HrefEvent, this._hrefHandler);
svg.addEventListener(TooltipShowEvent, this._tooltipHandler);
svg.addEventListener(TooltipHideEvent, this._tooltipHandler);
}
return Handler_Handler.prototype.initialize.call(this, el, origin, obj);
};
SVGHandler_prototype.canvas = function() {
return this._svg;
};
// wrap an event listener for the SVG DOM
function SVGHandler_listener(context, handler) {
return function(evt) {
var target = evt.target,
item = target.__data__;
evt.vegaType = evt.type;
item = Array.isArray(item) ? item[0] : item;
handler.call(context._obj, evt, item);
};
}
// add an event handler
SVGHandler_prototype.on = function(type, handler) {
var name = this.eventName(type),
h = this._handlers,
i = this._handlerIndex(h[name], type, handler);
if (i < 0) {
var x = {
type: type,
handler: handler,
listener: SVGHandler_listener(this, handler)
};
(h[name] || (h[name] = [])).push(x);
if (this._svg) {
this._svg.addEventListener(name, x.listener);
}
}
return this;
};
// remove an event handler
SVGHandler_prototype.off = function(type, handler) {
var name = this.eventName(type),
h = this._handlers[name],
i = this._handlerIndex(h, type, handler);
if (i >= 0) {
if (this._svg) {
this._svg.removeEventListener(name, h[i].listener);
}
h.splice(i, 1);
}
return this;
};
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/tags.js
// generate string for an opening xml tag
// tag: the name of the xml tag
// attr: hash of attribute name-value pairs to include
// raw: additional raw string to include in tag markup
function openTag(tag, attr, raw) {
var s = '<' + tag, key, val;
if (attr) {
for (key in attr) {
val = attr[key];
if (val != null) {
s += ' ' + key + '="' + val + '"';
}
}
}
if (raw) s += ' ' + raw;
return s + '>';
}
// generate string for closing xml tag
// tag: the name of the xml tag
function closeTag(tag) {
return '</' + tag + '>';
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/svg/metadata.js
/* harmony default export */ var svg_metadata = ({
'version': '1.1',
'xmlns': 'http://www.w3.org/2000/svg',
'xmlns:xlink': 'http://www.w3.org/1999/xlink'
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/svg/styles.js
var styles = {
'fill': 'fill',
'fillOpacity': 'fill-opacity',
'stroke': 'stroke',
'strokeOpacity': 'stroke-opacity',
'strokeWidth': 'stroke-width',
'strokeCap': 'stroke-linecap',
'strokeJoin': 'stroke-linejoin',
'strokeDash': 'stroke-dasharray',
'strokeDashOffset': 'stroke-dashoffset',
'strokeMiterLimit': 'stroke-miterlimit',
'opacity': 'opacity',
'blend': 'mix-blend-mode'
};
var styleProperties = Object.keys(styles);
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/SVGRenderer.js
var SVGRenderer_ns = svg_metadata.xmlns;
function SVGRenderer_SVGRenderer(loader) {
Renderer_Renderer.call(this, loader);
this._dirtyID = 0;
this._dirty = [];
this._svg = null;
this._root = null;
this._defs = null;
}
var SVGRenderer_prototype = Object(vega_util["y" /* inherits */])(SVGRenderer_SVGRenderer, Renderer_Renderer);
var SVGRenderer_base = Renderer_Renderer.prototype;
SVGRenderer_prototype.initialize = function(el, width, height, padding) {
if (el) {
this._svg = domChild(el, 0, 'svg', SVGRenderer_ns);
this._svg.setAttribute('class', 'marks');
domClear(el, 1);
// set the svg root group
this._root = domChild(this._svg, 0, 'g', SVGRenderer_ns);
domClear(this._svg, 1);
}
// create the svg definitions cache
this._defs = {
gradient: {},
clipping: {}
};
// set background color if defined
this.background(this._bgcolor);
return SVGRenderer_base.initialize.call(this, el, width, height, padding);
};
SVGRenderer_prototype.background = function(bgcolor) {
if (arguments.length && this._svg) {
this._svg.style.setProperty('background-color', bgcolor);
}
return SVGRenderer_base.background.apply(this, arguments);
};
SVGRenderer_prototype.resize = function(width, height, origin, scaleFactor) {
SVGRenderer_base.resize.call(this, width, height, origin, scaleFactor);
if (this._svg) {
this._svg.setAttribute('width', this._width * this._scale);
this._svg.setAttribute('height', this._height * this._scale);
this._svg.setAttribute('viewBox', '0 0 ' + this._width + ' ' + this._height);
this._root.setAttribute('transform', 'translate(' + this._origin + ')');
}
this._dirty = [];
return this;
};
SVGRenderer_prototype.canvas = function() {
return this._svg;
};
SVGRenderer_prototype.svg = function() {
if (!this._svg) return null;
var attr = {
class: 'marks',
width: this._width * this._scale,
height: this._height * this._scale,
viewBox: '0 0 ' + this._width + ' ' + this._height
};
for (var key in svg_metadata) {
attr[key] = svg_metadata[key];
}
var bg = !this._bgcolor ? ''
: (openTag('rect', {
width: this._width,
height: this._height,
style: 'fill: ' + this._bgcolor + ';'
}) + closeTag('rect'));
return openTag('svg', attr) + bg + this._svg.innerHTML + closeTag('svg');
};
// -- Render entry point --
SVGRenderer_prototype._render = function(scene) {
// perform spot updates and re-render markup
if (this._dirtyCheck()) {
if (this._dirtyAll) this._resetDefs();
this.draw(this._root, scene);
domClear(this._root, 1);
}
this.updateDefs();
this._dirty = [];
++this._dirtyID;
return this;
};
// -- Manage SVG definitions ('defs') block --
SVGRenderer_prototype.updateDefs = function() {
var svg = this._svg,
defs = this._defs,
el = defs.el,
index = 0, id;
for (id in defs.gradient) {
if (!el) defs.el = (el = domChild(svg, 0, 'defs', SVGRenderer_ns));
index = SVGRenderer_updateGradient(el, defs.gradient[id], index);
}
for (id in defs.clipping) {
if (!el) defs.el = (el = domChild(svg, 0, 'defs', SVGRenderer_ns));
index = SVGRenderer_updateClipping(el, defs.clipping[id], index);
}
// clean-up
if (el) {
if (index === 0) {
svg.removeChild(el);
defs.el = null;
} else {
domClear(el, index);
}
}
};
function SVGRenderer_updateGradient(el, grad, index) {
var i, n, stop;
if (grad.gradient === 'radial') {
// SVG radial gradients automatically transform to normalized bbox
// coordinates, in a way that is cumbersome to replicate in canvas.
// We wrap the radial gradient in a pattern element, allowing us to
// maintain a circular gradient that matches what canvas provides.
var pt = domChild(el, index++, 'pattern', SVGRenderer_ns);
pt.setAttribute('id', patternPrefix + grad.id);
pt.setAttribute('viewBox', '0,0,1,1');
pt.setAttribute('width', '100%');
pt.setAttribute('height', '100%');
pt.setAttribute('preserveAspectRatio', 'xMidYMid slice');
pt = domChild(pt, 0, 'rect', SVGRenderer_ns);
pt.setAttribute('width', '1');
pt.setAttribute('height', '1');
pt.setAttribute('fill', 'url(' + SVGRenderer_href() + '#' + grad.id + ')');
el = domChild(el, index++, 'radialGradient', SVGRenderer_ns);
el.setAttribute('id', grad.id);
el.setAttribute('fx', grad.x1);
el.setAttribute('fy', grad.y1);
el.setAttribute('fr', grad.r1);
el.setAttribute('cx', grad.x2);
el.setAttribute('cy', grad.y2);
el.setAttribute( 'r', grad.r2);
} else {
el = domChild(el, index++, 'linearGradient', SVGRenderer_ns);
el.setAttribute('id', grad.id);
el.setAttribute('x1', grad.x1);
el.setAttribute('x2', grad.x2);
el.setAttribute('y1', grad.y1);
el.setAttribute('y2', grad.y2);
}
for (i=0, n=grad.stops.length; i<n; ++i) {
stop = domChild(el, i, 'stop', SVGRenderer_ns);
stop.setAttribute('offset', grad.stops[i].offset);
stop.setAttribute('stop-color', grad.stops[i].color);
}
domClear(el, i);
return index;
}
function SVGRenderer_updateClipping(el, clip, index) {
var mask;
el = domChild(el, index, 'clipPath', SVGRenderer_ns);
el.setAttribute('id', clip.id);
if (clip.path) {
mask = domChild(el, 0, 'path', SVGRenderer_ns);
mask.setAttribute('d', clip.path);
} else {
mask = domChild(el, 0, 'rect', SVGRenderer_ns);
mask.setAttribute('x', 0);
mask.setAttribute('y', 0);
mask.setAttribute('width', clip.width);
mask.setAttribute('height', clip.height);
}
domClear(el, 1);
return index + 1;
}
SVGRenderer_prototype._resetDefs = function() {
var def = this._defs;
def.gradient = {};
def.clipping = {};
};
// -- Manage rendering of items marked as dirty --
SVGRenderer_prototype.dirty = function(item) {
if (item.dirty !== this._dirtyID) {
item.dirty = this._dirtyID;
this._dirty.push(item);
}
};
SVGRenderer_prototype.isDirty = function(item) {
return this._dirtyAll
|| !item._svg
|| item.dirty === this._dirtyID;
};
SVGRenderer_prototype._dirtyCheck = function() {
this._dirtyAll = true;
var items = this._dirty;
if (!items.length || !this._dirtyID) return true;
var id = ++this._dirtyID,
item, mark, type, mdef, i, n, o;
for (i=0, n=items.length; i<n; ++i) {
item = items[i];
mark = item.mark;
if (mark.marktype !== type) {
// memoize mark instance lookup
type = mark.marktype;
mdef = src_marks[type];
}
if (mark.zdirty && mark.dirty !== id) {
this._dirtyAll = false;
SVGRenderer_dirtyParents(item, id);
mark.items.forEach(function(i) { i.dirty = id; });
}
if (mark.zdirty) continue; // handle in standard drawing pass
if (item.exit) { // EXIT
if (mdef.nested && mark.items.length) {
// if nested mark with remaining points, update instead
o = mark.items[0];
if (o._svg) this._update(mdef, o._svg, o);
} else if (item._svg) {
// otherwise remove from DOM
o = item._svg.parentNode;
if (o) o.removeChild(item._svg);
}
item._svg = null;
continue;
}
item = (mdef.nested ? mark.items[0] : item);
if (item._update === id) continue; // already visited
if (!item._svg || !item._svg.ownerSVGElement) {
// ENTER
this._dirtyAll = false;
SVGRenderer_dirtyParents(item, id);
} else {
// IN-PLACE UPDATE
this._update(mdef, item._svg, item);
}
item._update = id;
}
return !this._dirtyAll;
};
function SVGRenderer_dirtyParents(item, id) {
for (; item && item.dirty !== id; item=item.mark.group) {
item.dirty = id;
if (item.mark && item.mark.dirty !== id) {
item.mark.dirty = id;
} else return;
}
}
// -- Construct & maintain scenegraph to SVG mapping ---
// Draw a mark container.
SVGRenderer_prototype.draw = function(el, scene, prev) {
if (!this.isDirty(scene)) return scene._svg;
var renderer = this,
svg = this._svg,
mdef = src_marks[scene.marktype],
events = scene.interactive === false ? 'none' : null,
isGroup = mdef.tag === 'g',
sibling = null,
i = 0,
parent;
parent = SVGRenderer_bind(scene, el, prev, 'g', svg);
parent.setAttribute('class', cssClass(scene));
if (!isGroup) {
parent.style.setProperty('pointer-events', events);
}
if (scene.clip) {
parent.setAttribute('clip-path', svg_clip(renderer, scene, scene.group));
} else {
parent.removeAttribute('clip-path');
}
function process(item) {
var dirty = renderer.isDirty(item),
node = SVGRenderer_bind(item, parent, sibling, mdef.tag, svg);
if (dirty) {
renderer._update(mdef, node, item);
if (isGroup) SVGRenderer_recurse(renderer, node, item);
}
sibling = node;
++i;
}
if (mdef.nested) {
if (scene.items.length) process(scene.items[0]);
} else {
visit_visit(scene, process);
}
domClear(parent, i);
return parent;
};
// Recursively process group contents.
function SVGRenderer_recurse(renderer, el, group) {
el = el.lastChild.previousSibling;
var prev, idx = 0;
visit_visit(group, function(item) {
prev = renderer.draw(el, item, prev);
++idx;
});
// remove any extraneous DOM elements
domClear(el, 1 + idx);
}
// Bind a scenegraph item to an SVG DOM element.
// Create new SVG elements as needed.
function SVGRenderer_bind(item, el, sibling, tag, svg) {
var node = item._svg, doc;
// create a new dom node if needed
if (!node) {
doc = el.ownerDocument;
node = domCreate(doc, tag, SVGRenderer_ns);
item._svg = node;
if (item.mark) {
node.__data__ = item;
node.__values__ = {fill: 'default'};
// if group, create background, content, and foreground elements
if (tag === 'g') {
var bg = domCreate(doc, 'path', SVGRenderer_ns);
node.appendChild(bg);
bg.__data__ = item;
var cg = domCreate(doc, 'g', SVGRenderer_ns);
node.appendChild(cg);
cg.__data__ = item;
var fg = domCreate(doc, 'path', SVGRenderer_ns);
node.appendChild(fg);
fg.__data__ = item;
fg.__values__ = {fill: 'default'};
}
}
}
// (re-)insert if (a) not contained in SVG or (b) sibling order has changed
if (node.ownerSVGElement !== svg || SVGRenderer_siblingCheck(node, sibling)) {
el.insertBefore(node, sibling ? sibling.nextSibling : el.firstChild);
}
return node;
}
function SVGRenderer_siblingCheck(node, sibling) {
return node.parentNode
&& node.parentNode.childNodes.length > 1
&& node.previousSibling != sibling; // treat null/undefined the same
}
// -- Set attributes & styles on SVG elements ---
var SVGRenderer_element = null, // temp var for current SVG element
SVGRenderer_values = null; // temp var for current values hash
// Extra configuration for certain mark types
var SVGRenderer_mark_extras = {
group: function(mdef, el, item) {
var fg, bg;
SVGRenderer_element = fg = el.childNodes[2];
SVGRenderer_values = fg.__values__;
mdef.foreground(SVGRenderer_emit, item, this);
SVGRenderer_values = el.__values__; // use parent's values hash
SVGRenderer_element = el.childNodes[1];
mdef.content(SVGRenderer_emit, item, this);
SVGRenderer_element = bg = el.childNodes[0];
mdef.background(SVGRenderer_emit, item, this);
var value = item.mark.interactive === false ? 'none' : null;
if (value !== SVGRenderer_values.events) {
fg.style.setProperty('pointer-events', value);
bg.style.setProperty('pointer-events', value);
SVGRenderer_values.events = value;
}
if (item.strokeForeground && item.stroke) {
const fill = item.fill;
fg.style.removeProperty('display');
// set style of background
this.style(bg, item);
bg.style.removeProperty('stroke');
// set style of foreground
if (fill) item.fill = null;
SVGRenderer_values = fg.__values__;
this.style(fg, item);
if (fill) item.fill = fill;
// leave element null to prevent downstream styling
SVGRenderer_element = null;
} else {
// ensure foreground is ignored
fg.style.setProperty('display', 'none');
fg.style.setProperty('fill', 'none');
}
},
image: function(mdef, el, item) {
if (item.smooth === false) {
SVGRenderer_setStyle(el, 'image-rendering', 'optimizeSpeed');
SVGRenderer_setStyle(el, 'image-rendering', 'pixelated');
} else {
SVGRenderer_setStyle(el, 'image-rendering', null);
}
},
text: function(mdef, el, item) {
var tl = text_textLines(item),
key, value, doc, lh;
if (Object(vega_util["A" /* isArray */])(tl)) {
// multi-line text
value = tl.map(_ => text_textValue(item, _));
key = value.join('\n'); // content cache key
if (key !== SVGRenderer_values.text) {
domClear(el, 0);
doc = el.ownerDocument;
lh = text_lineHeight(item);
value.forEach((t, i) => {
const ts = domCreate(doc, 'tspan', SVGRenderer_ns);
ts.__data__ = item; // data binding
ts.textContent = t;
if (i) {
ts.setAttribute('x', 0);
ts.setAttribute('dy', lh);
}
el.appendChild(ts);
});
SVGRenderer_values.text = key;
}
} else {
// single-line text
value = text_textValue(item, tl);
if (value !== SVGRenderer_values.text) {
el.textContent = value;
SVGRenderer_values.text = value;
}
}
SVGRenderer_setStyle(el, 'font-family', text_fontFamily(item));
SVGRenderer_setStyle(el, 'font-size', text_fontSize(item) + 'px');
SVGRenderer_setStyle(el, 'font-style', item.fontStyle);
SVGRenderer_setStyle(el, 'font-variant', item.fontVariant);
SVGRenderer_setStyle(el, 'font-weight', item.fontWeight);
}
};
function SVGRenderer_setStyle(el, name, value) {
if (value !== SVGRenderer_values[name]) {
if (value == null) {
el.style.removeProperty(name);
} else {
el.style.setProperty(name, value + '');
}
SVGRenderer_values[name] = value;
}
}
SVGRenderer_prototype._update = function(mdef, el, item) {
// set dom element and values cache
// provides access to emit method
SVGRenderer_element = el;
SVGRenderer_values = el.__values__;
// apply svg attributes
mdef.attr(SVGRenderer_emit, item, this);
// some marks need special treatment
var extra = SVGRenderer_mark_extras[mdef.type];
if (extra) extra.call(this, mdef, el, item);
// apply svg css styles
// note: element may be modified by 'extra' method
if (SVGRenderer_element) this.style(SVGRenderer_element, item);
};
function SVGRenderer_emit(name, value, ns) {
// early exit if value is unchanged
if (value === SVGRenderer_values[name]) return;
if (value != null) {
// if value is provided, update DOM attribute
if (ns) {
SVGRenderer_element.setAttributeNS(ns, name, value);
} else {
SVGRenderer_element.setAttribute(name, value);
}
} else {
// else remove DOM attribute
if (ns) {
SVGRenderer_element.removeAttributeNS(ns, name);
} else {
SVGRenderer_element.removeAttribute(name);
}
}
// note current value for future comparison
SVGRenderer_values[name] = value;
}
SVGRenderer_prototype.style = function(el, o) {
if (o == null) return;
var i, n, prop, name, value;
for (i=0, n=styleProperties.length; i<n; ++i) {
prop = styleProperties[i];
value = o[prop];
if (prop === 'font') {
value = text_fontFamily(o);
}
if (value === SVGRenderer_values[prop]) continue;
name = styles[prop];
if (value == null) {
if (name === 'fill') {
el.style.setProperty(name, 'none');
} else {
el.style.removeProperty(name);
}
} else {
if (isGradient(value)) {
value = gradientRef(value, this._defs.gradient, SVGRenderer_href());
}
el.style.setProperty(name, value + '');
}
SVGRenderer_values[prop] = value;
}
};
function SVGRenderer_href() {
var loc;
return typeof window === 'undefined' ? ''
: (loc = window.location).hash ? loc.href.slice(0, -loc.hash.length)
: loc.href;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/SVGStringRenderer.js
function SVGStringRenderer_SVGStringRenderer(loader) {
Renderer_Renderer.call(this, loader);
this._text = {
head: '',
bg: '',
root: '',
foot: '',
defs: '',
body: ''
};
this._defs = {
gradient: {},
clipping: {}
};
}
var SVGStringRenderer_prototype = Object(vega_util["y" /* inherits */])(SVGStringRenderer_SVGStringRenderer, Renderer_Renderer);
var SVGStringRenderer_base = Renderer_Renderer.prototype;
SVGStringRenderer_prototype.resize = function(width, height, origin, scaleFactor) {
SVGStringRenderer_base.resize.call(this, width, height, origin, scaleFactor);
var o = this._origin,
t = this._text;
var attr = {
class: 'marks',
width: this._width * this._scale,
height: this._height * this._scale,
viewBox: '0 0 ' + this._width + ' ' + this._height
};
for (var key in svg_metadata) {
attr[key] = svg_metadata[key];
}
t.head = openTag('svg', attr);
var bg = this._bgcolor;
if (bg === 'transparent' || bg === 'none') bg = null;
if (bg) {
t.bg = openTag('rect', {
width: this._width,
height: this._height,
style: 'fill: ' + bg + ';'
}) + closeTag('rect');
} else {
t.bg = '';
}
t.root = openTag('g', {
transform: 'translate(' + o + ')'
});
t.foot = closeTag('g') + closeTag('svg');
return this;
};
SVGStringRenderer_prototype.background = function() {
var rv = SVGStringRenderer_base.background.apply(this, arguments);
if (arguments.length && this._text.head) {
this.resize(this._width, this._height, this._origin, this._scale);
}
return rv;
};
SVGStringRenderer_prototype.svg = function() {
var t = this._text;
return t.head + t.bg + t.defs + t.root + t.body + t.foot;
};
SVGStringRenderer_prototype._render = function(scene) {
this._text.body = this.mark(scene);
this._text.defs = this.buildDefs();
return this;
};
SVGStringRenderer_prototype.buildDefs = function() {
var all = this._defs,
defs = '',
i, id, def, tag, stops;
for (id in all.gradient) {
def = all.gradient[id];
stops = def.stops;
if (def.gradient === 'radial') {
// SVG radial gradients automatically transform to normalized bbox
// coordinates, in a way that is cumbersome to replicate in canvas.
// We wrap the radial gradient in a pattern element, allowing us to
// maintain a circular gradient that matches what canvas provides.
defs += openTag(tag = 'pattern', {
id: patternPrefix + id,
viewBox: '0,0,1,1',
width: '100%',
height: '100%',
preserveAspectRatio: 'xMidYMid slice'
});
defs += openTag('rect', {
width: '1',
height: '1',
fill: 'url(#' + id + ')'
}) + closeTag('rect');
defs += closeTag(tag);
defs += openTag(tag = 'radialGradient', {
id: id,
fx: def.x1,
fy: def.y1,
fr: def.r1,
cx: def.x2,
cy: def.y2,
r: def.r2
});
} else {
defs += openTag(tag = 'linearGradient', {
id: id,
x1: def.x1,
x2: def.x2,
y1: def.y1,
y2: def.y2
});
}
for (i=0; i<stops.length; ++i) {
defs += openTag('stop', {
offset: stops[i].offset,
'stop-color': stops[i].color
}) + closeTag('stop');
}
defs += closeTag(tag);
}
for (id in all.clipping) {
def = all.clipping[id];
defs += openTag('clipPath', {id: id});
if (def.path) {
defs += openTag('path', {
d: def.path
}) + closeTag('path');
} else {
defs += openTag('rect', {
x: 0,
y: 0,
width: def.width,
height: def.height
}) + closeTag('rect');
}
defs += closeTag('clipPath');
}
return (defs.length > 0) ? openTag('defs') + defs + closeTag('defs') : '';
};
var SVGStringRenderer_object;
function SVGStringRenderer_emit(name, value, ns, prefixed) {
SVGStringRenderer_object[prefixed || name] = value;
}
SVGStringRenderer_prototype.attributes = function(attr, item) {
SVGStringRenderer_object = {};
attr(SVGStringRenderer_emit, item, this);
return SVGStringRenderer_object;
};
SVGStringRenderer_prototype.href = function(item) {
var that = this,
href = item.href,
attr;
if (href) {
if (attr = that._hrefs && that._hrefs[href]) {
return attr;
} else {
that.sanitizeURL(href).then(function(attr) {
// rewrite to use xlink namespace
// note that this will be deprecated in SVG 2.0
attr['xlink:href'] = attr.href;
attr.href = null;
(that._hrefs || (that._hrefs = {}))[href] = attr;
});
}
}
return null;
};
SVGStringRenderer_prototype.mark = function(scene) {
var renderer = this,
mdef = src_marks[scene.marktype],
tag = mdef.tag,
defs = this._defs,
str = '',
style;
if (tag !== 'g' && scene.interactive === false) {
style = 'style="pointer-events: none;"';
}
// render opening group tag
str += openTag('g', {
'class': cssClass(scene),
'clip-path': scene.clip ? svg_clip(renderer, scene, scene.group) : null
}, style);
// render contained elements
function process(item) {
var href = renderer.href(item);
if (href) str += openTag('a', href);
style = (tag !== 'g') ? SVGStringRenderer_applyStyles(item, scene, tag, defs) : null;
str += openTag(tag, renderer.attributes(mdef.attr, item), style);
if (tag === 'text') {
const tl = text_textLines(item);
if (Object(vega_util["A" /* isArray */])(tl)) {
// multi-line text
const attrs = {x: 0, dy: text_lineHeight(item)};
for (let i=0; i<tl.length; ++i) {
str += openTag('tspan', i ? attrs: null)
+ SVGStringRenderer_escape_text(text_textValue(item, tl[i]))
+ closeTag('tspan');
}
} else {
// single-line text
str += SVGStringRenderer_escape_text(text_textValue(item, tl));
}
} else if (tag === 'g') {
const fore = item.strokeForeground,
fill = item.fill,
stroke = item.stroke;
if (fore && stroke) {
item.stroke = null;
}
str += openTag('path', renderer.attributes(mdef.background, item),
SVGStringRenderer_applyStyles(item, scene, 'bgrect', defs)) + closeTag('path');
str += openTag('g', renderer.attributes(mdef.content, item))
+ renderer.markGroup(item)
+ closeTag('g');
if (fore && stroke) {
if (fill) item.fill = null;
item.stroke = stroke;
str += openTag('path', renderer.attributes(mdef.foreground, item),
SVGStringRenderer_applyStyles(item, scene, 'bgrect', defs)) + closeTag('path');
if (fill) item.fill = fill;
} else {
str += openTag('path', renderer.attributes(mdef.foreground, item),
SVGStringRenderer_applyStyles({}, scene, 'bgfore', defs)) + closeTag('path');
}
}
str += closeTag(tag);
if (href) str += closeTag('a');
}
if (mdef.nested) {
if (scene.items && scene.items.length) process(scene.items[0]);
} else {
visit_visit(scene, process);
}
// render closing group tag
return str + closeTag('g');
};
SVGStringRenderer_prototype.markGroup = function(scene) {
var renderer = this,
str = '';
visit_visit(scene, function(item) {
str += renderer.mark(item);
});
return str;
};
function SVGStringRenderer_applyStyles(o, mark, tag, defs) {
if (o == null) return '';
var i, n, prop, name, value, s = '';
if (tag === 'bgrect' && mark.interactive === false) {
s += 'pointer-events: none; ';
}
if (tag === 'bgfore') {
if (mark.interactive === false) {
s += 'pointer-events: none; ';
}
s += 'display: none; ';
}
if (tag === 'image') {
if (o.smooth === false) {
s += 'image-rendering: optimizeSpeed; image-rendering: pixelated; ';
}
}
if (tag === 'text') {
s += 'font-family: ' + text_fontFamily(o) + '; ';
s += 'font-size: ' + text_fontSize(o) + 'px; ';
if (o.fontStyle) s += 'font-style: ' + o.fontStyle + '; ';
if (o.fontVariant) s += 'font-variant: ' + o.fontVariant + '; ';
if (o.fontWeight) s += 'font-weight: ' + o.fontWeight + '; ';
}
for (i=0, n=styleProperties.length; i<n; ++i) {
prop = styleProperties[i];
name = styles[prop];
value = o[prop];
if (value == null) {
if (name === 'fill') {
s += 'fill: none; ';
}
} else if (value === 'transparent' && (name === 'fill' || name === 'stroke')) {
// transparent is not a legal SVG value, so map to none instead
s += name + ': none; ';
} else {
if (isGradient(value)) {
value = gradientRef(value, defs.gradient, '');
}
s += name + ': ' + value + '; ';
}
}
return s ? 'style="' + s.trim() + '"' : null;
}
function SVGStringRenderer_escape_text(s) {
return s.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/modules.js
var modules_Canvas = 'canvas';
var modules_PNG = 'png';
var modules_SVG = 'svg';
var modules_None = 'none';
var modules_RenderType = {
Canvas: modules_Canvas,
PNG: modules_PNG,
SVG: modules_SVG,
None: modules_None
};
var modules_modules = {};
modules_modules[modules_Canvas] = modules_modules[modules_PNG] = {
renderer: CanvasRenderer_CanvasRenderer,
headless: CanvasRenderer_CanvasRenderer,
handler: CanvasHandler_CanvasHandler
};
modules_modules[modules_SVG] = {
renderer: SVGRenderer_SVGRenderer,
headless: SVGStringRenderer_SVGStringRenderer,
handler: SVGHandler_SVGHandler
};
modules_modules[modules_None] = {};
function modules_renderModule(name, _) {
name = String(name || '').toLowerCase();
if (arguments.length > 1) {
modules_modules[name] = _;
return this;
} else {
return modules_modules[name];
}
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/intersect.js
function intersect_intersect(scene, bounds, filter) {
const hits = [], // intersection results
box = new Bounds().union(bounds), // defensive copy
type = scene.marktype;
return type ? intersect_intersectMark(scene, box, filter, hits)
: type === 'group' ? intersect_intersectGroup(scene, box, filter, hits)
: Object(vega_util["n" /* error */])('Intersect scene must be mark node or group item.');
}
function intersect_intersectMark(mark, box, filter, hits) {
if (intersect_visitMark(mark, box, filter)) {
const items = mark.items,
type = mark.marktype,
n = items.length;
let i = 0;
if (type === 'group') {
for (; i<n; ++i) {
intersect_intersectGroup(items[i], box, filter, hits);
}
} else {
for (const test = src_marks[type].isect; i<n; ++i) {
let item = items[i];
if (intersect_intersectItem(item, box, test)) hits.push(item);
}
}
}
return hits;
}
function intersect_visitMark(mark, box, filter) {
// process if bounds intersect and if
// (1) mark is a group mark (so we must recurse), or
// (2) mark is interactive and passes filter
return mark.bounds && box.intersects(mark.bounds) && (
mark.marktype === 'group' ||
mark.interactive !== false && (!filter || filter(mark))
);
}
function intersect_intersectGroup(group, box, filter, hits) {
// test intersect against group
// skip groups by default unless filter says otherwise
if ((filter && filter(group.mark)) &&
intersect_intersectItem(group, box, src_marks.group.isect)) {
hits.push(group);
}
// recursively test children marks
// translate box to group coordinate space
const marks = group.items,
n = marks && marks.length;
if (n) {
const x = group.x || 0,
y = group.y || 0;
box.translate(-x, -y);
for (let i=0; i<n; ++i) {
intersect_intersectMark(marks[i], box, filter, hits);
}
box.translate(x, y);
}
return hits;
}
function intersect_intersectItem(item, box, test) {
// test bounds enclosure, bounds intersection, then detailed test
const bounds = item.bounds;
return box.encloses(bounds) || (box.intersects(bounds) && test(item, box));
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/bound/boundClip.js
var boundClip_clipBounds = new Bounds();
/* harmony default export */ var boundClip = (function(mark) {
var clip = mark.clip;
if (Object(vega_util["D" /* isFunction */])(clip)) {
clip(boundContext_context(boundClip_clipBounds.clear()));
} else if (clip) {
boundClip_clipBounds.set(0, 0, mark.group.width, mark.group.height);
} else return;
mark.bounds.intersect(boundClip_clipBounds);
});
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/src/util/equal.js
var equal_TOLERANCE = 1e-9;
function equal_sceneEqual(a, b, key) {
return (a === b) ? true
: (key === 'path') ? equal_pathEqual(a, b)
: (a instanceof Date && b instanceof Date) ? +a === +b
: (Object(vega_util["E" /* isNumber */])(a) && Object(vega_util["E" /* isNumber */])(b)) ? Math.abs(a - b) <= equal_TOLERANCE
: (!a || !b || !Object(vega_util["F" /* isObject */])(a) && !Object(vega_util["F" /* isObject */])(b)) ? a == b
: (a == null || b == null) ? false
: equal_objectEqual(a, b);
}
function equal_pathEqual(a, b) {
return equal_sceneEqual(path_parse(a), path_parse(b));
}
function equal_objectEqual(a, b) {
var ka = Object.keys(a),
kb = Object.keys(b),
key, i;
if (ka.length !== kb.length) return false;
ka.sort();
kb.sort();
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i]) return false;
}
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!equal_sceneEqual(a[key], b[key], key)) return false;
}
return typeof a === typeof b;
}
// CONCATENATED MODULE: ./node_modules/vega-scenegraph/index.js
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/Bound.js
/**
* Calculate bounding boxes for scenegraph items.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {object} params.mark - The scenegraph mark instance to bound.
*/
function Bound_Bound(params) {
Transform_Transform.call(this, null, params);
}
var Bound_prototype = Object(vega_util["y" /* inherits */])(Bound_Bound, Transform_Transform);
Bound_prototype.transform = function(_, pulse) {
var view = pulse.dataflow,
mark = _.mark,
type = mark.marktype,
entry = src_marks[type],
bound = entry.bound,
markBounds = mark.bounds, rebound;
if (entry.nested) {
// multi-item marks have a single bounds instance
if (mark.items.length) view.dirty(mark.items[0]);
markBounds = Bound_boundItem(mark, bound);
mark.items.forEach(function(item) {
item.bounds.clear().union(markBounds);
});
}
else if (type === Group || _.modified()) {
// operator parameters modified -> re-bound all items
// updates group bounds in response to modified group content
pulse.visit(pulse.MOD, function(item) { view.dirty(item); });
markBounds.clear();
mark.items.forEach(function(item) {
markBounds.union(Bound_boundItem(item, bound));
});
// force reflow for axes/legends/titles to propagate any layout changes
switch (mark.role) {
case AxisRole:
case LegendRole:
case TitleRole:
pulse.reflow();
}
}
else {
// incrementally update bounds, re-bound mark as needed
rebound = pulse.changed(pulse.REM);
pulse.visit(pulse.ADD, function(item) {
markBounds.union(Bound_boundItem(item, bound));
});
pulse.visit(pulse.MOD, function(item) {
rebound = rebound || markBounds.alignsWith(item.bounds);
view.dirty(item);
markBounds.union(Bound_boundItem(item, bound));
});
if (rebound) {
markBounds.clear();
mark.items.forEach(function(item) { markBounds.union(item.bounds); });
}
}
// ensure mark bounds do not exceed any clipping region
boundClip(mark);
return pulse.modifies('bounds');
};
function Bound_boundItem(item, bound, opt) {
return bound(item.bounds.clear(), item, opt);
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/Identifier.js
var Identifier_COUNTER_NAME = ':vega_identifier:';
/**
* Adds a unique identifier to all added tuples.
* This transform creates a new signal that serves as an id counter.
* As a result, the id counter is shared across all instances of this
* transform, generating unique ids across multiple data streams. In
* addition, this signal value can be included in a snapshot of the
* dataflow state, enabling correct resumption of id allocation.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {string} params.as - The field name for the generated identifier.
*/
function Identifier_Identifier(params) {
Transform_Transform.call(this, 0, params);
}
Identifier_Identifier.Definition = {
"type": "Identifier",
"metadata": {"modifies": true},
"params": [
{ "name": "as", "type": "string", "required": true }
]
};
var Identifier_prototype = Object(vega_util["y" /* inherits */])(Identifier_Identifier, Transform_Transform);
Identifier_prototype.transform = function(_, pulse) {
var counter = Identifier_getCounter(pulse.dataflow),
id = counter.value,
as = _.as;
pulse.visit(pulse.ADD, function(t) {
if (!t[as]) t[as] = ++id;
});
counter.set(this.value = id);
return pulse;
};
function Identifier_getCounter(view) {
var counter = view._signals[Identifier_COUNTER_NAME];
if (!counter) {
view._signals[Identifier_COUNTER_NAME] = (counter = view.add(0));
}
return counter;
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/Mark.js
/**
* Bind scenegraph items to a scenegraph mark instance.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {object} params.markdef - The mark definition for creating the mark.
* This is an object of legal scenegraph mark properties which *must* include
* the 'marktype' property.
*/
function Mark_Mark(params) {
Transform_Transform.call(this, null, params);
}
var Mark_prototype = Object(vega_util["y" /* inherits */])(Mark_Mark, Transform_Transform);
Mark_prototype.transform = function(_, pulse) {
var mark = this.value;
// acquire mark on first invocation, bind context and group
if (!mark) {
mark = pulse.dataflow.scenegraph().mark(_.markdef, Mark_lookup(_), _.index);
mark.group.context = _.context;
if (!_.context.group) _.context.group = mark.group;
mark.source = this.source; // point to upstream collector
mark.clip = _.clip;
mark.interactive = _.interactive;
this.value = mark;
}
// initialize entering items
var Init = mark.marktype === Group ? GroupItem_GroupItem : Item_Item;
pulse.visit(pulse.ADD, function(item) { Init.call(item, mark); });
// update clipping and/or interactive status
if (_.modified('clip') || _.modified('interactive')) {
mark.clip = _.clip;
mark.interactive = !!_.interactive;
mark.zdirty = true; // force scenegraph re-eval
pulse.reflow();
}
// bind items array to scenegraph mark
mark.items = pulse.source;
return pulse;
};
function Mark_lookup(_) {
var g = _.groups, p = _.parent;
return g && g.size === 1 ? g.get(Object.keys(g.object)[0])
: g && p ? g.lookup(p)
: null;
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/Overlap.js
/**
* Analyze items for overlap, changing opacity to hide items with
* overlapping bounding boxes. This transform will preserve at least
* two items (e.g., first and last) even if overlap persists.
* @param {object} params - The parameters for this operator.
* @param {function(*,*): number} [params.sort] - A comparator
* function for sorting items.
* @param {object} [params.method] - The overlap removal method to apply.
* One of 'parity' (default, hide every other item until there is no
* more overlap) or 'greedy' (sequentially scan and hide and items that
* overlap with the last visible item).
* @param {object} [params.boundScale] - A scale whose range should be used
* to bound the items. Items exceeding the bounds of the scale range
* will be treated as overlapping. If null or undefined, no bounds check
* will be applied.
* @param {object} [params.boundOrient] - The orientation of the scale
* (top, bottom, left, or right) used to bound items. This parameter is
* ignored if boundScale is null or undefined.
* @param {object} [params.boundTolerance] - The tolerance in pixels for
* bound inclusion testing (default 1). This specifies by how many pixels
* an item's bounds may exceed the scale range bounds and not be culled.
* @constructor
*/
function Overlap_Overlap(params) {
Transform_Transform.call(this, null, params);
}
var Overlap_prototype = Object(vega_util["y" /* inherits */])(Overlap_Overlap, Transform_Transform);
var Overlap_methods = {
parity: function(items) {
return items.filter((item, i) => i % 2 ? (item.opacity = 0) : 1);
},
greedy: function(items, sep) {
var a;
return items.filter((b, i) => {
if (!i || !Overlap_intersect(a.bounds, b.bounds, sep)) {
a = b;
return 1;
} else {
return b.opacity = 0;
}
});
}
};
// compute bounding box intersection
// including padding pixels of separation
function Overlap_intersect(a, b, sep) {
return sep > Math.max(
b.x1 - a.x2,
a.x1 - b.x2,
b.y1 - a.y2,
a.y1 - b.y2
);
}
function Overlap_hasOverlap(items, pad) {
for (var i=1, n=items.length, a=items[0].bounds, b; i<n; a=b, ++i) {
if (Overlap_intersect(a, b = items[i].bounds, pad)) return true;
}
}
function Overlap_hasBounds(item) {
var b = item.bounds;
return b.width() > 1 && b.height() > 1;
}
function Overlap_boundTest(scale, orient, tolerance) {
var range = scale.range(),
b = new Bounds();
if (orient === Top || orient === Bottom) {
b.set(range[0], -Infinity, range[1], +Infinity);
} else {
b.set(-Infinity, range[0], +Infinity, range[1]);
}
b.expand(tolerance || 1);
return item => b.encloses(item.bounds);
}
// reset all items to be fully opaque
function Overlap_reset(source) {
source.forEach(item => item.opacity = 1);
return source;
}
// add all tuples to mod, fork pulse if parameters were modified
// fork prevents cross-stream tuple pollution (e.g., pulse from scale)
function Overlap_reflow(pulse, _) {
return pulse.reflow(_.modified()).modifies('opacity');
}
Overlap_prototype.transform = function(_, pulse) {
var reduce = Overlap_methods[_.method] || Overlap_methods.parity,
source = pulse.materialize(pulse.SOURCE).source,
sep = _.separation || 0,
items, test, bounds;
if (!source || !source.length) return;
if (!_.method) {
// early exit if method is falsy
if (_.modified('method')) {
Overlap_reset(source);
pulse = Overlap_reflow(pulse, _);
}
return pulse;
}
// skip labels with no content
source = source.filter(Overlap_hasBounds);
// early exit, nothing to do
if (!source.length) return;
if (_.sort) {
source = source.slice().sort(_.sort);
}
items = Overlap_reset(source);
pulse = Overlap_reflow(pulse, _);
if (items.length >= 3 && Overlap_hasOverlap(items, sep)) {
do {
items = reduce(items, sep);
} while (items.length >= 3 && Overlap_hasOverlap(items, sep));
if (items.length < 3 && !Object(vega_util["U" /* peek */])(source).opacity) {
if (items.length > 1) Object(vega_util["U" /* peek */])(items).opacity = 0;
Object(vega_util["U" /* peek */])(source).opacity = 1;
}
}
if (_.boundScale && _.boundTolerance >= 0) {
test = Overlap_boundTest(_.boundScale, _.boundOrient, +_.boundTolerance);
source.forEach(item => {
if (!test(item)) item.opacity = 0;
});
}
// re-calculate mark bounds
bounds = items[0].mark.bounds.clear();
source.forEach(item => {
if (item.opacity) bounds.union(item.bounds);
});
return pulse;
};
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/Render.js
/**
* Queue modified scenegraph items for rendering.
* @constructor
*/
function Render_Render(params) {
Transform_Transform.call(this, null, params);
}
var Render_prototype = Object(vega_util["y" /* inherits */])(Render_Render, Transform_Transform);
Render_prototype.transform = function(_, pulse) {
var view = pulse.dataflow;
pulse.visit(pulse.ALL, function(item) { view.dirty(item); });
// set z-index dirty flag as needed
if (pulse.fields && pulse.fields['zindex']) {
var item = pulse.source && pulse.source[0];
if (item) item.mark.zdirty = true;
}
};
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/layout/util.js
const util_tempBounds = new Bounds();
function util_set(item, property, value) {
return item[property] === value ? 0
: (item[property] = value, 1);
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/layout/axis.js
function axis_isYAxis(mark) {
var orient = mark.items[0].datum.orient;
return orient === Left || orient === Right;
}
function axis_axisIndices(datum) {
var index = +datum.grid;
return [
datum.ticks ? index++ : -1, // ticks index
datum.labels ? index++ : -1, // labels index
index + (+datum.domain) // title index
];
}
function axis_axisLayout(view, axis, width, height) {
var item = axis.items[0],
datum = item.datum,
orient = datum.orient,
delta = datum.translate != null ? datum.translate : 0.5,
indices = axis_axisIndices(datum),
range = item.range,
offset = item.offset,
position = item.position,
minExtent = item.minExtent,
maxExtent = item.maxExtent,
title = datum.title && item.items[indices[2]].items[0],
titlePadding = item.titlePadding,
bounds = item.bounds,
dl = title && text_multiLineOffset(title),
x = 0, y = 0, i, s;
util_tempBounds.clear().union(bounds);
bounds.clear();
if ((i=indices[0]) > -1) bounds.union(item.items[i].bounds);
if ((i=indices[1]) > -1) bounds.union(item.items[i].bounds);
// position axis group and title
switch (orient) {
case Top:
x = position || 0;
y = -offset;
s = Math.max(minExtent, Math.min(maxExtent, -bounds.y1));
bounds.add(0, -s).add(range, 0);
if (title) axis_axisTitleLayout(view, title, s, titlePadding, dl, 0, -1, bounds);
break;
case Left:
x = -offset;
y = position || 0;
s = Math.max(minExtent, Math.min(maxExtent, -bounds.x1));
bounds.add(-s, 0).add(0, range);
if (title) axis_axisTitleLayout(view, title, s, titlePadding, dl, 1, -1, bounds);
break;
case Right:
x = width + offset;
y = position || 0;
s = Math.max(minExtent, Math.min(maxExtent, bounds.x2));
bounds.add(0, 0).add(s, range);
if (title) axis_axisTitleLayout(view, title, s, titlePadding, dl, 1, 1, bounds);
break;
case Bottom:
x = position || 0;
y = height + offset;
s = Math.max(minExtent, Math.min(maxExtent, bounds.y2));
bounds.add(0, 0).add(range, s);
if (title) axis_axisTitleLayout(view, title, s, titlePadding, 0, 0, 1, bounds);
break;
default:
x = item.x;
y = item.y;
}
// update bounds
boundStroke(bounds.translate(x, y), item);
if (util_set(item, 'x', x + delta) | util_set(item, 'y', y + delta)) {
item.bounds = util_tempBounds;
view.dirty(item);
item.bounds = bounds;
view.dirty(item);
}
return item.mark.bounds.clear().union(bounds);
}
function axis_axisTitleLayout(view, title, offset, pad, dl, isYAxis, sign, bounds) {
const b = title.bounds;
if (title.auto) {
const v = sign * (offset + dl + pad);
let dx = 0, dy = 0;
view.dirty(title);
isYAxis
? dx = (title.x || 0) - (title.x = v)
: dy = (title.y || 0) - (title.y = v);
title.mark.bounds.clear().union(b.translate(-dx, -dy));
view.dirty(title);
}
bounds.union(b);
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/layout/grid.js
function grid_gridLayoutGroups(group) {
var groups = group.items,
n = groups.length,
i = 0, mark, items;
var views = {
marks: [],
rowheaders: [],
rowfooters: [],
colheaders: [],
colfooters: [],
rowtitle: null,
coltitle: null
};
// layout axes, gather legends, collect bounds
for (; i<n; ++i) {
mark = groups[i];
items = mark.items;
if (mark.marktype === Group) {
switch (mark.role) {
case AxisRole:
case LegendRole:
case TitleRole:
break;
case RowHeader: views.rowheaders.push(...items); break;
case RowFooter: views.rowfooters.push(...items); break;
case ColHeader: views.colheaders.push(...items); break;
case ColFooter: views.colfooters.push(...items); break;
case RowTitle: views.rowtitle = items[0]; break;
case ColTitle: views.coltitle = items[0]; break;
default: views.marks.push(...items);
}
}
}
return views;
}
function grid_bboxFlush(item) {
return new Bounds().set(0, 0, item.width || 0, item.height || 0);
}
function grid_bboxFull(item) {
var b = item.bounds.clone();
return b.empty()
? b.set(0, 0, 0, 0)
: b.translate(-(item.x || 0), -(item.y || 0));
}
function grid_get(opt, key, d) {
var v = Object(vega_util["F" /* isObject */])(opt) ? opt[key] : opt;
return v != null ? v : (d !== undefined ? d : 0);
}
function grid_offsetValue(v) {
return v < 0 ? Math.ceil(-v) : 0;
}
function grid_gridLayout(view, groups, opt) {
var dirty = !opt.nodirty,
bbox = opt.bounds === Flush ? grid_bboxFlush : grid_bboxFull,
bounds = util_tempBounds.set(0, 0, 0, 0),
alignCol = grid_get(opt.align, Column),
alignRow = grid_get(opt.align, Row),
padCol = grid_get(opt.padding, Column),
padRow = grid_get(opt.padding, Row),
ncols = opt.columns || groups.length,
nrows = ncols < 0 ? 1 : Math.ceil(groups.length / ncols),
n = groups.length,
xOffset = Array(n), xExtent = Array(ncols), xMax = 0,
yOffset = Array(n), yExtent = Array(nrows), yMax = 0,
dx = Array(n), dy = Array(n), boxes = Array(n),
m, i, c, r, b, g, px, py, x, y, offset;
for (i=0; i<ncols; ++i) xExtent[i] = 0;
for (i=0; i<nrows; ++i) yExtent[i] = 0;
// determine offsets for each group
for (i=0; i<n; ++i) {
g = groups[i];
b = boxes[i] = bbox(g);
g.x = g.x || 0; dx[i] = 0;
g.y = g.y || 0; dy[i] = 0;
c = i % ncols;
r = ~~(i / ncols);
xMax = Math.max(xMax, px = Math.ceil(b.x2));
yMax = Math.max(yMax, py = Math.ceil(b.y2));
xExtent[c] = Math.max(xExtent[c], px);
yExtent[r] = Math.max(yExtent[r], py);
xOffset[i] = padCol + grid_offsetValue(b.x1);
yOffset[i] = padRow + grid_offsetValue(b.y1);
if (dirty) view.dirty(groups[i]);
}
// set initial alignment offsets
for (i=0; i<n; ++i) {
if (i % ncols === 0) xOffset[i] = 0;
if (i < ncols) yOffset[i] = 0;
}
// enforce column alignment constraints
if (alignCol === Each) {
for (c=1; c<ncols; ++c) {
for (offset=0, i=c; i<n; i += ncols) {
if (offset < xOffset[i]) offset = xOffset[i];
}
for (i=c; i<n; i += ncols) {
xOffset[i] = offset + xExtent[c-1];
}
}
} else if (alignCol === All) {
for (offset=0, i=0; i<n; ++i) {
if (i % ncols && offset < xOffset[i]) offset = xOffset[i];
}
for (i=0; i<n; ++i) {
if (i % ncols) xOffset[i] = offset + xMax;
}
} else {
for (alignCol=false, c=1; c<ncols; ++c) {
for (i=c; i<n; i += ncols) {
xOffset[i] += xExtent[c-1];
}
}
}
// enforce row alignment constraints
if (alignRow === Each) {
for (r=1; r<nrows; ++r) {
for (offset=0, i=r*ncols, m=i+ncols; i<m; ++i) {
if (offset < yOffset[i]) offset = yOffset[i];
}
for (i=r*ncols; i<m; ++i) {
yOffset[i] = offset + yExtent[r-1];
}
}
} else if (alignRow === All) {
for (offset=0, i=ncols; i<n; ++i) {
if (offset < yOffset[i]) offset = yOffset[i];
}
for (i=ncols; i<n; ++i) {
yOffset[i] = offset + yMax;
}
} else {
for (alignRow=false, r=1; r<nrows; ++r) {
for (i=r*ncols, m=i+ncols; i<m; ++i) {
yOffset[i] += yExtent[r-1];
}
}
}
// perform horizontal grid layout
for (x=0, i=0; i<n; ++i) {
x = xOffset[i] + (i % ncols ? x : 0);
dx[i] += x - groups[i].x;
}
// perform vertical grid layout
for (c=0; c<ncols; ++c) {
for (y=0, i=c; i<n; i += ncols) {
y += yOffset[i];
dy[i] += y - groups[i].y;
}
}
// perform horizontal centering
if (alignCol && grid_get(opt.center, Column) && nrows > 1) {
for (i=0; i<n; ++i) {
b = alignCol === All ? xMax : xExtent[i % ncols];
x = b - boxes[i].x2 - groups[i].x - dx[i];
if (x > 0) dx[i] += x / 2;
}
}
// perform vertical centering
if (alignRow && grid_get(opt.center, Row) && ncols !== 1) {
for (i=0; i<n; ++i) {
b = alignRow === All ? yMax : yExtent[~~(i / ncols)];
y = b - boxes[i].y2 - groups[i].y - dy[i];
if (y > 0) dy[i] += y / 2;
}
}
// position grid relative to anchor
for (i=0; i<n; ++i) {
bounds.union(boxes[i].translate(dx[i], dy[i]));
}
x = grid_get(opt.anchor, constants_X);
y = grid_get(opt.anchor, constants_Y);
switch (grid_get(opt.anchor, Column)) {
case End: x -= bounds.width(); break;
case Middle: x -= bounds.width() / 2;
}
switch (grid_get(opt.anchor, Row)) {
case End: y -= bounds.height(); break;
case Middle: y -= bounds.height() / 2;
}
x = Math.round(x);
y = Math.round(y);
// update mark positions, bounds, dirty
bounds.clear();
for (i=0; i<n; ++i) {
groups[i].mark.bounds.clear();
}
for (i=0; i<n; ++i) {
g = groups[i];
g.x += (dx[i] += x);
g.y += (dy[i] += y);
bounds.union(g.mark.bounds.union(g.bounds.translate(dx[i], dy[i])));
if (dirty) view.dirty(g);
}
return bounds;
}
function grid_trellisLayout(view, group, opt) {
var views = grid_gridLayoutGroups(group),
groups = views.marks,
bbox = opt.bounds === Flush ? grid_boundFlush : grid_boundFull,
off = opt.offset,
ncols = opt.columns || groups.length,
nrows = ncols < 0 ? 1 : Math.ceil(groups.length / ncols),
cells = nrows * ncols,
x, y, x2, y2, anchor, band, offset;
// -- initial grid layout
const bounds = grid_gridLayout(view, groups, opt);
// -- layout grid headers and footers --
// perform row header layout
if (views.rowheaders) {
band = grid_get(opt.headerBand, Row, null);
x = grid_layoutHeaders(view, views.rowheaders, groups, ncols, nrows, -grid_get(off, 'rowHeader'), grid_min, 0, bbox, 'x1', 0, ncols, 1, band);
}
// perform column header layout
if (views.colheaders) {
band = grid_get(opt.headerBand, Column, null);
y = grid_layoutHeaders(view, views.colheaders, groups, ncols, ncols, -grid_get(off, 'columnHeader'), grid_min, 1, bbox, 'y1', 0, 1, ncols, band);
}
// perform row footer layout
if (views.rowfooters) {
band = grid_get(opt.footerBand, Row, null);
x2 = grid_layoutHeaders(view, views.rowfooters, groups, ncols, nrows, grid_get(off, 'rowFooter'), grid_max, 0, bbox, 'x2', ncols-1, ncols, 1, band);
}
// perform column footer layout
if (views.colfooters) {
band = grid_get(opt.footerBand, Column, null);
y2 = grid_layoutHeaders(view, views.colfooters, groups, ncols, ncols, grid_get(off, 'columnFooter'), grid_max, 1, bbox, 'y2', cells-ncols, 1, ncols, band);
}
// perform row title layout
if (views.rowtitle) {
anchor = grid_get(opt.titleAnchor, Row);
offset = grid_get(off, 'rowTitle');
offset = anchor === End ? x2 + offset : x - offset;
band = grid_get(opt.titleBand, Row, 0.5);
grid_layoutTitle(view, views.rowtitle, offset, 0, bounds, band);
}
// perform column title layout
if (views.coltitle) {
anchor = grid_get(opt.titleAnchor, Column);
offset = grid_get(off, 'columnTitle');
offset = anchor === End ? y2 + offset : y - offset;
band = grid_get(opt.titleBand, Column, 0.5);
grid_layoutTitle(view, views.coltitle, offset, 1, bounds, band);
}
}
function grid_boundFlush(item, field) {
return field === 'x1' ? (item.x || 0)
: field === 'y1' ? (item.y || 0)
: field === 'x2' ? (item.x || 0) + (item.width || 0)
: field === 'y2' ? (item.y || 0) + (item.height || 0)
: undefined;
}
function grid_boundFull(item, field) {
return item.bounds[field];
}
// aggregation functions for grid margin determination
function grid_min(a, b) { return Math.floor(Math.min(a, b)); }
function grid_max(a, b) { return Math.ceil(Math.max(a, b)); }
function grid_layoutHeaders(view, headers, groups, ncols, limit, offset, agg, isX, bound, bf, start, stride, back, band) {
var n = groups.length,
init = 0,
edge = 0,
i, j, k, m, b, h, g, x, y;
// if no groups, early exit and return 0
if (!n) return init;
// compute margin
for (i=start; i<n; i+=stride) {
if (groups[i]) init = agg(init, bound(groups[i], bf));
}
// if no headers, return margin calculation
if (!headers.length) return init;
// check if number of headers exceeds number of rows or columns
if (headers.length > limit) {
view.warn('Grid headers exceed limit: ' + limit);
headers = headers.slice(0, limit);
}
// apply offset
init += offset;
// clear mark bounds for all headers
for (j=0, m=headers.length; j<m; ++j) {
view.dirty(headers[j]);
headers[j].mark.bounds.clear();
}
// layout each header
for (i=start, j=0, m=headers.length; j<m; ++j, i+=stride) {
h = headers[j];
b = h.mark.bounds;
// search for nearest group to align to
// necessary if table has empty cells
for (k=i; k >= 0 && (g = groups[k]) == null; k-=back);
// assign coordinates and update bounds
if (isX) {
x = band == null ? g.x : Math.round(g.bounds.x1 + band * g.bounds.width());
y = init;
} else {
x = init;
y = band == null ? g.y : Math.round(g.bounds.y1 + band * g.bounds.height());
}
b.union(h.bounds.translate(x - (h.x || 0), y - (h.y || 0)));
h.x = x;
h.y = y;
view.dirty(h);
// update current edge of layout bounds
edge = agg(edge, b[bf]);
}
return edge;
}
function grid_layoutTitle(view, g, offset, isX, bounds, band) {
if (!g) return;
view.dirty(g);
// compute title coordinates
var x = offset, y = offset;
isX
? (x = Math.round(bounds.x1 + band * bounds.width()))
: (y = Math.round(bounds.y1 + band * bounds.height()));
// assign coordinates and update bounds
g.bounds.translate(x - (g.x || 0), y - (g.y || 0));
g.mark.bounds.clear().union(g.bounds);
g.x = x;
g.y = y;
// queue title for redraw
view.dirty(g);
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/layout/legend.js
// utility for looking up legend layout configuration
function legend_lookup(config, orient) {
const opt = config[orient] || {};
return (key, d) => opt[key] != null ? opt[key]
: config[key] != null ? config[key]
: d;
}
// if legends specify offset directly, use the maximum specified value
function legend_offsets(legends, value) {
var max = -Infinity;
legends.forEach(item => {
if (item.offset != null) max = Math.max(max, item.offset);
});
return max > -Infinity ? max : value;
}
function legend_legendParams(g, orient, config, xb, yb, w, h) {
const _ = legend_lookup(config, orient),
offset = legend_offsets(g, _('offset', 0)),
anchor = _('anchor', Start),
mult = anchor === End ? 1 : anchor === Middle ? 0.5 : 0;
const p = {
align: Each,
bounds: _('bounds', Flush),
columns: _('direction') === 'vertical' ? 1 : g.length,
padding: _('margin', 8),
center: _('center'),
nodirty: true
};
switch (orient) {
case Left:
p.anchor = {
x: Math.floor(xb.x1) - offset, column: End,
y: mult * (h || xb.height() + 2 * xb.y1), row: anchor
};
break;
case Right:
p.anchor = {
x: Math.ceil(xb.x2) + offset,
y: mult * (h || xb.height() + 2 * xb.y1), row: anchor
};
break;
case Top:
p.anchor = {
y: Math.floor(yb.y1) - offset, row: End,
x: mult * (w || yb.width() + 2 * yb.x1), column: anchor
};
break;
case Bottom:
p.anchor = {
y: Math.ceil(yb.y2) + offset,
x: mult * (w || yb.width() + 2 * yb.x1), column: anchor
};
break;
case TopLeft:
p.anchor = {x: offset, y: offset};
break;
case TopRight:
p.anchor = {x: w - offset, y: offset, column: End};
break;
case BottomLeft:
p.anchor = {x: offset, y: h - offset, row: End};
break;
case BottomRight:
p.anchor = {x: w - offset, y: h - offset, column: End, row: End};
break;
}
return p;
}
function legend_legendLayout(view, legend) {
var item = legend.items[0],
datum = item.datum,
orient = item.orient,
bounds = item.bounds,
x = item.x, y = item.y, w, h;
// cache current bounds for later comparison
item._bounds
? item._bounds.clear().union(bounds)
: item._bounds = bounds.clone();
bounds.clear();
// adjust legend to accommodate padding and title
legend_legendGroupLayout(view, item, item.items[0].items[0]);
// aggregate bounds to determine size, and include origin
bounds = legend_legendBounds(item, bounds);
w = 2 * item.padding;
h = 2 * item.padding;
if (!bounds.empty()) {
w = Math.ceil(bounds.width() + w);
h = Math.ceil(bounds.height() + h);
}
if (datum.type === Symbols) {
legend_legendEntryLayout(item.items[0].items[0].items[0].items);
}
if (orient !== constants_None) {
item.x = x = 0;
item.y = y = 0;
}
item.width = w;
item.height = h;
boundStroke(bounds.set(x, y, x + w, y + h), item);
item.mark.bounds.clear().union(bounds);
return item;
}
function legend_legendBounds(item, b) {
// aggregate item bounds
item.items.forEach(_ => b.union(_.bounds));
// anchor to legend origin
b.x1 = item.padding;
b.y1 = item.padding;
return b;
}
function legend_legendGroupLayout(view, item, entry) {
var pad = item.padding,
ex = pad - entry.x,
ey = pad - entry.y;
if (!item.datum.title) {
if (ex || ey) legend_translate(view, entry, ex, ey);
} else {
var title = item.items[1].items[0],
anchor = title.anchor,
tpad = item.titlePadding || 0,
tx = pad - title.x,
ty = pad - title.y;
switch (title.orient) {
case Left:
ex += Math.ceil(title.bounds.width()) + tpad;
break;
case Right:
case Bottom:
break;
default:
ey += title.bounds.height() + tpad;
}
if (ex || ey) legend_translate(view, entry, ex, ey);
switch (title.orient) {
case Left:
ty += legend_legendTitleOffset(item, entry, title, anchor, 1, 1);
break;
case Right:
tx += legend_legendTitleOffset(item, entry, title, End, 0, 0) + tpad;
ty += legend_legendTitleOffset(item, entry, title, anchor, 1, 1);
break;
case Bottom:
tx += legend_legendTitleOffset(item, entry, title, anchor, 0, 0);
ty += legend_legendTitleOffset(item, entry, title, End, -1, 0, 1) + tpad;
break;
default:
tx += legend_legendTitleOffset(item, entry, title, anchor, 0, 0);
}
if (tx || ty) legend_translate(view, title, tx, ty);
// translate legend if title pushes into negative coordinates
if ((tx = Math.round(title.bounds.x1 - pad)) < 0) {
legend_translate(view, entry, -tx, 0);
legend_translate(view, title, -tx, 0);
}
}
}
function legend_legendTitleOffset(item, entry, title, anchor, y, lr, noBar) {
const grad = item.datum.type !== 'symbol',
vgrad = title.datum.vgrad,
e = grad && (lr || !vgrad) && !noBar ? entry.items[0] : entry,
s = e.bounds[y ? 'y2' : 'x2'] - item.padding,
u = vgrad && lr ? s : 0,
v = vgrad && lr ? 0 : s,
o = y <= 0 ? 0 : text_multiLineOffset(title);
return Math.round(anchor === Start ? u
: anchor === End ? (v - o)
: 0.5 * (s - o));
}
function legend_translate(view, item, dx, dy) {
item.x += dx;
item.y += dy;
item.bounds.translate(dx, dy);
item.mark.bounds.translate(dx, dy);
view.dirty(item);
}
function legend_legendEntryLayout(entries) {
// get max widths for each column
var widths = entries.reduce(function(w, g) {
w[g.column] = Math.max(g.bounds.x2 - g.x, w[g.column] || 0);
return w;
}, {});
// set dimensions of legend entry groups
entries.forEach(function(g) {
g.width = widths[g.column];
g.height = g.bounds.y2 - g.y;
});
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/layout/title.js
function title_titleLayout(view, mark, width, height, viewBounds) {
var group = mark.items[0],
frame = group.frame,
orient = group.orient,
anchor = group.anchor,
offset = group.offset,
padding = group.padding,
title = group.items[0].items[0],
subtitle = group.items[1] && group.items[1].items[0],
end = (orient === Left || orient === Right) ? height : width,
start = 0, x = 0, y = 0, sx = 0, sy = 0, pos;
if (frame !== Group) {
orient === Left ? (start = viewBounds.y2, end = viewBounds.y1)
: orient === Right ? (start = viewBounds.y1, end = viewBounds.y2)
: (start = viewBounds.x1, end = viewBounds.x2);
} else if (orient === Left) {
start = height, end = 0;
}
pos = (anchor === Start) ? start
: (anchor === End) ? end
: (start + end) / 2;
if (subtitle && subtitle.text) {
// position subtitle
switch (orient) {
case Top:
case Bottom:
sy = title.bounds.height() + padding;
break;
case Left:
sx = title.bounds.width() + padding;
break;
case Right:
sx = -title.bounds.width() - padding;
break;
}
util_tempBounds.clear().union(subtitle.bounds);
util_tempBounds.translate(sx - (subtitle.x || 0), sy - (subtitle.y || 0));
if (util_set(subtitle, 'x', sx) | util_set(subtitle, 'y', sy)) {
view.dirty(subtitle);
subtitle.bounds.clear().union(util_tempBounds);
subtitle.mark.bounds.clear().union(util_tempBounds);
view.dirty(subtitle);
}
util_tempBounds.clear().union(subtitle.bounds);
} else {
util_tempBounds.clear();
}
util_tempBounds.union(title.bounds);
// position title group
switch (orient) {
case Top:
x = pos;
y = viewBounds.y1 - util_tempBounds.height() - offset;
break;
case Left:
x = viewBounds.x1 - util_tempBounds.width() - offset;
y = pos;
break;
case Right:
x = viewBounds.x2 + util_tempBounds.width() + offset;
y = pos;
break;
case Bottom:
x = pos;
y = viewBounds.y2 + offset;
break;
default:
x = group.x;
y = group.y;
}
if (util_set(group, 'x', x) | util_set(group, 'y', y)) {
util_tempBounds.translate(x, y);
view.dirty(group);
group.bounds.clear().union(util_tempBounds);
mark.bounds.clear().union(util_tempBounds);
view.dirty(group);
}
return group.bounds;
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/src/ViewLayout.js
/**
* Layout view elements such as axes and legends.
* Also performs size adjustments.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {object} params.mark - Scenegraph mark of groups to layout.
*/
function ViewLayout_ViewLayout(params) {
Transform_Transform.call(this, null, params);
}
var ViewLayout_prototype = Object(vega_util["y" /* inherits */])(ViewLayout_ViewLayout, Transform_Transform);
ViewLayout_prototype.transform = function(_, pulse) {
// TODO incremental update, output?
var view = pulse.dataflow;
_.mark.items.forEach(function(group) {
if (_.layout) grid_trellisLayout(view, group, _.layout);
ViewLayout_layoutGroup(view, group, _);
});
if (_.modified()) pulse.reflow();
return pulse;
};
function ViewLayout_layoutGroup(view, group, _) {
var items = group.items,
width = Math.max(0, group.width || 0),
height = Math.max(0, group.height || 0),
viewBounds = new Bounds().set(0, 0, width, height),
xBounds = viewBounds.clone(),
yBounds = viewBounds.clone(),
legends = [], title,
mark, orient, b, i, n;
// layout axes, gather legends, collect bounds
for (i=0, n=items.length; i<n; ++i) {
mark = items[i];
switch (mark.role) {
case AxisRole:
b = axis_isYAxis(mark) ? xBounds : yBounds;
b.union(axis_axisLayout(view, mark, width, height));
break;
case TitleRole:
title = mark;
break;
case LegendRole:
legends.push(legend_legendLayout(view, mark));
break;
case FrameRole:
case ScopeRole:
case RowHeader:
case RowFooter:
case RowTitle:
case ColHeader:
case ColFooter:
case ColTitle:
xBounds.union(mark.bounds);
yBounds.union(mark.bounds);
break;
default:
viewBounds.union(mark.bounds);
}
}
// layout legends, adjust viewBounds
if (legends.length) {
// group legends by orient
const l = {};
legends.forEach(item => {
orient = item.orient || Right;
if (orient !== constants_None) (l[orient] || (l[orient] = [])).push(item);
});
// perform grid layout for each orient group
for (let orient in l) {
const g = l[orient];
grid_gridLayout(view, g, legend_legendParams(
g, orient, _.legends, xBounds, yBounds, width, height
));
}
// update view bounds
legends.forEach(item => {
const b = item.bounds;
if (!b.equals(item._bounds)) {
item.bounds = item._bounds;
view.dirty(item); // dirty previous location
item.bounds = b;
view.dirty(item);
}
if (_.autosize && _.autosize.type === Fit) {
// For autosize fit, incorporate the orthogonal dimension only.
// Legends that overrun the chart area will then be clipped;
// otherwise the chart area gets reduced to nothing!
switch(item.orient) {
case Left:
case Right:
viewBounds.add(b.x1, 0).add(b.x2, 0);
break;
case Top:
case Bottom:
viewBounds.add(0, b.y1).add(0, b.y2);
}
} else {
viewBounds.union(b);
}
});
}
// combine bounding boxes
viewBounds.union(xBounds).union(yBounds);
// layout title, adjust bounds
if (title) {
viewBounds.union(title_titleLayout(view, title, width, height, viewBounds));
}
// override aggregated view bounds if content is clipped
if (group.clip) {
viewBounds.set(0, 0, group.width || 0, group.height || 0);
}
// perform size adjustment
ViewLayout_viewSizeLayout(view, group, viewBounds, _);
}
function ViewLayout_viewSizeLayout(view, group, viewBounds, _) {
const auto = _.autosize || {},
type = auto.type;
if (view._autosize < 1 || !type) return;
let viewWidth = view._width,
viewHeight = view._height,
width = Math.max(0, group.width || 0),
left = Math.max(0, Math.ceil(-viewBounds.x1)),
right = Math.max(0, Math.ceil(viewBounds.x2 - width)),
height = Math.max(0, group.height || 0),
top = Math.max(0, Math.ceil(-viewBounds.y1)),
bottom = Math.max(0, Math.ceil(viewBounds.y2 - height));
if (auto.contains === Padding) {
const padding = view.padding();
viewWidth -= padding.left + padding.right;
viewHeight -= padding.top + padding.bottom;
}
if (type === constants_None) {
left = 0;
top = 0;
width = viewWidth;
height = viewHeight;
}
else if (type === Fit) {
width = Math.max(0, viewWidth - left - right);
height = Math.max(0, viewHeight - top - bottom);
}
else if (type === FitX) {
width = Math.max(0, viewWidth - left - right);
viewHeight = height + top + bottom;
}
else if (type === FitY) {
viewWidth = width + left + right;
height = Math.max(0, viewHeight - top - bottom);
}
else if (type === Pad) {
viewWidth = width + left + right;
viewHeight = height + top + bottom;
}
view._resizeView(
viewWidth, viewHeight,
width, height,
[left, top],
auto.resize
);
}
// CONCATENATED MODULE: ./node_modules/vega-view-transforms/index.js
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/bandSpace.js
/* harmony default export */ var bandSpace = (function(count, paddingInner, paddingOuter) {
var space = count - paddingInner + paddingOuter * 2;
return count ? (space > 0 ? space : 1) : 0;
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/types.js
const Identity = 'identity';
const types_Linear = 'linear';
const Log = 'log';
const Pow = 'pow';
const Sqrt = 'sqrt';
const Symlog = 'symlog';
const Time = 'time';
const UTC = 'utc';
const Sequential = 'sequential';
const Diverging = 'diverging';
const types_Quantile = 'quantile';
const Quantize = 'quantize';
const Threshold = 'threshold';
const Ordinal = 'ordinal';
const Point = 'point';
const Band = 'band';
const BinOrdinal = 'bin-ordinal';
// categories
const Continuous = 'continuous';
const Discrete = 'discrete';
const Discretizing = 'discretizing';
const Interpolating = 'interpolating';
const Temporal = 'temporal';
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/invertRange.js
/* harmony default export */ var invertRange = (function(scale) {
return function(_) {
var lo = _[0],
hi = _[1],
t;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
return [
scale.invert(lo),
scale.invert(hi)
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/invertRangeExtent.js
/* harmony default export */ var invertRangeExtent = (function(scale) {
return function(_) {
var range = scale.range(),
lo = _[0],
hi = _[1],
min = -1, max, t, i, n;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
for (i=0, n=range.length; i<n; ++i) {
if (range[i] >= lo && range[i] <= hi) {
if (min < 0) min = i;
max = i;
}
}
if (min < 0) return undefined;
lo = scale.invertExtent(range[min]);
hi = scale.invertExtent(range[max]);
return [
lo[0] === undefined ? lo[1] : lo[0],
hi[1] === undefined ? hi[0] : hi[1]
];
}
});
// CONCATENATED MODULE: ./node_modules/d3-array/src/bisect.js
var bisect_ascendingBisect = bisector(src_ascending);
var bisect_bisectRight = bisect_ascendingBisect.right;
var bisect_bisectLeft = bisect_ascendingBisect.left;
/* harmony default export */ var d3_array_src_bisect = (bisect_bisectRight);
// CONCATENATED MODULE: ./node_modules/d3-scale/src/init.js
function initRange(domain, range) {
switch (arguments.length) {
case 0: break;
case 1: this.range(domain); break;
default: this.range(range).domain(domain); break;
}
return this;
}
function initInterpolator(domain, interpolator) {
switch (arguments.length) {
case 0: break;
case 1: {
if (typeof domain === "function") this.interpolator(domain);
else this.range(domain);
break;
}
default: {
this.domain(domain);
if (typeof interpolator === "function") this.interpolator(interpolator);
else this.range(interpolator);
break;
}
}
return this;
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/ordinal.js
const ordinal_implicit = Symbol("implicit");
function ordinal_ordinal() {
var index = new Map(),
domain = [],
range = [],
unknown = ordinal_implicit;
function scale(d) {
var key = d + "", i = index.get(key);
if (!i) {
if (unknown !== ordinal_implicit) return unknown;
index.set(key, i = domain.push(d));
}
return range[(i - 1) % range.length];
}
scale.domain = function(_) {
if (!arguments.length) return domain.slice();
domain = [], index = new Map();
for (const value of _) {
const key = value + "";
if (index.has(key)) continue;
index.set(key, domain.push(value));
}
return scale;
};
scale.range = function(_) {
return arguments.length ? (range = Array.from(_), scale) : range.slice();
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
scale.copy = function() {
return ordinal_ordinal(domain, range).unknown(unknown);
};
initRange.apply(scale, arguments);
return scale;
}
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/scaleBand.js
function scaleBand_band() {
var scale = ordinal_ordinal().unknown(undefined),
domain = scale.domain,
ordinalRange = scale.range,
range = [0, 1],
step,
bandwidth,
round = false,
paddingInner = 0,
paddingOuter = 0,
align = 0.5;
delete scale.unknown;
function rescale() {
var n = domain().length,
reverse = range[1] < range[0],
start = range[reverse - 0],
stop = range[1 - reverse],
space = bandSpace(n, paddingInner, paddingOuter);
step = (stop - start) / (space || 1);
if (round) {
step = Math.floor(step);
}
start += (stop - start - step * (n - paddingInner)) * align;
bandwidth = step * (1 - paddingInner);
if (round) {
start = Math.round(start);
bandwidth = Math.round(bandwidth);
}
var values = src_range(n).map(function(i) { return start + step * i; });
return ordinalRange(reverse ? values.reverse() : values);
}
scale.domain = function(_) {
if (arguments.length) {
domain(_);
return rescale();
} else {
return domain();
}
};
scale.range = function(_) {
if (arguments.length) {
range = [+_[0], +_[1]];
return rescale();
} else {
return range.slice();
}
};
scale.rangeRound = function(_) {
range = [+_[0], +_[1]];
round = true;
return rescale();
};
scale.bandwidth = function() {
return bandwidth;
};
scale.step = function() {
return step;
};
scale.round = function(_) {
if (arguments.length) {
round = !!_;
return rescale();
} else {
return round;
}
};
scale.padding = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
paddingInner = paddingOuter;
return rescale();
} else {
return paddingInner;
}
};
scale.paddingInner = function(_) {
if (arguments.length) {
paddingInner = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingInner;
}
};
scale.paddingOuter = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingOuter;
}
};
scale.align = function(_) {
if (arguments.length) {
align = Math.max(0, Math.min(1, _));
return rescale();
} else {
return align;
}
};
scale.invertRange = function(_) {
// bail if range has null or undefined values
if (_[0] == null || _[1] == null) return;
var lo = +_[0],
hi = +_[1],
reverse = range[1] < range[0],
values = reverse ? ordinalRange().reverse() : ordinalRange(),
n = values.length - 1, a, b, t;
// bail if either range endpoint is invalid
if (lo !== lo || hi !== hi) return;
// order range inputs, bail if outside of scale range
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
if (hi < values[0] || lo > range[1-reverse]) return;
// binary search to index into scale range
a = Math.max(0, bisect_bisectRight(values, lo) - 1);
b = lo===hi ? a : bisect_bisectRight(values, hi) - 1;
// increment index a if lo is within padding gap
if (lo - values[a] > bandwidth + 1e-10) ++a;
if (reverse) {
// map + swap
t = a;
a = n - b;
b = n - t;
}
return (a > b) ? undefined : domain().slice(a, b+1);
};
scale.invert = function(_) {
var value = scale.invertRange([_, _]);
return value ? value[0] : value;
};
scale.copy = function() {
return scaleBand_band()
.domain(domain())
.range(range)
.round(round)
.paddingInner(paddingInner)
.paddingOuter(paddingOuter)
.align(align);
};
return rescale();
}
function scaleBand_pointish(scale) {
var copy = scale.copy;
scale.padding = scale.paddingOuter;
delete scale.paddingInner;
scale.copy = function() {
return scaleBand_pointish(copy());
};
return scale;
}
function scaleBand_point() {
return scaleBand_pointish(scaleBand_band().paddingInner(1));
}
// EXTERNAL MODULE: ./node_modules/d3-format/src/index.js + 15 modules
var d3_format_src = __webpack_require__(45);
// CONCATENATED MODULE: ./node_modules/d3-scale/src/tickFormat.js
/* harmony default export */ var src_tickFormat = (function(start, stop, count, specifier) {
var step = tickStep(start, stop, count),
precision;
specifier = Object(d3_format_src["formatSpecifier"])(specifier == null ? ",f" : specifier);
switch (specifier.type) {
case "s": {
var value = Math.max(Math.abs(start), Math.abs(stop));
if (specifier.precision == null && !isNaN(precision = Object(d3_format_src["precisionPrefix"])(step, value))) specifier.precision = precision;
return Object(d3_format_src["formatPrefix"])(specifier, value);
}
case "":
case "e":
case "g":
case "p":
case "r": {
if (specifier.precision == null && !isNaN(precision = Object(d3_format_src["precisionRound"])(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
break;
}
case "f":
case "%": {
if (specifier.precision == null && !isNaN(precision = Object(d3_format_src["precisionFixed"])(step))) specifier.precision = precision - (specifier.type === "%") * 2;
break;
}
}
return Object(d3_format_src["format"])(specifier);
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/numbers.js
var numbers_map = Array.prototype.map;
function numbers_numbers(_) {
return numbers_map.call(_, function(x) { return +x; });
}
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/slice.js
var slice = Array.prototype.slice;
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales/scaleBinOrdinal.js
function scaleBinOrdinal_scaleBinOrdinal() {
var domain = [],
range = [];
function scale(x) {
return x == null || x !== x
? undefined
: range[(d3_array_src_bisect(domain, x) - 1) % range.length];
}
scale.domain = function(_) {
if (arguments.length) {
domain = numbers_numbers(_);
return scale;
} else {
return domain.slice();
}
};
scale.range = function(_) {
if (arguments.length) {
range = slice.call(_);
return scale;
} else {
return range.slice();
}
};
scale.tickFormat = function(count, specifier) {
return src_tickFormat(domain[0], Object(vega_util["U" /* peek */])(domain), count == null ? 10 : count, specifier);
};
scale.copy = function() {
return scaleBinOrdinal_scaleBinOrdinal().domain(scale.domain()).range(scale.range());
};
return scale;
}
// CONCATENATED MODULE: ./node_modules/d3-color/src/define.js
/* harmony default export */ var define = (function(constructor, factory, prototype) {
constructor.prototype = factory.prototype = prototype;
prototype.constructor = constructor;
});
function extend(parent, definition) {
var prototype = Object.create(parent.prototype);
for (var key in definition) prototype[key] = definition[key];
return prototype;
}
// CONCATENATED MODULE: ./node_modules/d3-color/src/color.js
function color_Color() {}
var color_darker = 0.7;
var color_brighter = 1 / color_darker;
var color_reI = "\\s*([+-]?\\d+)\\s*",
color_reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
color_reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
color_reHex = /^#([0-9a-f]{3,8})$/,
color_reRgbInteger = new RegExp("^rgb\\(" + [color_reI, color_reI, color_reI] + "\\)$"),
color_reRgbPercent = new RegExp("^rgb\\(" + [color_reP, color_reP, color_reP] + "\\)$"),
color_reRgbaInteger = new RegExp("^rgba\\(" + [color_reI, color_reI, color_reI, color_reN] + "\\)$"),
color_reRgbaPercent = new RegExp("^rgba\\(" + [color_reP, color_reP, color_reP, color_reN] + "\\)$"),
color_reHslPercent = new RegExp("^hsl\\(" + [color_reN, color_reP, color_reP] + "\\)$"),
color_reHslaPercent = new RegExp("^hsla\\(" + [color_reN, color_reP, color_reP, color_reN] + "\\)$");
var color_named = {
aliceblue: 0xf0f8ff,
antiquewhite: 0xfaebd7,
aqua: 0x00ffff,
aquamarine: 0x7fffd4,
azure: 0xf0ffff,
beige: 0xf5f5dc,
bisque: 0xffe4c4,
black: 0x000000,
blanchedalmond: 0xffebcd,
blue: 0x0000ff,
blueviolet: 0x8a2be2,
brown: 0xa52a2a,
burlywood: 0xdeb887,
cadetblue: 0x5f9ea0,
chartreuse: 0x7fff00,
chocolate: 0xd2691e,
coral: 0xff7f50,
cornflowerblue: 0x6495ed,
cornsilk: 0xfff8dc,
crimson: 0xdc143c,
cyan: 0x00ffff,
darkblue: 0x00008b,
darkcyan: 0x008b8b,
darkgoldenrod: 0xb8860b,
darkgray: 0xa9a9a9,
darkgreen: 0x006400,
darkgrey: 0xa9a9a9,
darkkhaki: 0xbdb76b,
darkmagenta: 0x8b008b,
darkolivegreen: 0x556b2f,
darkorange: 0xff8c00,
darkorchid: 0x9932cc,
darkred: 0x8b0000,
darksalmon: 0xe9967a,
darkseagreen: 0x8fbc8f,
darkslateblue: 0x483d8b,
darkslategray: 0x2f4f4f,
darkslategrey: 0x2f4f4f,
darkturquoise: 0x00ced1,
darkviolet: 0x9400d3,
deeppink: 0xff1493,
deepskyblue: 0x00bfff,
dimgray: 0x696969,
dimgrey: 0x696969,
dodgerblue: 0x1e90ff,
firebrick: 0xb22222,
floralwhite: 0xfffaf0,
forestgreen: 0x228b22,
fuchsia: 0xff00ff,
gainsboro: 0xdcdcdc,
ghostwhite: 0xf8f8ff,
gold: 0xffd700,
goldenrod: 0xdaa520,
gray: 0x808080,
green: 0x008000,
greenyellow: 0xadff2f,
grey: 0x808080,
honeydew: 0xf0fff0,
hotpink: 0xff69b4,
indianred: 0xcd5c5c,
indigo: 0x4b0082,
ivory: 0xfffff0,
khaki: 0xf0e68c,
lavender: 0xe6e6fa,
lavenderblush: 0xfff0f5,
lawngreen: 0x7cfc00,
lemonchiffon: 0xfffacd,
lightblue: 0xadd8e6,
lightcoral: 0xf08080,
lightcyan: 0xe0ffff,
lightgoldenrodyellow: 0xfafad2,
lightgray: 0xd3d3d3,
lightgreen: 0x90ee90,
lightgrey: 0xd3d3d3,
lightpink: 0xffb6c1,
lightsalmon: 0xffa07a,
lightseagreen: 0x20b2aa,
lightskyblue: 0x87cefa,
lightslategray: 0x778899,
lightslategrey: 0x778899,
lightsteelblue: 0xb0c4de,
lightyellow: 0xffffe0,
lime: 0x00ff00,
limegreen: 0x32cd32,
linen: 0xfaf0e6,
magenta: 0xff00ff,
maroon: 0x800000,
mediumaquamarine: 0x66cdaa,
mediumblue: 0x0000cd,
mediumorchid: 0xba55d3,
mediumpurple: 0x9370db,
mediumseagreen: 0x3cb371,
mediumslateblue: 0x7b68ee,
mediumspringgreen: 0x00fa9a,
mediumturquoise: 0x48d1cc,
mediumvioletred: 0xc71585,
midnightblue: 0x191970,
mintcream: 0xf5fffa,
mistyrose: 0xffe4e1,
moccasin: 0xffe4b5,
navajowhite: 0xffdead,
navy: 0x000080,
oldlace: 0xfdf5e6,
olive: 0x808000,
olivedrab: 0x6b8e23,
orange: 0xffa500,
orangered: 0xff4500,
orchid: 0xda70d6,
palegoldenrod: 0xeee8aa,
palegreen: 0x98fb98,
paleturquoise: 0xafeeee,
palevioletred: 0xdb7093,
papayawhip: 0xffefd5,
peachpuff: 0xffdab9,
peru: 0xcd853f,
pink: 0xffc0cb,
plum: 0xdda0dd,
powderblue: 0xb0e0e6,
purple: 0x800080,
rebeccapurple: 0x663399,
red: 0xff0000,
rosybrown: 0xbc8f8f,
royalblue: 0x4169e1,
saddlebrown: 0x8b4513,
salmon: 0xfa8072,
sandybrown: 0xf4a460,
seagreen: 0x2e8b57,
seashell: 0xfff5ee,
sienna: 0xa0522d,
silver: 0xc0c0c0,
skyblue: 0x87ceeb,
slateblue: 0x6a5acd,
slategray: 0x708090,
slategrey: 0x708090,
snow: 0xfffafa,
springgreen: 0x00ff7f,
steelblue: 0x4682b4,
tan: 0xd2b48c,
teal: 0x008080,
thistle: 0xd8bfd8,
tomato: 0xff6347,
turquoise: 0x40e0d0,
violet: 0xee82ee,
wheat: 0xf5deb3,
white: 0xffffff,
whitesmoke: 0xf5f5f5,
yellow: 0xffff00,
yellowgreen: 0x9acd32
};
define(color_Color, color_color, {
copy: function(channels) {
return Object.assign(new this.constructor, this, channels);
},
displayable: function() {
return this.rgb().displayable();
},
hex: color_color_formatHex, // Deprecated! Use color.formatHex.
formatHex: color_color_formatHex,
formatHsl: color_color_formatHsl,
formatRgb: color_color_formatRgb,
toString: color_color_formatRgb
});
function color_color_formatHex() {
return this.rgb().formatHex();
}
function color_color_formatHsl() {
return color_hslConvert(this).formatHsl();
}
function color_color_formatRgb() {
return this.rgb().formatRgb();
}
function color_color(format) {
var m, l;
format = (format + "").trim().toLowerCase();
return (m = color_reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? color_rgbn(m) // #ff0000
: l === 3 ? new color_Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
: l === 8 ? new color_Rgb(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
: l === 4 ? new color_Rgb((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
: null) // invalid hex
: (m = color_reRgbInteger.exec(format)) ? new color_Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
: (m = color_reRgbPercent.exec(format)) ? new color_Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
: (m = color_reRgbaInteger.exec(format)) ? color_rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
: (m = color_reRgbaPercent.exec(format)) ? color_rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
: (m = color_reHslPercent.exec(format)) ? color_hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
: (m = color_reHslaPercent.exec(format)) ? color_hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
: color_named.hasOwnProperty(format) ? color_rgbn(color_named[format]) // eslint-disable-line no-prototype-builtins
: format === "transparent" ? new color_Rgb(NaN, NaN, NaN, 0)
: null;
}
function color_rgbn(n) {
return new color_Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}
function color_rgba(r, g, b, a) {
if (a <= 0) r = g = b = NaN;
return new color_Rgb(r, g, b, a);
}
function color_rgbConvert(o) {
if (!(o instanceof color_Color)) o = color_color(o);
if (!o) return new color_Rgb;
o = o.rgb();
return new color_Rgb(o.r, o.g, o.b, o.opacity);
}
function color_rgb(r, g, b, opacity) {
return arguments.length === 1 ? color_rgbConvert(r) : new color_Rgb(r, g, b, opacity == null ? 1 : opacity);
}
function color_Rgb(r, g, b, opacity) {
this.r = +r;
this.g = +g;
this.b = +b;
this.opacity = +opacity;
}
define(color_Rgb, color_rgb, extend(color_Color, {
brighter: function(k) {
k = k == null ? color_brighter : Math.pow(color_brighter, k);
return new color_Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
darker: function(k) {
k = k == null ? color_darker : Math.pow(color_darker, k);
return new color_Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
rgb: function() {
return this;
},
displayable: function() {
return (-0.5 <= this.r && this.r < 255.5)
&& (-0.5 <= this.g && this.g < 255.5)
&& (-0.5 <= this.b && this.b < 255.5)
&& (0 <= this.opacity && this.opacity <= 1);
},
hex: color_rgb_formatHex, // Deprecated! Use color.formatHex.
formatHex: color_rgb_formatHex,
formatRgb: color_rgb_formatRgb,
toString: color_rgb_formatRgb
}));
function color_rgb_formatHex() {
return "#" + color_hex(this.r) + color_hex(this.g) + color_hex(this.b);
}
function color_rgb_formatRgb() {
var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
return (a === 1 ? "rgb(" : "rgba(")
+ Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
+ Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
+ Math.max(0, Math.min(255, Math.round(this.b) || 0))
+ (a === 1 ? ")" : ", " + a + ")");
}
function color_hex(value) {
value = Math.max(0, Math.min(255, Math.round(value) || 0));
return (value < 16 ? "0" : "") + value.toString(16);
}
function color_hsla(h, s, l, a) {
if (a <= 0) h = s = l = NaN;
else if (l <= 0 || l >= 1) h = s = NaN;
else if (s <= 0) h = NaN;
return new color_Hsl(h, s, l, a);
}
function color_hslConvert(o) {
if (o instanceof color_Hsl) return new color_Hsl(o.h, o.s, o.l, o.opacity);
if (!(o instanceof color_Color)) o = color_color(o);
if (!o) return new color_Hsl;
if (o instanceof color_Hsl) return o;
o = o.rgb();
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
min = Math.min(r, g, b),
max = Math.max(r, g, b),
h = NaN,
s = max - min,
l = (max + min) / 2;
if (s) {
if (r === max) h = (g - b) / s + (g < b) * 6;
else if (g === max) h = (b - r) / s + 2;
else h = (r - g) / s + 4;
s /= l < 0.5 ? max + min : 2 - max - min;
h *= 60;
} else {
s = l > 0 && l < 1 ? 0 : h;
}
return new color_Hsl(h, s, l, o.opacity);
}
function color_hsl(h, s, l, opacity) {
return arguments.length === 1 ? color_hslConvert(h) : new color_Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function color_Hsl(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(color_Hsl, color_hsl, extend(color_Color, {
brighter: function(k) {
k = k == null ? color_brighter : Math.pow(color_brighter, k);
return new color_Hsl(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
k = k == null ? color_darker : Math.pow(color_darker, k);
return new color_Hsl(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = this.h % 360 + (this.h < 0) * 360,
s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
l = this.l,
m2 = l + (l < 0.5 ? l : 1 - l) * s,
m1 = 2 * l - m2;
return new color_Rgb(
color_hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
color_hsl2rgb(h, m1, m2),
color_hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
this.opacity
);
},
displayable: function() {
return (0 <= this.s && this.s <= 1 || isNaN(this.s))
&& (0 <= this.l && this.l <= 1)
&& (0 <= this.opacity && this.opacity <= 1);
},
formatHsl: function() {
var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
return (a === 1 ? "hsl(" : "hsla(")
+ (this.h || 0) + ", "
+ (this.s || 0) * 100 + "%, "
+ (this.l || 0) * 100 + "%"
+ (a === 1 ? ")" : ", " + a + ")");
}
}));
/* From FvD 13.37, CSS Color Module Level 3 */
function color_hsl2rgb(h, m1, m2) {
return (h < 60 ? m1 + (m2 - m1) * h / 60
: h < 180 ? m2
: h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
: m1) * 255;
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/basis.js
function basis_basis(t1, v0, v1, v2, v3) {
var t2 = t1 * t1, t3 = t2 * t1;
return ((1 - 3 * t1 + 3 * t2 - t3) * v0
+ (4 - 6 * t2 + 3 * t3) * v1
+ (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
+ t3 * v3) / 6;
}
/* harmony default export */ var src_basis = (function(values) {
var n = values.length - 1;
return function(t) {
var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),
v1 = values[i],
v2 = values[i + 1],
v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,
v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
return basis_basis((t - i / n) * n, v0, v1, v2, v3);
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/basisClosed.js
/* harmony default export */ var src_basisClosed = (function(values) {
var n = values.length;
return function(t) {
var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),
v0 = values[(i + n - 1) % n],
v1 = values[i % n],
v2 = values[(i + 1) % n],
v3 = values[(i + 2) % n];
return basis_basis((t - i / n) * n, v0, v1, v2, v3);
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/constant.js
/* harmony default export */ var d3_interpolate_src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/color.js
function color_linear(a, d) {
return function(t) {
return a + t * d;
};
}
function color_exponential(a, b, y) {
return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
return Math.pow(a + t * b, y);
};
}
function color_hue(a, b) {
var d = b - a;
return d ? color_linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : d3_interpolate_src_constant(isNaN(a) ? b : a);
}
function color_gamma(y) {
return (y = +y) === 1 ? color_nogamma : function(a, b) {
return b - a ? color_exponential(a, b, y) : d3_interpolate_src_constant(isNaN(a) ? b : a);
};
}
function color_nogamma(a, b) {
var d = b - a;
return d ? color_linear(a, d) : d3_interpolate_src_constant(isNaN(a) ? b : a);
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/rgb.js
/* harmony default export */ var src_rgb = ((function rgbGamma(y) {
var color = color_gamma(y);
function rgb(start, end) {
var r = color((start = color_rgb(start)).r, (end = color_rgb(end)).r),
g = color(start.g, end.g),
b = color(start.b, end.b),
opacity = color_nogamma(start.opacity, end.opacity);
return function(t) {
start.r = r(t);
start.g = g(t);
start.b = b(t);
start.opacity = opacity(t);
return start + "";
};
}
rgb.gamma = rgbGamma;
return rgb;
})(1));
function rgb_rgbSpline(spline) {
return function(colors) {
var n = colors.length,
r = new Array(n),
g = new Array(n),
b = new Array(n),
i, color;
for (i = 0; i < n; ++i) {
color = color_rgb(colors[i]);
r[i] = color.r || 0;
g[i] = color.g || 0;
b[i] = color.b || 0;
}
r = spline(r);
g = spline(g);
b = spline(b);
color.opacity = 1;
return function(t) {
color.r = r(t);
color.g = g(t);
color.b = b(t);
return color + "";
};
};
}
var rgb_rgbBasis = rgb_rgbSpline(src_basis);
var rgb_rgbBasisClosed = rgb_rgbSpline(src_basisClosed);
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/numberArray.js
/* harmony default export */ var numberArray = (function(a, b) {
if (!b) b = [];
var n = a ? Math.min(b.length, a.length) : 0,
c = b.slice(),
i;
return function(t) {
for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
return c;
};
});
function isNumberArray(x) {
return ArrayBuffer.isView(x) && !(x instanceof DataView);
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/array.js
/* harmony default export */ var src_array = (function(a, b) {
return (isNumberArray(b) ? numberArray : array_genericArray)(a, b);
});
function array_genericArray(a, b) {
var nb = b ? b.length : 0,
na = a ? Math.min(nb, a.length) : 0,
x = new Array(na),
c = new Array(nb),
i;
for (i = 0; i < na; ++i) x[i] = src_value(a[i], b[i]);
for (; i < nb; ++i) c[i] = b[i];
return function(t) {
for (i = 0; i < na; ++i) c[i] = x[i](t);
return c;
};
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/date.js
/* harmony default export */ var src_date = (function(a, b) {
var d = new Date;
return a = +a, b = +b, function(t) {
return d.setTime(a * (1 - t) + b * t), d;
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/number.js
/* harmony default export */ var d3_interpolate_src_number = (function(a, b) {
return a = +a, b = +b, function(t) {
return a * (1 - t) + b * t;
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/object.js
/* harmony default export */ var src_object = (function(a, b) {
var i = {},
c = {},
k;
if (a === null || typeof a !== "object") a = {};
if (b === null || typeof b !== "object") b = {};
for (k in b) {
if (k in a) {
i[k] = src_value(a[k], b[k]);
} else {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/string.js
var string_reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,
string_reB = new RegExp(string_reA.source, "g");
function string_zero(b) {
return function() {
return b;
};
}
function string_one(b) {
return function(t) {
return b(t) + "";
};
}
/* harmony default export */ var src_string = (function(a, b) {
var bi = string_reA.lastIndex = string_reB.lastIndex = 0, // scan index for next number in b
am, // current match in a
bm, // current match in b
bs, // string preceding current number in b, if any
i = -1, // index in s
s = [], // string constants and placeholders
q = []; // number interpolators
// Coerce inputs to strings.
a = a + "", b = b + "";
// Interpolate pairs of numbers in a & b.
while ((am = string_reA.exec(a))
&& (bm = string_reB.exec(b))) {
if ((bs = bm.index) > bi) { // a string precedes the next number in b
bs = b.slice(bi, bs);
if (s[i]) s[i] += bs; // coalesce with previous string
else s[++i] = bs;
}
if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match
if (s[i]) s[i] += bm; // coalesce with previous string
else s[++i] = bm;
} else { // interpolate non-matching numbers
s[++i] = null;
q.push({i: i, x: d3_interpolate_src_number(am, bm)});
}
bi = string_reB.lastIndex;
}
// Add remains of b.
if (bi < b.length) {
bs = b.slice(bi);
if (s[i]) s[i] += bs; // coalesce with previous string
else s[++i] = bs;
}
// Special optimization for only a single match.
// Otherwise, interpolate each of the numbers and rejoin the string.
return s.length < 2 ? (q[0]
? string_one(q[0].x)
: string_zero(b))
: (b = q.length, function(t) {
for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
return s.join("");
});
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/value.js
/* harmony default export */ var src_value = (function(a, b) {
var t = typeof b, c;
return b == null || t === "boolean" ? d3_interpolate_src_constant(b)
: (t === "number" ? d3_interpolate_src_number
: t === "string" ? ((c = color_color(b)) ? (b = c, src_rgb) : src_string)
: b instanceof color_color ? src_rgb
: b instanceof Date ? src_date
: isNumberArray(b) ? numberArray
: Array.isArray(b) ? array_genericArray
: typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? src_object
: d3_interpolate_src_number)(a, b);
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/round.js
/* harmony default export */ var src_round = (function(a, b) {
return a = +a, b = +b, function(t) {
return Math.round(a * (1 - t) + b * t);
};
});
// CONCATENATED MODULE: ./node_modules/d3-scale/src/constant.js
/* harmony default export */ var d3_scale_src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-scale/src/number.js
/* harmony default export */ var d3_scale_src_number = (function(x) {
return +x;
});
// CONCATENATED MODULE: ./node_modules/d3-scale/src/continuous.js
var continuous_unit = [0, 1];
function continuous_identity(x) {
return x;
}
function continuous_normalize(a, b) {
return (b -= (a = +a))
? function(x) { return (x - a) / b; }
: d3_scale_src_constant(isNaN(b) ? NaN : 0.5);
}
function continuous_clamper(a, b) {
var t;
if (a > b) t = a, a = b, b = t;
return function(x) { return Math.max(a, Math.min(b, x)); };
}
// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].
function continuous_bimap(domain, range, interpolate) {
var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
if (d1 < d0) d0 = continuous_normalize(d1, d0), r0 = interpolate(r1, r0);
else d0 = continuous_normalize(d0, d1), r0 = interpolate(r0, r1);
return function(x) { return r0(d0(x)); };
}
function continuous_polymap(domain, range, interpolate) {
var j = Math.min(domain.length, range.length) - 1,
d = new Array(j),
r = new Array(j),
i = -1;
// Reverse descending domains.
if (domain[j] < domain[0]) {
domain = domain.slice().reverse();
range = range.slice().reverse();
}
while (++i < j) {
d[i] = continuous_normalize(domain[i], domain[i + 1]);
r[i] = interpolate(range[i], range[i + 1]);
}
return function(x) {
var i = d3_array_src_bisect(domain, x, 1, j) - 1;
return r[i](d[i](x));
};
}
function continuous_copy(source, target) {
return target
.domain(source.domain())
.range(source.range())
.interpolate(source.interpolate())
.clamp(source.clamp())
.unknown(source.unknown());
}
function continuous_transformer() {
var domain = continuous_unit,
range = continuous_unit,
interpolate = src_value,
transform,
untransform,
unknown,
clamp = continuous_identity,
piecewise,
output,
input;
function rescale() {
var n = Math.min(domain.length, range.length);
if (clamp !== continuous_identity) clamp = continuous_clamper(domain[0], domain[n - 1]);
piecewise = n > 2 ? continuous_polymap : continuous_bimap;
output = input = null;
return scale;
}
function scale(x) {
return isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));
}
scale.invert = function(y) {
return clamp(untransform((input || (input = piecewise(range, domain.map(transform), d3_interpolate_src_number)))(y)));
};
scale.domain = function(_) {
return arguments.length ? (domain = Array.from(_, d3_scale_src_number), rescale()) : domain.slice();
};
scale.range = function(_) {
return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
};
scale.rangeRound = function(_) {
return range = Array.from(_), interpolate = src_round, rescale();
};
scale.clamp = function(_) {
return arguments.length ? (clamp = _ ? true : continuous_identity, rescale()) : clamp !== continuous_identity;
};
scale.interpolate = function(_) {
return arguments.length ? (interpolate = _, rescale()) : interpolate;
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
return function(t, u) {
transform = t, untransform = u;
return rescale();
};
}
function continuous_continuous() {
return continuous_transformer()(continuous_identity, continuous_identity);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/linear.js
function linear_linearish(scale) {
var domain = scale.domain;
scale.ticks = function(count) {
var d = domain();
return src_ticks(d[0], d[d.length - 1], count == null ? 10 : count);
};
scale.tickFormat = function(count, specifier) {
var d = domain();
return src_tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
};
scale.nice = function(count) {
if (count == null) count = 10;
var d = domain(),
i0 = 0,
i1 = d.length - 1,
start = d[i0],
stop = d[i1],
step;
if (stop < start) {
step = start, start = stop, stop = step;
step = i0, i0 = i1, i1 = step;
}
step = tickIncrement(start, stop, count);
if (step > 0) {
start = Math.floor(start / step) * step;
stop = Math.ceil(stop / step) * step;
step = tickIncrement(start, stop, count);
} else if (step < 0) {
start = Math.ceil(start * step) / step;
stop = Math.floor(stop * step) / step;
step = tickIncrement(start, stop, count);
}
if (step > 0) {
d[i0] = Math.floor(start / step) * step;
d[i1] = Math.ceil(stop / step) * step;
domain(d);
} else if (step < 0) {
d[i0] = Math.ceil(start * step) / step;
d[i1] = Math.floor(stop * step) / step;
domain(d);
}
return scale;
};
return scale;
}
function linear_linear() {
var scale = continuous_continuous();
scale.copy = function() {
return continuous_copy(scale, linear_linear());
};
initRange.apply(scale, arguments);
return linear_linearish(scale);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/identity.js
function identity_identity(domain) {
var unknown;
function scale(x) {
return isNaN(x = +x) ? unknown : x;
}
scale.invert = scale;
scale.domain = scale.range = function(_) {
return arguments.length ? (domain = Array.from(_, d3_scale_src_number), scale) : domain.slice();
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
scale.copy = function() {
return identity_identity(domain).unknown(unknown);
};
domain = arguments.length ? Array.from(domain, d3_scale_src_number) : [0, 1];
return linear_linearish(scale);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/nice.js
/* harmony default export */ var src_nice = (function(domain, interval) {
domain = domain.slice();
var i0 = 0,
i1 = domain.length - 1,
x0 = domain[i0],
x1 = domain[i1],
t;
if (x1 < x0) {
t = i0, i0 = i1, i1 = t;
t = x0, x0 = x1, x1 = t;
}
domain[i0] = interval.floor(x0);
domain[i1] = interval.ceil(x1);
return domain;
});
// CONCATENATED MODULE: ./node_modules/d3-scale/src/log.js
function log_transformLog(x) {
return Math.log(x);
}
function log_transformExp(x) {
return Math.exp(x);
}
function log_transformLogn(x) {
return -Math.log(-x);
}
function log_transformExpn(x) {
return -Math.exp(-x);
}
function log_pow10(x) {
return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x;
}
function log_powp(base) {
return base === 10 ? log_pow10
: base === Math.E ? Math.exp
: function(x) { return Math.pow(base, x); };
}
function log_logp(base) {
return base === Math.E ? Math.log
: base === 10 && Math.log10
|| base === 2 && Math.log2
|| (base = Math.log(base), function(x) { return Math.log(x) / base; });
}
function log_reflect(f) {
return function(x) {
return -f(-x);
};
}
function log_loggish(transform) {
var scale = transform(log_transformLog, log_transformExp),
domain = scale.domain,
base = 10,
logs,
pows;
function rescale() {
logs = log_logp(base), pows = log_powp(base);
if (domain()[0] < 0) {
logs = log_reflect(logs), pows = log_reflect(pows);
transform(log_transformLogn, log_transformExpn);
} else {
transform(log_transformLog, log_transformExp);
}
return scale;
}
scale.base = function(_) {
return arguments.length ? (base = +_, rescale()) : base;
};
scale.domain = function(_) {
return arguments.length ? (domain(_), rescale()) : domain();
};
scale.ticks = function(count) {
var d = domain(),
u = d[0],
v = d[d.length - 1],
r;
if (r = v < u) i = u, u = v, v = i;
var i = logs(u),
j = logs(v),
p,
k,
t,
n = count == null ? 10 : +count,
z = [];
if (!(base % 1) && j - i < n) {
i = Math.floor(i), j = Math.ceil(j);
if (u > 0) for (; i <= j; ++i) {
for (k = 1, p = pows(i); k < base; ++k) {
t = p * k;
if (t < u) continue;
if (t > v) break;
z.push(t);
}
} else for (; i <= j; ++i) {
for (k = base - 1, p = pows(i); k >= 1; --k) {
t = p * k;
if (t < u) continue;
if (t > v) break;
z.push(t);
}
}
if (z.length * 2 < n) z = src_ticks(u, v, n);
} else {
z = src_ticks(i, j, Math.min(j - i, n)).map(pows);
}
return r ? z.reverse() : z;
};
scale.tickFormat = function(count, specifier) {
if (specifier == null) specifier = base === 10 ? ".0e" : ",";
if (typeof specifier !== "function") specifier = Object(d3_format_src["format"])(specifier);
if (count === Infinity) return specifier;
if (count == null) count = 10;
var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?
return function(d) {
var i = d / pows(Math.round(logs(d)));
if (i * base < base - 0.5) i *= base;
return i <= k ? specifier(d) : "";
};
};
scale.nice = function() {
return domain(src_nice(domain(), {
floor: function(x) { return pows(Math.floor(logs(x))); },
ceil: function(x) { return pows(Math.ceil(logs(x))); }
}));
};
return scale;
}
function log_log() {
var scale = log_loggish(continuous_transformer()).domain([1, 10]);
scale.copy = function() {
return continuous_copy(scale, log_log()).base(scale.base());
};
initRange.apply(scale, arguments);
return scale;
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/pow.js
function pow_transformPow(exponent) {
return function(x) {
return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
};
}
function pow_transformSqrt(x) {
return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);
}
function pow_transformSquare(x) {
return x < 0 ? -x * x : x * x;
}
function pow_powish(transform) {
var scale = transform(continuous_identity, continuous_identity),
exponent = 1;
function rescale() {
return exponent === 1 ? transform(continuous_identity, continuous_identity)
: exponent === 0.5 ? transform(pow_transformSqrt, pow_transformSquare)
: transform(pow_transformPow(exponent), pow_transformPow(1 / exponent));
}
scale.exponent = function(_) {
return arguments.length ? (exponent = +_, rescale()) : exponent;
};
return linear_linearish(scale);
}
function pow_pow() {
var scale = pow_powish(continuous_transformer());
scale.copy = function() {
return continuous_copy(scale, pow_pow()).exponent(scale.exponent());
};
initRange.apply(scale, arguments);
return scale;
}
function pow_sqrt() {
return pow_pow.apply(null, arguments).exponent(0.5);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/symlog.js
function symlog_transformSymlog(c) {
return function(x) {
return Math.sign(x) * Math.log1p(Math.abs(x / c));
};
}
function symlog_transformSymexp(c) {
return function(x) {
return Math.sign(x) * Math.expm1(Math.abs(x)) * c;
};
}
function symlog_symlogish(transform) {
var c = 1, scale = transform(symlog_transformSymlog(c), symlog_transformSymexp(c));
scale.constant = function(_) {
return arguments.length ? transform(symlog_transformSymlog(c = +_), symlog_transformSymexp(c)) : c;
};
return linear_linearish(scale);
}
function symlog_symlog() {
var scale = symlog_symlogish(continuous_transformer());
scale.copy = function() {
return continuous_copy(scale, symlog_symlog()).constant(scale.constant());
};
return initRange.apply(scale, arguments);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/time.js
var time_durationSecond = 1000,
time_durationMinute = time_durationSecond * 60,
time_durationHour = time_durationMinute * 60,
time_durationDay = time_durationHour * 24,
time_durationWeek = time_durationDay * 7,
time_durationMonth = time_durationDay * 30,
time_durationYear = time_durationDay * 365;
function time_date(t) {
return new Date(t);
}
function time_number(t) {
return t instanceof Date ? +t : +new Date(+t);
}
function time_calendar(year, month, week, day, hour, minute, second, millisecond, format) {
var scale = continuous_continuous(),
invert = scale.invert,
domain = scale.domain;
var formatMillisecond = format(".%L"),
formatSecond = format(":%S"),
formatMinute = format("%I:%M"),
formatHour = format("%I %p"),
formatDay = format("%a %d"),
formatWeek = format("%b %d"),
formatMonth = format("%B"),
formatYear = format("%Y");
var tickIntervals = [
[second, 1, time_durationSecond],
[second, 5, 5 * time_durationSecond],
[second, 15, 15 * time_durationSecond],
[second, 30, 30 * time_durationSecond],
[minute, 1, time_durationMinute],
[minute, 5, 5 * time_durationMinute],
[minute, 15, 15 * time_durationMinute],
[minute, 30, 30 * time_durationMinute],
[ hour, 1, time_durationHour ],
[ hour, 3, 3 * time_durationHour ],
[ hour, 6, 6 * time_durationHour ],
[ hour, 12, 12 * time_durationHour ],
[ day, 1, time_durationDay ],
[ day, 2, 2 * time_durationDay ],
[ week, 1, time_durationWeek ],
[ month, 1, time_durationMonth ],
[ month, 3, 3 * time_durationMonth ],
[ year, 1, time_durationYear ]
];
function tickFormat(date) {
return (second(date) < date ? formatMillisecond
: minute(date) < date ? formatSecond
: hour(date) < date ? formatMinute
: day(date) < date ? formatHour
: month(date) < date ? (week(date) < date ? formatDay : formatWeek)
: year(date) < date ? formatMonth
: formatYear)(date);
}
function tickInterval(interval, start, stop) {
if (interval == null) interval = 10;
// If a desired tick count is specified, pick a reasonable tick interval
// based on the extent of the domain and a rough estimate of tick size.
// Otherwise, assume interval is already a time interval and use it.
if (typeof interval === "number") {
var target = Math.abs(stop - start) / interval,
i = bisector(function(i) { return i[2]; }).right(tickIntervals, target),
step;
if (i === tickIntervals.length) {
step = tickStep(start / time_durationYear, stop / time_durationYear, interval);
interval = year;
} else if (i) {
i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
step = i[1];
interval = i[0];
} else {
step = Math.max(tickStep(start, stop, interval), 1);
interval = millisecond;
}
return interval.every(step);
}
return interval;
}
scale.invert = function(y) {
return new Date(invert(y));
};
scale.domain = function(_) {
return arguments.length ? domain(Array.from(_, time_number)) : domain().map(time_date);
};
scale.ticks = function(interval) {
var d = domain(),
t0 = d[0],
t1 = d[d.length - 1],
r = t1 < t0,
t;
if (r) t = t0, t0 = t1, t1 = t;
t = tickInterval(interval, t0, t1);
t = t ? t.range(t0, t1 + 1) : []; // inclusive stop
return r ? t.reverse() : t;
};
scale.tickFormat = function(count, specifier) {
return specifier == null ? tickFormat : format(specifier);
};
scale.nice = function(interval) {
var d = domain();
return (interval = tickInterval(interval, d[0], d[d.length - 1]))
? domain(src_nice(d, interval))
: scale;
};
scale.copy = function() {
return continuous_copy(scale, time_calendar(year, month, week, day, hour, minute, second, millisecond, format));
};
return scale;
}
/* harmony default export */ var src_time = (function() {
return initRange.apply(time_calendar(src_year, src_month, week_sunday, src_day, src_hour, src_minute, src_second, src_millisecond, defaultLocale_timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments);
});
// CONCATENATED MODULE: ./node_modules/d3-scale/src/utcTime.js
/* harmony default export */ var utcTime = (function() {
return initRange.apply(time_calendar(src_utcYear, src_utcMonth, utcWeek_utcSunday, src_utcDay, src_utcHour, src_utcMinute, src_second, src_millisecond, defaultLocale_utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]), arguments);
});
// CONCATENATED MODULE: ./node_modules/d3-scale/src/sequential.js
function sequential_transformer() {
var x0 = 0,
x1 = 1,
t0,
t1,
k10,
transform,
interpolator = continuous_identity,
clamp = false,
unknown;
function scale(x) {
return isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));
}
scale.domain = function(_) {
return arguments.length ? ([x0, x1] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];
};
scale.clamp = function(_) {
return arguments.length ? (clamp = !!_, scale) : clamp;
};
scale.interpolator = function(_) {
return arguments.length ? (interpolator = _, scale) : interpolator;
};
function range(interpolate) {
return function(_) {
var r0, r1;
return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [interpolator(0), interpolator(1)];
};
}
scale.range = range(src_value);
scale.rangeRound = range(src_round);
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
return function(t) {
transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);
return scale;
};
}
function sequential_copy(source, target) {
return target
.domain(source.domain())
.interpolator(source.interpolator())
.clamp(source.clamp())
.unknown(source.unknown());
}
function sequential_sequential() {
var scale = linear_linearish(sequential_transformer()(continuous_identity));
scale.copy = function() {
return sequential_copy(scale, sequential_sequential());
};
return initInterpolator.apply(scale, arguments);
}
function sequential_sequentialLog() {
var scale = log_loggish(sequential_transformer()).domain([1, 10]);
scale.copy = function() {
return sequential_copy(scale, sequential_sequentialLog()).base(scale.base());
};
return initInterpolator.apply(scale, arguments);
}
function sequential_sequentialSymlog() {
var scale = symlog_symlogish(sequential_transformer());
scale.copy = function() {
return sequential_copy(scale, sequential_sequentialSymlog()).constant(scale.constant());
};
return initInterpolator.apply(scale, arguments);
}
function sequential_sequentialPow() {
var scale = pow_powish(sequential_transformer());
scale.copy = function() {
return sequential_copy(scale, sequential_sequentialPow()).exponent(scale.exponent());
};
return initInterpolator.apply(scale, arguments);
}
function sequential_sequentialSqrt() {
return sequential_sequentialPow.apply(null, arguments).exponent(0.5);
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/piecewise.js
function piecewise_piecewise(interpolate, values) {
var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);
while (i < n) I[i] = interpolate(v, v = values[++i]);
return function(t) {
var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
return I[i](t - i);
};
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/diverging.js
function diverging_transformer() {
var x0 = 0,
x1 = 0.5,
x2 = 1,
s = 1,
t0,
t1,
t2,
k10,
k21,
interpolator = continuous_identity,
transform,
clamp = false,
unknown;
function scale(x) {
return isNaN(x = +x) ? unknown : (x = 0.5 + ((x = +transform(x)) - t1) * (s * x < s * t1 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x)) : x));
}
scale.domain = function(_) {
return arguments.length ? ([x0, x1, x2] = _, t0 = transform(x0 = +x0), t1 = transform(x1 = +x1), t2 = transform(x2 = +x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1, scale) : [x0, x1, x2];
};
scale.clamp = function(_) {
return arguments.length ? (clamp = !!_, scale) : clamp;
};
scale.interpolator = function(_) {
return arguments.length ? (interpolator = _, scale) : interpolator;
};
function range(interpolate) {
return function(_) {
var r0, r1, r2;
return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise_piecewise(interpolate, [r0, r1, r2]), scale) : [interpolator(0), interpolator(0.5), interpolator(1)];
};
}
scale.range = range(src_value);
scale.rangeRound = range(src_round);
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
return function(t) {
transform = t, t0 = t(x0), t1 = t(x1), t2 = t(x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1;
return scale;
};
}
function diverging_diverging() {
var scale = linear_linearish(diverging_transformer()(continuous_identity));
scale.copy = function() {
return sequential_copy(scale, diverging_diverging());
};
return initInterpolator.apply(scale, arguments);
}
function diverging_divergingLog() {
var scale = log_loggish(diverging_transformer()).domain([0.1, 1, 10]);
scale.copy = function() {
return sequential_copy(scale, diverging_divergingLog()).base(scale.base());
};
return initInterpolator.apply(scale, arguments);
}
function diverging_divergingSymlog() {
var scale = symlog_symlogish(diverging_transformer());
scale.copy = function() {
return sequential_copy(scale, diverging_divergingSymlog()).constant(scale.constant());
};
return initInterpolator.apply(scale, arguments);
}
function diverging_divergingPow() {
var scale = pow_powish(diverging_transformer());
scale.copy = function() {
return sequential_copy(scale, diverging_divergingPow()).exponent(scale.exponent());
};
return initInterpolator.apply(scale, arguments);
}
function diverging_divergingSqrt() {
return diverging_divergingPow.apply(null, arguments).exponent(0.5);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/quantile.js
function src_quantile_quantile() {
var domain = [],
range = [],
thresholds = [],
unknown;
function rescale() {
var i = 0, n = Math.max(1, range.length);
thresholds = new Array(n - 1);
while (++i < n) thresholds[i - 1] = quantile_quantile(domain, i / n);
return scale;
}
function scale(x) {
return isNaN(x = +x) ? unknown : range[d3_array_src_bisect(thresholds, x)];
}
scale.invertExtent = function(y) {
var i = range.indexOf(y);
return i < 0 ? [NaN, NaN] : [
i > 0 ? thresholds[i - 1] : domain[0],
i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
];
};
scale.domain = function(_) {
if (!arguments.length) return domain.slice();
domain = [];
for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);
domain.sort(src_ascending);
return rescale();
};
scale.range = function(_) {
return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
scale.quantiles = function() {
return thresholds.slice();
};
scale.copy = function() {
return src_quantile_quantile()
.domain(domain)
.range(range)
.unknown(unknown);
};
return initRange.apply(scale, arguments);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/quantize.js
function quantize_quantize() {
var x0 = 0,
x1 = 1,
n = 1,
domain = [0.5],
range = [0, 1],
unknown;
function scale(x) {
return x <= x ? range[d3_array_src_bisect(domain, x, 0, n)] : unknown;
}
function rescale() {
var i = -1;
domain = new Array(n);
while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);
return scale;
}
scale.domain = function(_) {
return arguments.length ? ([x0, x1] = _, x0 = +x0, x1 = +x1, rescale()) : [x0, x1];
};
scale.range = function(_) {
return arguments.length ? (n = (range = Array.from(_)).length - 1, rescale()) : range.slice();
};
scale.invertExtent = function(y) {
var i = range.indexOf(y);
return i < 0 ? [NaN, NaN]
: i < 1 ? [x0, domain[0]]
: i >= n ? [domain[n - 1], x1]
: [domain[i - 1], domain[i]];
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : scale;
};
scale.thresholds = function() {
return domain.slice();
};
scale.copy = function() {
return quantize_quantize()
.domain([x0, x1])
.range(range)
.unknown(unknown);
};
return initRange.apply(linear_linearish(scale), arguments);
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/threshold.js
function threshold_threshold() {
var domain = [0.5],
range = [0, 1],
unknown,
n = 1;
function scale(x) {
return x <= x ? range[d3_array_src_bisect(domain, x, 0, n)] : unknown;
}
scale.domain = function(_) {
return arguments.length ? (domain = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();
};
scale.range = function(_) {
return arguments.length ? (range = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();
};
scale.invertExtent = function(y) {
var i = range.indexOf(y);
return [domain[i - 1], domain[i]];
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
scale.copy = function() {
return threshold_threshold()
.domain(domain)
.range(range)
.unknown(unknown);
};
return initRange.apply(scale, arguments);
}
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/scales.js
// scale registry
const scales_scales = {};
/**
* Augment scales with their type and needed inverse methods.
*/
function scales_create(type, constructor, metadata) {
const ctr = function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? invertRange(s)
: s.invertExtent ? invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
ctr.metadata = Object(vega_util["Da" /* toSet */])(Object(vega_util["i" /* array */])(metadata));
return ctr;
}
function scales_scale(type, scale, metadata) {
if (arguments.length > 1) {
scales_scales[type] = scales_create(type, scale, metadata);
return this;
} else {
return scales_isValidScaleType(type) ? scales_scales[type] : undefined;
}
}
// identity scale
scales_scale(Identity, identity_identity);
// continuous scales
scales_scale(types_Linear, linear_linear, Continuous);
scales_scale(Log, log_log, [Continuous, Log]);
scales_scale(Pow, pow_pow, Continuous);
scales_scale(Sqrt, pow_sqrt, Continuous);
scales_scale(Symlog, symlog_symlog, Continuous);
scales_scale(Time, src_time, [Continuous, Temporal]);
scales_scale(UTC, utcTime, [Continuous, Temporal]);
// sequential scales
scales_scale(Sequential, sequential_sequential, [Continuous, Interpolating]); // backwards compat
scales_scale(`${Sequential}-${types_Linear}`, sequential_sequential, [Continuous, Interpolating]);
scales_scale(`${Sequential}-${Log}`, sequential_sequentialLog, [Continuous, Interpolating, Log]);
scales_scale(`${Sequential}-${Pow}`, sequential_sequentialPow, [Continuous, Interpolating]);
scales_scale(`${Sequential}-${Sqrt}`, sequential_sequentialSqrt, [Continuous, Interpolating]);
scales_scale(`${Sequential}-${Symlog}`, sequential_sequentialSymlog, [Continuous, Interpolating]);
// diverging scales
scales_scale(`${Diverging}-${types_Linear}`, diverging_diverging, [Continuous, Interpolating]);
scales_scale(`${Diverging}-${Log}`, diverging_divergingLog, [Continuous, Interpolating, Log]);
scales_scale(`${Diverging}-${Pow}`, diverging_divergingPow, [Continuous, Interpolating]);
scales_scale(`${Diverging}-${Sqrt}`, diverging_divergingSqrt, [Continuous, Interpolating]);
scales_scale(`${Diverging}-${Symlog}`, diverging_divergingSymlog, [Continuous, Interpolating]);
// discretizing scales
scales_scale(types_Quantile, src_quantile_quantile, [Discretizing, types_Quantile]);
scales_scale(Quantize, quantize_quantize, Discretizing);
scales_scale(Threshold, threshold_threshold, Discretizing);
// discrete scales
scales_scale(BinOrdinal, scaleBinOrdinal_scaleBinOrdinal, [Discrete, Discretizing]);
scales_scale(Ordinal, ordinal_ordinal, Discrete);
scales_scale(Band, scaleBand_band, Discrete);
scales_scale(Point, scaleBand_point, Discrete);
function scales_isValidScaleType(type) {
return Object(vega_util["v" /* hasOwnProperty */])(scales_scales, type);
}
function scales_hasType(key, type) {
const s = scales_scales[key];
return s && s.metadata[type];
}
function scales_isContinuous(key) {
return scales_hasType(key, Continuous);
}
function scales_isDiscrete(key) {
return scales_hasType(key, Discrete);
}
function scales_isDiscretizing(key) {
return scales_hasType(key, Discretizing);
}
function scales_isLogarithmic(key) {
return scales_hasType(key, Log);
}
function scales_isTemporal(key) {
return scales_hasType(key, Temporal);
}
function scales_isInterpolating(key) {
return scales_hasType(key, Interpolating);
}
function scales_isQuantile(key) {
return scales_hasType(key, types_Quantile);
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/discrete.js
/* harmony default export */ var discrete = (function(range) {
var n = range.length;
return function(t) {
return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/hue.js
/* harmony default export */ var src_hue = (function(a, b) {
var i = color_hue(+a, +b);
return function(t) {
var x = i(t);
return x - 360 * Math.floor(x / 360);
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/transform/decompose.js
var degrees = 180 / Math.PI;
var decompose_identity = {
translateX: 0,
translateY: 0,
rotate: 0,
skewX: 0,
scaleX: 1,
scaleY: 1
};
/* harmony default export */ var decompose = (function(a, b, c, d, e, f) {
var scaleX, scaleY, skewX;
if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;
if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;
if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;
if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;
return {
translateX: e,
translateY: f,
rotate: Math.atan2(b, a) * degrees,
skewX: Math.atan(skewX) * degrees,
scaleX: scaleX,
scaleY: scaleY
};
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/transform/parse.js
var parse_cssNode,
parse_cssRoot,
parse_cssView,
parse_svgNode;
function parse_parseCss(value) {
if (value === "none") return decompose_identity;
if (!parse_cssNode) parse_cssNode = document.createElement("DIV"), parse_cssRoot = document.documentElement, parse_cssView = document.defaultView;
parse_cssNode.style.transform = value;
value = parse_cssView.getComputedStyle(parse_cssRoot.appendChild(parse_cssNode), null).getPropertyValue("transform");
parse_cssRoot.removeChild(parse_cssNode);
value = value.slice(7, -1).split(",");
return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
}
function parse_parseSvg(value) {
if (value == null) return decompose_identity;
if (!parse_svgNode) parse_svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g");
parse_svgNode.setAttribute("transform", value);
if (!(value = parse_svgNode.transform.baseVal.consolidate())) return decompose_identity;
value = value.matrix;
return decompose(value.a, value.b, value.c, value.d, value.e, value.f);
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/transform/index.js
function transform_interpolateTransform(parse, pxComma, pxParen, degParen) {
function pop(s) {
return s.length ? s.pop() + " " : "";
}
function translate(xa, ya, xb, yb, s, q) {
if (xa !== xb || ya !== yb) {
var i = s.push("translate(", null, pxComma, null, pxParen);
q.push({i: i - 4, x: d3_interpolate_src_number(xa, xb)}, {i: i - 2, x: d3_interpolate_src_number(ya, yb)});
} else if (xb || yb) {
s.push("translate(" + xb + pxComma + yb + pxParen);
}
}
function rotate(a, b, s, q) {
if (a !== b) {
if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path
q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: d3_interpolate_src_number(a, b)});
} else if (b) {
s.push(pop(s) + "rotate(" + b + degParen);
}
}
function skewX(a, b, s, q) {
if (a !== b) {
q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: d3_interpolate_src_number(a, b)});
} else if (b) {
s.push(pop(s) + "skewX(" + b + degParen);
}
}
function scale(xa, ya, xb, yb, s, q) {
if (xa !== xb || ya !== yb) {
var i = s.push(pop(s) + "scale(", null, ",", null, ")");
q.push({i: i - 4, x: d3_interpolate_src_number(xa, xb)}, {i: i - 2, x: d3_interpolate_src_number(ya, yb)});
} else if (xb !== 1 || yb !== 1) {
s.push(pop(s) + "scale(" + xb + "," + yb + ")");
}
}
return function(a, b) {
var s = [], // string constants and placeholders
q = []; // number interpolators
a = parse(a), b = parse(b);
translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);
rotate(a.rotate, b.rotate, s, q);
skewX(a.skewX, b.skewX, s, q);
scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);
a = b = null; // gc
return function(t) {
var i = -1, n = q.length, o;
while (++i < n) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
};
}
var transform_interpolateTransformCss = transform_interpolateTransform(parse_parseCss, "px, ", "px)", "deg)");
var transform_interpolateTransformSvg = transform_interpolateTransform(parse_parseSvg, ", ", ")", ")");
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/zoom.js
var rho = Math.SQRT2,
rho2 = 2,
rho4 = 4,
epsilon2 = 1e-12;
function zoom_cosh(x) {
return ((x = Math.exp(x)) + 1 / x) / 2;
}
function zoom_sinh(x) {
return ((x = Math.exp(x)) - 1 / x) / 2;
}
function tanh(x) {
return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}
// p0 = [ux0, uy0, w0]
// p1 = [ux1, uy1, w1]
/* harmony default export */ var src_zoom = (function(p0, p1) {
var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],
ux1 = p1[0], uy1 = p1[1], w1 = p1[2],
dx = ux1 - ux0,
dy = uy1 - uy0,
d2 = dx * dx + dy * dy,
i,
S;
// Special case for u0 ≅ u1.
if (d2 < epsilon2) {
S = Math.log(w1 / w0) / rho;
i = function(t) {
return [
ux0 + t * dx,
uy0 + t * dy,
w0 * Math.exp(rho * t * S)
];
}
}
// General case.
else {
var d1 = Math.sqrt(d2),
b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),
b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),
r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),
r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
S = (r1 - r0) / rho;
i = function(t) {
var s = t * S,
coshr0 = zoom_cosh(r0),
u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - zoom_sinh(r0));
return [
ux0 + u * dx,
uy0 + u * dy,
w0 * coshr0 / zoom_cosh(rho * s + r0)
];
}
}
i.duration = S * 1000;
return i;
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/hsl.js
function hsl_hsl(hue) {
return function(start, end) {
var h = hue((start = color_hsl(start)).h, (end = color_hsl(end)).h),
s = color_nogamma(start.s, end.s),
l = color_nogamma(start.l, end.l),
opacity = color_nogamma(start.opacity, end.opacity);
return function(t) {
start.h = h(t);
start.s = s(t);
start.l = l(t);
start.opacity = opacity(t);
return start + "";
};
}
}
/* harmony default export */ var src_hsl = (hsl_hsl(color_hue));
var hsl_hslLong = hsl_hsl(color_nogamma);
// CONCATENATED MODULE: ./node_modules/d3-color/src/math.js
var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;
// CONCATENATED MODULE: ./node_modules/d3-color/src/lab.js
// https://observablehq.com/@mbostock/lab-and-rgb
var lab_K = 18,
lab_Xn = 0.96422,
lab_Yn = 1,
lab_Zn = 0.82521,
lab_t0 = 4 / 29,
lab_t1 = 6 / 29,
lab_t2 = 3 * lab_t1 * lab_t1,
lab_t3 = lab_t1 * lab_t1 * lab_t1;
function lab_labConvert(o) {
if (o instanceof lab_Lab) return new lab_Lab(o.l, o.a, o.b, o.opacity);
if (o instanceof lab_Hcl) return lab_hcl2lab(o);
if (!(o instanceof color_Rgb)) o = color_rgbConvert(o);
var r = lab_rgb2lrgb(o.r),
g = lab_rgb2lrgb(o.g),
b = lab_rgb2lrgb(o.b),
y = lab_xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / lab_Yn), x, z;
if (r === g && g === b) x = z = y; else {
x = lab_xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / lab_Xn);
z = lab_xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / lab_Zn);
}
return new lab_Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}
function lab_gray(l, opacity) {
return new lab_Lab(l, 0, 0, opacity == null ? 1 : opacity);
}
function lab_lab(l, a, b, opacity) {
return arguments.length === 1 ? lab_labConvert(l) : new lab_Lab(l, a, b, opacity == null ? 1 : opacity);
}
function lab_Lab(l, a, b, opacity) {
this.l = +l;
this.a = +a;
this.b = +b;
this.opacity = +opacity;
}
define(lab_Lab, lab_lab, extend(color_Color, {
brighter: function(k) {
return new lab_Lab(this.l + lab_K * (k == null ? 1 : k), this.a, this.b, this.opacity);
},
darker: function(k) {
return new lab_Lab(this.l - lab_K * (k == null ? 1 : k), this.a, this.b, this.opacity);
},
rgb: function() {
var y = (this.l + 16) / 116,
x = isNaN(this.a) ? y : y + this.a / 500,
z = isNaN(this.b) ? y : y - this.b / 200;
x = lab_Xn * lab_lab2xyz(x);
y = lab_Yn * lab_lab2xyz(y);
z = lab_Zn * lab_lab2xyz(z);
return new color_Rgb(
lab_lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
lab_lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
lab_lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
this.opacity
);
}
}));
function lab_xyz2lab(t) {
return t > lab_t3 ? Math.pow(t, 1 / 3) : t / lab_t2 + lab_t0;
}
function lab_lab2xyz(t) {
return t > lab_t1 ? t * t * t : lab_t2 * (t - lab_t0);
}
function lab_lrgb2rgb(x) {
return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
function lab_rgb2lrgb(x) {
return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function lab_hclConvert(o) {
if (o instanceof lab_Hcl) return new lab_Hcl(o.h, o.c, o.l, o.opacity);
if (!(o instanceof lab_Lab)) o = lab_labConvert(o);
if (o.a === 0 && o.b === 0) return new lab_Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
var h = Math.atan2(o.b, o.a) * rad2deg;
return new lab_Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function lab_lch(l, c, h, opacity) {
return arguments.length === 1 ? lab_hclConvert(l) : new lab_Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function lab_hcl(h, c, l, opacity) {
return arguments.length === 1 ? lab_hclConvert(h) : new lab_Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function lab_Hcl(h, c, l, opacity) {
this.h = +h;
this.c = +c;
this.l = +l;
this.opacity = +opacity;
}
function lab_hcl2lab(o) {
if (isNaN(o.h)) return new lab_Lab(o.l, 0, 0, o.opacity);
var h = o.h * deg2rad;
return new lab_Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
define(lab_Hcl, lab_hcl, extend(color_Color, {
brighter: function(k) {
return new lab_Hcl(this.h, this.c, this.l + lab_K * (k == null ? 1 : k), this.opacity);
},
darker: function(k) {
return new lab_Hcl(this.h, this.c, this.l - lab_K * (k == null ? 1 : k), this.opacity);
},
rgb: function() {
return lab_hcl2lab(this).rgb();
}
}));
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/lab.js
function src_lab_lab(start, end) {
var l = color_nogamma((start = lab_lab(start)).l, (end = lab_lab(end)).l),
a = color_nogamma(start.a, end.a),
b = color_nogamma(start.b, end.b),
opacity = color_nogamma(start.opacity, end.opacity);
return function(t) {
start.l = l(t);
start.a = a(t);
start.b = b(t);
start.opacity = opacity(t);
return start + "";
};
}
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/hcl.js
function hcl_hcl(hue) {
return function(start, end) {
var h = hue((start = lab_hcl(start)).h, (end = lab_hcl(end)).h),
c = color_nogamma(start.c, end.c),
l = color_nogamma(start.l, end.l),
opacity = color_nogamma(start.opacity, end.opacity);
return function(t) {
start.h = h(t);
start.c = c(t);
start.l = l(t);
start.opacity = opacity(t);
return start + "";
};
}
}
/* harmony default export */ var src_hcl = (hcl_hcl(color_hue));
var hcl_hclLong = hcl_hcl(color_nogamma);
// CONCATENATED MODULE: ./node_modules/d3-color/src/cubehelix.js
var cubehelix_A = -0.14861,
cubehelix_B = +1.78277,
cubehelix_C = -0.29227,
cubehelix_D = -0.90649,
cubehelix_E = +1.97294,
cubehelix_ED = cubehelix_E * cubehelix_D,
cubehelix_EB = cubehelix_E * cubehelix_B,
cubehelix_BC_DA = cubehelix_B * cubehelix_C - cubehelix_D * cubehelix_A;
function cubehelix_cubehelixConvert(o) {
if (o instanceof cubehelix_Cubehelix) return new cubehelix_Cubehelix(o.h, o.s, o.l, o.opacity);
if (!(o instanceof color_Rgb)) o = color_rgbConvert(o);
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
l = (cubehelix_BC_DA * b + cubehelix_ED * r - cubehelix_EB * g) / (cubehelix_BC_DA + cubehelix_ED - cubehelix_EB),
bl = b - l,
k = (cubehelix_E * (g - l) - cubehelix_C * bl) / cubehelix_D,
s = Math.sqrt(k * k + bl * bl) / (cubehelix_E * l * (1 - l)), // NaN if l=0 or l=1
h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
return new cubehelix_Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}
function cubehelix_cubehelix(h, s, l, opacity) {
return arguments.length === 1 ? cubehelix_cubehelixConvert(h) : new cubehelix_Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}
function cubehelix_Cubehelix(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(cubehelix_Cubehelix, cubehelix_cubehelix, extend(color_Color, {
brighter: function(k) {
k = k == null ? color_brighter : Math.pow(color_brighter, k);
return new cubehelix_Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
k = k == null ? color_darker : Math.pow(color_darker, k);
return new cubehelix_Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
l = +this.l,
a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
cosh = Math.cos(h),
sinh = Math.sin(h);
return new color_Rgb(
255 * (l + a * (cubehelix_A * cosh + cubehelix_B * sinh)),
255 * (l + a * (cubehelix_C * cosh + cubehelix_D * sinh)),
255 * (l + a * (cubehelix_E * cosh)),
this.opacity
);
}
}));
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/cubehelix.js
function src_cubehelix_cubehelix(hue) {
return (function cubehelixGamma(y) {
y = +y;
function cubehelix(start, end) {
var h = hue((start = cubehelix_cubehelix(start)).h, (end = cubehelix_cubehelix(end)).h),
s = color_nogamma(start.s, end.s),
l = color_nogamma(start.l, end.l),
opacity = color_nogamma(start.opacity, end.opacity);
return function(t) {
start.h = h(t);
start.s = s(t);
start.l = l(Math.pow(t, y));
start.opacity = opacity(t);
return start + "";
};
}
cubehelix.gamma = cubehelixGamma;
return cubehelix;
})(1);
}
/* harmony default export */ var src_cubehelix = (src_cubehelix_cubehelix(color_hue));
var cubehelix_cubehelixLong = src_cubehelix_cubehelix(color_nogamma);
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/quantize.js
/* harmony default export */ var d3_interpolate_src_quantize = (function(interpolator, n) {
var samples = new Array(n);
for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));
return samples;
});
// CONCATENATED MODULE: ./node_modules/d3-interpolate/src/index.js
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/interpolate.js
const interpolate_scaleProps = ['clamp', 'base', 'constant', 'exponent'];
function interpolate_interpolateRange(interpolator, range) {
var start = range[0],
span = Object(vega_util["U" /* peek */])(range) - start;
return function(i) { return interpolator(start + i * span); };
}
function interpolate_interpolateColors(colors, type, gamma) {
return piecewise_piecewise(interpolate_interpolate(type || 'rgb', gamma), colors);
}
function interpolate_quantizeInterpolator(interpolator, count) {
var samples = new Array(count),
n = count + 1;
for (var i = 0; i < count;) samples[i] = interpolator(++i / n);
return samples;
}
function interpolate_scaleCopy(scale) {
const t = scale.type,
s = scale.copy();
s.type = t;
return s;
}
function interpolate_scaleFraction(scale, min, max) {
var delta = max - min, i, t, s;
if (!delta || !Number.isFinite(delta)) {
return Object(vega_util["l" /* constant */])(0.5);
} else {
i = (t = scale.type).indexOf('-');
t = i < 0 ? t : t.slice(i + 1);
s = scales_scale(t)().domain([min, max]).range([0, 1]);
interpolate_scaleProps.forEach(m => scale[m] ? s[m](scale[m]()) : 0);
return s;
}
}
function interpolate_interpolate(type, gamma) {
var interp = d3_interpolate_src_namespaceObject[interpolate_method(type)];
return (gamma != null && interp && interp.gamma)
? interp.gamma(gamma)
: interp;
}
function interpolate_method(type) {
return 'interpolate' + type.toLowerCase()
.split('-')
.map(function(s) { return s[0].toUpperCase() + s.slice(1); })
.join('');
}
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/palettes.js
const palettes_continuous = {
blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',
greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',
greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',
oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',
purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',
reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',
blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',
bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',
greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',
orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',
purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',
purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',
purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',
redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',
yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',
yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',
yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',
blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',
brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',
purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',
purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',
redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',
redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',
yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',
redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',
redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',
pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',
spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',
viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',
magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',
inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',
plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',
rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',
sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',
browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',
tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',
teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',
warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',
goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',
goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',
goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',
lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',
lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',
lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',
lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',
lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',
darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',
darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',
darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',
darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',
darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'
};
const palettes_discrete = {
category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',
category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',
category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',
category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',
tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',
tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',
accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',
dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',
paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',
pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',
pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',
set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',
set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',
set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f'
};
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/src/schemes.js
function schemes_colors(palette) {
var n = palette.length / 6 | 0, c = new Array(n), i = 0;
while (i < n) c[i] = '#' + palette.slice(i * 6, ++i * 6);
return c;
}
function schemes_apply(_, f) {
for (let k in _) schemes_scheme(k, f(_[k]));
}
const schemes_schemes = {};
schemes_apply(palettes_discrete, schemes_colors);
schemes_apply(palettes_continuous, _ => interpolate_interpolateColors(schemes_colors(_)));
function schemes_scheme(name, scheme) {
name = name && name.toLowerCase();
if (arguments.length > 1) {
schemes_schemes[name] = scheme;
return this;
} else {
return schemes_schemes[name];
}
}
// CONCATENATED MODULE: ./node_modules/d3-scale/src/index.js
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/vega-scale/index.js
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatDecimal.js
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
/* harmony default export */ var formatDecimal = (function(x, p) {
if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
var i, coefficient = x.slice(0, i);
// The string returned by toExponential either has the form \d\.\d+e[-+]\d+
// (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
return [
coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
+x.slice(i + 1)
];
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/exponent.js
/* harmony default export */ var src_exponent = (function(x) {
return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN;
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatGroup.js
/* harmony default export */ var formatGroup = (function(grouping, thousands) {
return function(value, width) {
var i = value.length,
t = [],
j = 0,
g = grouping[0],
length = 0;
while (i > 0 && g > 0) {
if (length + g + 1 > width) g = Math.max(1, width - length);
t.push(value.substring(i -= g, i + g));
if ((length += g + 1) > width) break;
g = grouping[j = (j + 1) % grouping.length];
}
return t.reverse().join(thousands);
};
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ var formatNumerals = (function(numerals) {
return function(value) {
return value.replace(/[0-9]/g, function(i) {
return numerals[+i];
});
};
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
var match;
return new FormatSpecifier({
fill: match[1],
align: match[2],
sign: match[3],
symbol: match[4],
zero: match[5],
width: match[6],
comma: match[7],
precision: match[8] && match[8].slice(1),
trim: match[9],
type: match[10]
});
}
formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
function FormatSpecifier(specifier) {
this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
this.align = specifier.align === undefined ? ">" : specifier.align + "";
this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
this.zero = !!specifier.zero;
this.width = specifier.width === undefined ? undefined : +specifier.width;
this.comma = !!specifier.comma;
this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
this.trim = !!specifier.trim;
this.type = specifier.type === undefined ? "" : specifier.type + "";
}
FormatSpecifier.prototype.toString = function() {
return this.fill
+ this.align
+ this.sign
+ this.symbol
+ (this.zero ? "0" : "")
+ (this.width === undefined ? "" : Math.max(1, this.width | 0))
+ (this.comma ? "," : "")
+ (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
+ (this.trim ? "~" : "")
+ this.type;
};
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ var formatTrim = (function(s) {
out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (s[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) i0 = i; i1 = i; break;
default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
}
}
return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatPrefixAuto.js
var formatPrefixAuto_prefixExponent;
/* harmony default export */ var formatPrefixAuto = (function(x, p) {
var d = formatDecimal(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1],
i = exponent - (formatPrefixAuto_prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
n = coefficient.length;
return i === n ? coefficient
: i > n ? coefficient + new Array(i - n + 1).join("0")
: i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
: "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatRounded.js
/* harmony default export */ var formatRounded = (function(x, p) {
var d = formatDecimal(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1];
return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
: coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
: coefficient + new Array(exponent - coefficient.length + 2).join("0");
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/formatTypes.js
/* harmony default export */ var formatTypes = ({
"%": function(x, p) { return (x * 100).toFixed(p); },
"b": function(x) { return Math.round(x).toString(2); },
"c": function(x) { return x + ""; },
"d": function(x) { return Math.round(x).toString(10); },
"e": function(x, p) { return x.toExponential(p); },
"f": function(x, p) { return x.toFixed(p); },
"g": function(x, p) { return x.toPrecision(p); },
"o": function(x) { return Math.round(x).toString(8); },
"p": function(x, p) { return formatRounded(x * 100, p); },
"r": formatRounded,
"s": formatPrefixAuto,
"X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
"x": function(x) { return Math.round(x).toString(16); }
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/identity.js
/* harmony default export */ var d3_format_src_identity = (function(x) {
return x;
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/locale.js
var locale_map = Array.prototype.map,
locale_prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
/* harmony default export */ var src_locale = (function(locale) {
var group = locale.grouping === undefined || locale.thousands === undefined ? d3_format_src_identity : formatGroup(locale_map.call(locale.grouping, Number), locale.thousands + ""),
currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
decimal = locale.decimal === undefined ? "." : locale.decimal + "",
numerals = locale.numerals === undefined ? d3_format_src_identity : formatNumerals(locale_map.call(locale.numerals, String)),
percent = locale.percent === undefined ? "%" : locale.percent + "",
minus = locale.minus === undefined ? "-" : locale.minus + "",
nan = locale.nan === undefined ? "NaN" : locale.nan + "";
function newFormat(specifier) {
specifier = formatSpecifier(specifier);
var fill = specifier.fill,
align = specifier.align,
sign = specifier.sign,
symbol = specifier.symbol,
zero = specifier.zero,
width = specifier.width,
comma = specifier.comma,
precision = specifier.precision,
trim = specifier.trim,
type = specifier.type;
// The "n" type is an alias for ",g".
if (type === "n") comma = true, type = "g";
// The "" type, and any invalid type, is an alias for ".12~g".
else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";
// If zero fill is specified, padding goes after sign and before digits.
if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
// Compute the prefix and suffix.
// For SI-prefix, the suffix is lazily computed.
var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
// What format function should we use?
// Is this an integer type?
// Can this type generate exponential notation?
var formatType = formatTypes[type],
maybeSuffix = /[defgprs%]/.test(type);
// Set the default precision if not specified,
// or clamp the specified precision to the supported range.
// For significant precision, it must be in [1, 21].
// For fixed precision, it must be in [0, 20].
precision = precision === undefined ? 6
: /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
: Math.max(0, Math.min(20, precision));
function format(value) {
var valuePrefix = prefix,
valueSuffix = suffix,
i, n, c;
if (type === "c") {
valueSuffix = formatType(value) + valueSuffix;
value = "";
} else {
value = +value;
// Determine the sign. -0 is not less than 0, but 1 / -0 is!
var valueNegative = value < 0 || 1 / value < 0;
// Perform the initial formatting.
value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
// Trim insignificant zeros.
if (trim) value = formatTrim(value);
// If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
// Compute the prefix and suffix.
valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
valueSuffix = (type === "s" ? locale_prefixes[8 + formatPrefixAuto_prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
if (maybeSuffix) {
i = -1, n = value.length;
while (++i < n) {
if (c = value.charCodeAt(i), 48 > c || c > 57) {
valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
value = value.slice(0, i);
break;
}
}
}
}
// If the fill character is not "0", grouping is applied before padding.
if (comma && !zero) value = group(value, Infinity);
// Compute the padding.
var length = valuePrefix.length + value.length + valueSuffix.length,
padding = length < width ? new Array(width - length + 1).join(fill) : "";
// If the fill character is "0", grouping is applied after padding.
if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
// Reconstruct the final output based on the desired alignment.
switch (align) {
case "<": value = valuePrefix + value + valueSuffix + padding; break;
case "=": value = valuePrefix + padding + value + valueSuffix; break;
case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
default: value = padding + valuePrefix + value + valueSuffix; break;
}
return numerals(value);
}
format.toString = function() {
return specifier + "";
};
return format;
}
function formatPrefix(specifier, value) {
var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
e = Math.max(-8, Math.min(8, Math.floor(src_exponent(value) / 3))) * 3,
k = Math.pow(10, -e),
prefix = locale_prefixes[8 + e / 3];
return function(value) {
return f(k * value) + prefix;
};
}
return {
format: newFormat,
formatPrefix: formatPrefix
};
});
// CONCATENATED MODULE: ./node_modules/vega-encode/node_modules/d3-format/src/defaultLocale.js
var src_defaultLocale_locale;
var defaultLocale_format;
var defaultLocale_formatPrefix;
src_defaultLocale_defaultLocale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["$", ""],
minus: "-"
});
function src_defaultLocale_defaultLocale(definition) {
src_defaultLocale_locale = src_locale(definition);
defaultLocale_format = src_defaultLocale_locale.format;
defaultLocale_formatPrefix = src_defaultLocale_locale.formatPrefix;
return src_defaultLocale_locale;
}
// CONCATENATED MODULE: ./node_modules/vega-encode/src/ticks.js
const ticks_defaultFormatter = value => Object(vega_util["A" /* isArray */])(value)
? value.map(v => String(v))
: String(value);
/**
* Determine the tick count or interval function.
* @param {Scale} scale - The scale for which to generate tick values.
* @param {*} count - The desired tick count or interval specifier.
* @param {number} minStep - The desired minimum step between tick values.
* @return {*} - The tick count or interval function.
*/
function ticks_tickCount(scale, count, minStep) {
var step;
if (Object(vega_util["E" /* isNumber */])(count)) {
if (scale.bins) {
count = Math.max(count, scale.bins.length);
}
if (minStep != null) {
count = Math.min(count, ~~(Object(vega_util["X" /* span */])(scale.domain()) / minStep) || 1);
}
}
if (Object(vega_util["F" /* isObject */])(count)) {
step = count.step;
count = count.interval;
}
if (Object(vega_util["H" /* isString */])(count)) {
count = scale.type === Time ? interval_timeInterval(count)
: scale.type == UTC ? interval_utcInterval(count)
: Object(vega_util["n" /* error */])('Only time and utc scales accept interval strings.');
if (step) count = count.every(step);
}
return count;
}
/**
* Filter a set of candidate tick values, ensuring that only tick values
* that lie within the scale range are included.
* @param {Scale} scale - The scale for which to generate tick values.
* @param {Array<*>} ticks - The candidate tick values.
* @param {*} count - The tick count or interval function.
* @return {Array<*>} - The filtered tick values.
*/
function ticks_validTicks(scale, ticks, count) {
var range = scale.range(),
lo = Math.floor(range[0]),
hi = Math.ceil(Object(vega_util["U" /* peek */])(range));
if (lo > hi) {
range = hi;
hi = lo;
lo = range;
}
ticks = ticks.filter(function(v) {
v = scale(v);
return lo <= v && v <= hi;
});
if (count > 0 && ticks.length > 1) {
var endpoints = [ticks[0], Object(vega_util["U" /* peek */])(ticks)];
while (ticks.length > count && ticks.length >= 3) {
ticks = ticks.filter(function(_, i) { return !(i % 2); });
}
if (ticks.length < 3) {
ticks = endpoints;
}
}
return ticks;
}
/**
* Generate tick values for the given scale and approximate tick count or
* interval value. If the scale has a 'ticks' method, it will be used to
* generate the ticks, with the count argument passed as a parameter. If the
* scale lacks a 'ticks' method, the full scale domain will be returned.
* @param {Scale} scale - The scale for which to generate tick values.
* @param {*} [count] - The approximate number of desired ticks.
* @return {Array<*>} - The generated tick values.
*/
function ticks_tickValues(scale, count) {
return scale.bins ? ticks_validTicks(scale, scale.bins)
: scale.ticks ? scale.ticks(count)
: scale.domain();
}
/**
* Generate a label format function for a scale. If the scale has a
* 'tickFormat' method, it will be used to generate the formatter, with the
* count and specifier arguments passed as parameters. If the scale lacks a
* 'tickFormat' method, the returned formatter performs simple string coercion.
* If the input scale is a logarithmic scale and the format specifier does not
* indicate a desired decimal precision, a special variable precision formatter
* that automatically trims trailing zeroes will be generated.
* @param {Scale} scale - The scale for which to generate the label formatter.
* @param {*} [count] - The approximate number of desired ticks.
* @param {string} [specifier] - The format specifier. Must be a legal d3
* specifier string (see https://github.com/d3/d3-format#formatSpecifier) or
* time multi-format specifier object.
* @return {function(*):string} - The generated label formatter.
*/
function ticks_tickFormat(scale, count, specifier, formatType, noSkip) {
var type = scale.type,
format = (type === Time || formatType === Time) ? format_timeFormat(specifier)
: (type === UTC || formatType === UTC) ? format_utcFormat(specifier)
: scale.tickFormat ? scale.tickFormat(count, specifier)
: specifier ? defaultLocale_format(specifier)
: ticks_defaultFormatter;
if (scales_isLogarithmic(type)) {
var logfmt = ticks_variablePrecision(specifier);
format = noSkip || scale.bins ? logfmt : ticks_filter(format, logfmt);
}
return format;
}
function ticks_filter(sourceFormat, targetFormat) {
return _ => sourceFormat(_) ? targetFormat(_) : '';
}
function ticks_variablePrecision(specifier) {
var s = formatSpecifier(specifier || ',');
if (s.precision == null) {
s.precision = 12;
switch (s.type) {
case '%': s.precision -= 2; break;
case 'e': s.precision -= 1; break;
}
return ticks_trimZeroes(
defaultLocale_format(s), // number format
defaultLocale_format('.1f')(1)[1] // decimal point character
);
} else {
return defaultLocale_format(s);
}
}
function ticks_trimZeroes(format, decimalChar) {
return function(x) {
var str = format(x),
dec = str.indexOf(decimalChar),
idx, end;
if (dec < 0) return str;
idx = ticks_rightmostDigit(str, dec);
end = idx < str.length ? str.slice(idx) : '';
while (--idx > dec) if (str[idx] !== '0') { ++idx; break; }
return str.slice(0, idx) + end;
};
}
function ticks_rightmostDigit(str, dec) {
var i = str.lastIndexOf('e'), c;
if (i > 0) return i;
for (i=str.length; --i > dec;) {
c = str.charCodeAt(i);
if (c >= 48 && c <= 57) return i + 1; // is digit
}
}
// CONCATENATED MODULE: ./node_modules/vega-encode/src/AxisTicks.js
/**
* Generates axis ticks for visualizing a spatial scale.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Scale} params.scale - The scale to generate ticks for.
* @param {*} [params.count=10] - The approximate number of ticks, or
* desired tick interval, to use.
* @param {Array<*>} [params.values] - The exact tick values to use.
* These must be legal domain values for the provided scale.
* If provided, the count argument is ignored.
* @param {function(*):string} [params.formatSpecifier] - A format specifier
* to use in conjunction with scale.tickFormat. Legal values are
* any valid d3 4.0 format specifier.
* @param {function(*):string} [params.format] - The format function to use.
* If provided, the formatSpecifier argument is ignored.
*/
function AxisTicks_AxisTicks(params) {
Transform_Transform.call(this, null, params);
}
var AxisTicks_prototype = Object(vega_util["y" /* inherits */])(AxisTicks_AxisTicks, Transform_Transform);
AxisTicks_prototype.transform = function(_, pulse) {
if (this.value && !_.modified()) {
return pulse.StopPropagation;
}
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
ticks = this.value,
scale = _.scale,
tally = _.count == null ? (_.values ? _.values.length : 10) : _.count,
count = ticks_tickCount(scale, tally, _.minstep),
format = _.format || ticks_tickFormat(scale, count, _.formatSpecifier, _.formatType, !!_.values),
values = _.values ? ticks_validTicks(scale, _.values, count) : ticks_tickValues(scale, count);
if (ticks) out.rem = ticks;
ticks = values.map(function(value, i) {
return Tuple_ingest({
index: i / (values.length - 1 || 1),
value: value,
label: format(value)
});
});
if (_.extra && ticks.length) {
// add an extra tick pegged to the initial domain value
// this is used to generate axes with 'binned' domains
ticks.push(Tuple_ingest({
index: -1,
extra: {value: ticks[0].value},
label: ''
}));
}
out.source = ticks;
out.add = ticks;
this.value = ticks;
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-encode/src/DataJoin.js
/**
* Joins a set of data elements against a set of visual items.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): object} [params.item] - An item generator function.
* @param {function(object): *} [params.key] - The key field associating data and visual items.
*/
function DataJoin_DataJoin(params) {
Transform_Transform.call(this, null, params);
}
var DataJoin_prototype = Object(vega_util["y" /* inherits */])(DataJoin_DataJoin, Transform_Transform);
function DataJoin_defaultItemCreate() {
return Tuple_ingest({});
}
function DataJoin_isExit(t) {
return t.exit;
}
DataJoin_prototype.transform = function(_, pulse) {
var df = pulse.dataflow,
out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
item = _.item || DataJoin_defaultItemCreate,
key = _.key || tupleid,
map = this.value;
// prevent transient (e.g., hover) requests from
// cascading across marks derived from marks
if (Object(vega_util["A" /* isArray */])(out.encode)) {
out.encode = null;
}
if (map && (_.modified('key') || pulse.modified(key))) {
Object(vega_util["n" /* error */])('DataJoin does not support modified key function or fields.');
}
if (!map) {
pulse = pulse.addAll();
this.value = map = Object(vega_util["s" /* fastmap */])().test(DataJoin_isExit);
map.lookup = function(t) { return map.get(key(t)); };
}
pulse.visit(pulse.ADD, function(t) {
var k = key(t),
x = map.get(k);
if (x) {
if (x.exit) {
map.empty--;
out.add.push(x);
} else {
out.mod.push(x);
}
} else {
map.set(k, (x = item(t)));
out.add.push(x);
}
x.datum = t;
x.exit = false;
});
pulse.visit(pulse.MOD, function(t) {
var k = key(t),
x = map.get(k);
if (x) {
x.datum = t;
out.mod.push(x);
}
});
pulse.visit(pulse.REM, function(t) {
var k = key(t),
x = map.get(k);
if (t === x.datum && !x.exit) {
out.rem.push(x);
x.exit = true;
++map.empty;
}
});
if (pulse.changed(pulse.ADD_MOD)) out.modifies('datum');
if (_.clean && map.empty > df.cleanThreshold) df.runAfter(map.clean);
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-encode/src/Encode.js
/**
* Invokes encoding functions for visual items.
* @constructor
* @param {object} params - The parameters to the encoding functions. This
* parameter object will be passed through to all invoked encoding functions.
* @param {object} [params.mod=false] - Flag indicating if tuples in the input
* mod set that are unmodified by encoders should be included in the output.
* @param {object} param.encoders - The encoding functions
* @param {function(object, object): boolean} [param.encoders.update] - Update encoding set
* @param {function(object, object): boolean} [param.encoders.enter] - Enter encoding set
* @param {function(object, object): boolean} [param.encoders.exit] - Exit encoding set
*/
function Encode_Encode(params) {
Transform_Transform.call(this, null, params);
}
var Encode_prototype = Object(vega_util["y" /* inherits */])(Encode_Encode, Transform_Transform);
Encode_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.ADD_REM),
fmod = _.mod || false,
encoders = _.encoders,
encode = pulse.encode;
// if an array, the encode directive includes additional sets
// that must be defined in order for the primary set to be invoked
// e.g., only run the update set if the hover set is defined
if (Object(vega_util["A" /* isArray */])(encode)) {
if (out.changed() || encode.every(function(e) { return encoders[e]; })) {
encode = encode[0];
out.encode = null; // consume targeted encode directive
} else {
return pulse.StopPropagation;
}
}
// marshall encoder functions
var reenter = encode === 'enter',
update = encoders.update || vega_util["r" /* falsy */],
enter = encoders.enter || vega_util["r" /* falsy */],
exit = encoders.exit || vega_util["r" /* falsy */],
set = (encode && !reenter ? encoders[encode] : update) || vega_util["r" /* falsy */];
if (pulse.changed(pulse.ADD)) {
pulse.visit(pulse.ADD, function(t) { enter(t, _); update(t, _); });
out.modifies(enter.output);
out.modifies(update.output);
if (set !== vega_util["r" /* falsy */] && set !== update) {
pulse.visit(pulse.ADD, function(t) { set(t, _); });
out.modifies(set.output);
}
}
if (pulse.changed(pulse.REM) && exit !== vega_util["r" /* falsy */]) {
pulse.visit(pulse.REM, function(t) { exit(t, _); });
out.modifies(exit.output);
}
if (reenter || set !== vega_util["r" /* falsy */]) {
var flag = pulse.MOD | (_.modified() ? pulse.REFLOW : 0);
if (reenter) {
pulse.visit(flag, function(t) {
var mod = enter(t, _) || fmod;
if (set(t, _) || mod) out.mod.push(t);
});
if (out.mod.length) out.modifies(enter.output);
} else {
pulse.visit(flag, function(t) {
if (set(t, _) || fmod) out.mod.push(t);
});
}
if (out.mod.length) out.modifies(set.output);
}
return out.changed() ? out : pulse.StopPropagation;
};
// CONCATENATED MODULE: ./node_modules/vega-encode/src/legend-types.js
var legend_types_Symbols = 'symbol';
var legend_types_Discrete = 'discrete';
var legend_types_Gradient = 'gradient';
// CONCATENATED MODULE: ./node_modules/vega-encode/src/labels.js
const labels_symbols = {
[types_Quantile]: 'quantiles',
[Quantize]: 'thresholds',
[Threshold]: 'domain'
};
const labels_formats = {
[types_Quantile]: 'quantiles',
[Quantize]: 'domain'
};
function labels_labelValues(scale, count) {
return scale.bins ? labels_binValues(scale.bins)
: scale.type === Log ? labels_logValues(scale, count)
: labels_symbols[scale.type] ? labels_thresholdValues(scale[labels_symbols[scale.type]]())
: ticks_tickValues(scale, count);
}
function labels_logValues(scale, count) {
var ticks = ticks_tickValues(scale, count),
base = scale.base(),
logb = Math.log(base),
k = Math.max(1, base * count / ticks.length);
// apply d3-scale's log format filter criteria
return ticks.filter(d => {
var i = d / Math.pow(base, Math.round(Math.log(d) / logb));
if (i * base < base - 0.5) i *= base;
return i <= k;
});
}
function labels_thresholdFormat(scale, specifier) {
var _ = scale[labels_formats[scale.type]](),
n = _.length,
d = n > 1 ? _[1] - _[0] : _[0], i;
for (i=1; i<n; ++i) {
d = Math.min(d, _[i] - _[i-1]);
}
// 3 ticks times 10 for increased resolution
return src_tickFormat(0, d, 3 * 10, specifier);
}
function labels_thresholdValues(thresholds) {
const values = [-Infinity].concat(thresholds);
values.max = +Infinity;
return values;
}
function labels_binValues(bins) {
const values = bins.slice(0, -1);
values.max = Object(vega_util["U" /* peek */])(bins);
return values;
}
function labels_isDiscreteRange(scale) {
return labels_symbols[scale.type] || scale.bins;
}
function labels_labelFormat(scale, count, type, specifier, formatType, noSkip) {
const format = labels_formats[scale.type] && formatType !== Time && formatType !== UTC
? labels_thresholdFormat(scale, specifier)
: ticks_tickFormat(scale, count, specifier, formatType, noSkip);
return type === legend_types_Symbols && labels_isDiscreteRange(scale) ? labels_formatRange(format)
: type === legend_types_Discrete ? labels_formatDiscrete(format)
: labels_formatPoint(format);
}
function labels_formatRange(format) {
return function(value, index, array) {
var limit = labels_get(array[index + 1], labels_get(array.max, +Infinity)),
lo = labels_formatValue(value, format),
hi = labels_formatValue(limit, format);
return lo && hi ? lo + ' \u2013 ' + hi : hi ? '< ' + hi : '\u2265 ' + lo;
};
}
function labels_get(value, dflt) {
return value != null ? value : dflt;
}
function labels_formatDiscrete(format) {
return function(value, index) {
return index ? format(value) : null;
}
}
function labels_formatPoint(format) {
return function(value) {
return format(value);
};
}
function labels_formatValue(value, format) {
return Number.isFinite(value) ? format(value) : null;
}
function labels_labelFraction(scale) {
var domain = scale.domain(),
count = domain.length - 1,
lo = +domain[0],
hi = +Object(vega_util["U" /* peek */])(domain),
span = hi - lo;
if (scale.type === Threshold) {
var adjust = count ? span / count : 0.1;
lo -= adjust;
hi += adjust;
span = hi - lo;
}
return function(value) {
return (value - lo) / span;
};
}
// CONCATENATED MODULE: ./node_modules/vega-encode/src/LegendEntries.js
/**
* Generates legend entries for visualizing a scale.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Scale} params.scale - The scale to generate items for.
* @param {*} [params.count=5] - The approximate number of items, or
* desired tick interval, to use.
* @param {*} [params.limit] - The maximum number of entries to
* include in a symbol legend.
* @param {Array<*>} [params.values] - The exact tick values to use.
* These must be legal domain values for the provided scale.
* If provided, the count argument is ignored.
* @param {string} [params.formatSpecifier] - A format specifier
* to use in conjunction with scale.tickFormat. Legal values are
* any valid D3 format specifier string.
* @param {function(*):string} [params.format] - The format function to use.
* If provided, the formatSpecifier argument is ignored.
*/
function LegendEntries_LegendEntries(params) {
Transform_Transform.call(this, [], params);
}
var LegendEntries_prototype = Object(vega_util["y" /* inherits */])(LegendEntries_LegendEntries, Transform_Transform);
LegendEntries_prototype.transform = function(_, pulse) {
if (this.value != null && !_.modified()) {
return pulse.StopPropagation;
}
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
items = this.value,
type = _.type || legend_types_Symbols,
scale = _.scale,
limit = +_.limit,
count = ticks_tickCount(scale, _.count == null ? 5 : _.count, _.minstep),
lskip = !!_.values || type === legend_types_Symbols,
format = _.format || labels_labelFormat(scale, count, type, _.formatSpecifier, _.formatType, lskip),
values = _.values || labels_labelValues(scale, count, type),
domain, fraction, size, offset, ellipsis;
if (items) out.rem = items;
if (type === legend_types_Symbols) {
if (limit && values.length > limit) {
pulse.dataflow.warn('Symbol legend count exceeds limit, filtering items.');
items = values.slice(0, limit - 1);
ellipsis = true;
} else {
items = values;
}
if (Object(vega_util["D" /* isFunction */])(size = _.size)) {
// if first value maps to size zero, remove from list (vega#717)
if (!_.values && scale(items[0]) === 0) {
items = items.slice(1);
}
// compute size offset for legend entries
offset = items.reduce(function(max, value) {
return Math.max(max, size(value, _));
}, 0);
} else {
size = Object(vega_util["l" /* constant */])(offset = size || 8);
}
items = items.map(function(value, index) {
return Tuple_ingest({
index: index,
label: format(value, index, items),
value: value,
offset: offset,
size: size(value, _)
});
});
if (ellipsis) {
ellipsis = values[items.length];
items.push(Tuple_ingest({
index: items.length,
label: `\u2026${values.length-items.length} entries`,
value: ellipsis,
offset: offset,
size: size(ellipsis, _)
}));
}
}
else if (type === legend_types_Gradient) {
domain = scale.domain(),
fraction = interpolate_scaleFraction(scale, domain[0], Object(vega_util["U" /* peek */])(domain));
// if automatic label generation produces 2 or fewer values,
// use the domain end points instead (fixes vega/vega#1364)
if (values.length < 3 && !_.values && domain[0] !== Object(vega_util["U" /* peek */])(domain)) {
values = [domain[0], Object(vega_util["U" /* peek */])(domain)];
}
items = values.map(function(value, index) {
return Tuple_ingest({
index: index,
label: format(value, index, values),
value: value,
perc: fraction(value)
});
});
}
else {
size = values.length - 1;
fraction = labels_labelFraction(scale);
items = values.map(function(value, index) {
return Tuple_ingest({
index: index,
label: format(value, index, values),
value: value,
perc: index ? fraction(value) : 0,
perc2: index === size ? 1 : fraction(values[index+1])
});
});
}
out.source = items;
out.add = items;
this.value = items;
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-encode/src/LinkPath.js
var LinkPath_Paths = Object(vega_util["s" /* fastmap */])({
'line': LinkPath_line,
'line-radial': LinkPath_lineR,
'arc': LinkPath_arc,
'arc-radial': LinkPath_arcR,
'curve': LinkPath_curve,
'curve-radial': LinkPath_curveR,
'orthogonal-horizontal': LinkPath_orthoX,
'orthogonal-vertical': LinkPath_orthoY,
'orthogonal-radial': LinkPath_orthoR,
'diagonal-horizontal': LinkPath_diagonalX,
'diagonal-vertical': LinkPath_diagonalY,
'diagonal-radial': LinkPath_diagonalR
});
function LinkPath_sourceX(t) { return t.source.x; }
function LinkPath_sourceY(t) { return t.source.y; }
function LinkPath_targetX(t) { return t.target.x; }
function LinkPath_targetY(t) { return t.target.y; }
/**
* Layout paths linking source and target elements.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function LinkPath_LinkPath(params) {
Transform_Transform.call(this, {}, params);
}
LinkPath_LinkPath.Definition = {
"type": "LinkPath",
"metadata": {"modifies": true},
"params": [
{ "name": "sourceX", "type": "field", "default": "source.x" },
{ "name": "sourceY", "type": "field", "default": "source.y" },
{ "name": "targetX", "type": "field", "default": "target.x" },
{ "name": "targetY", "type": "field", "default": "target.y" },
{ "name": "orient", "type": "enum", "default": "vertical",
"values": ["horizontal", "vertical", "radial"] },
{ "name": "shape", "type": "enum", "default": "line",
"values": ["line", "arc", "curve", "diagonal", "orthogonal"] },
{ "name": "require", "type": "signal" },
{ "name": "as", "type": "string", "default": "path" }
]
};
var LinkPath_prototype = Object(vega_util["y" /* inherits */])(LinkPath_LinkPath, Transform_Transform);
LinkPath_prototype.transform = function(_, pulse) {
var sx = _.sourceX || LinkPath_sourceX,
sy = _.sourceY || LinkPath_sourceY,
tx = _.targetX || LinkPath_targetX,
ty = _.targetY || LinkPath_targetY,
as = _.as || 'path',
orient = _.orient || 'vertical',
shape = _.shape || 'line',
path = LinkPath_Paths.get(shape + '-' + orient) || LinkPath_Paths.get(shape);
if (!path) {
Object(vega_util["n" /* error */])('LinkPath unsupported type: ' + _.shape
+ (_.orient ? '-' + _.orient : ''));
}
pulse.visit(pulse.SOURCE, function(t) {
t[as] = path(sx(t), sy(t), tx(t), ty(t));
});
return pulse.reflow(_.modified()).modifies(as);
};
// -- Link Path Generation Methods -----
function LinkPath_line(sx, sy, tx, ty) {
return 'M' + sx + ',' + sy +
'L' + tx + ',' + ty;
}
function LinkPath_lineR(sa, sr, ta, tr) {
return LinkPath_line(
sr * Math.cos(sa), sr * Math.sin(sa),
tr * Math.cos(ta), tr * Math.sin(ta)
);
}
function LinkPath_arc(sx, sy, tx, ty) {
var dx = tx - sx,
dy = ty - sy,
rr = Math.sqrt(dx * dx + dy * dy) / 2,
ra = 180 * Math.atan2(dy, dx) / Math.PI;
return 'M' + sx + ',' + sy +
'A' + rr + ',' + rr +
' ' + ra + ' 0 1' +
' ' + tx + ',' + ty;
}
function LinkPath_arcR(sa, sr, ta, tr) {
return LinkPath_arc(
sr * Math.cos(sa), sr * Math.sin(sa),
tr * Math.cos(ta), tr * Math.sin(ta)
);
}
function LinkPath_curve(sx, sy, tx, ty) {
var dx = tx - sx,
dy = ty - sy,
ix = 0.2 * (dx + dy),
iy = 0.2 * (dy - dx);
return 'M' + sx + ',' + sy +
'C' + (sx+ix) + ',' + (sy+iy) +
' ' + (tx+iy) + ',' + (ty-ix) +
' ' + tx + ',' + ty;
}
function LinkPath_curveR(sa, sr, ta, tr) {
return LinkPath_curve(
sr * Math.cos(sa), sr * Math.sin(sa),
tr * Math.cos(ta), tr * Math.sin(ta)
);
}
function LinkPath_orthoX(sx, sy, tx, ty) {
return 'M' + sx + ',' + sy +
'V' + ty + 'H' + tx;
}
function LinkPath_orthoY(sx, sy, tx, ty) {
return 'M' + sx + ',' + sy +
'H' + tx + 'V' + ty;
}
function LinkPath_orthoR(sa, sr, ta, tr) {
var sc = Math.cos(sa),
ss = Math.sin(sa),
tc = Math.cos(ta),
ts = Math.sin(ta),
sf = Math.abs(ta - sa) > Math.PI ? ta <= sa : ta > sa;
return 'M' + (sr*sc) + ',' + (sr*ss) +
'A' + sr + ',' + sr + ' 0 0,' + (sf?1:0) +
' ' + (sr*tc) + ',' + (sr*ts) +
'L' + (tr*tc) + ',' + (tr*ts);
}
function LinkPath_diagonalX(sx, sy, tx, ty) {
var m = (sx + tx) / 2;
return 'M' + sx + ',' + sy +
'C' + m + ',' + sy +
' ' + m + ',' + ty +
' ' + tx + ',' + ty;
}
function LinkPath_diagonalY(sx, sy, tx, ty) {
var m = (sy + ty) / 2;
return 'M' + sx + ',' + sy +
'C' + sx + ',' + m +
' ' + tx + ',' + m +
' ' + tx + ',' + ty;
}
function LinkPath_diagonalR(sa, sr, ta, tr) {
var sc = Math.cos(sa),
ss = Math.sin(sa),
tc = Math.cos(ta),
ts = Math.sin(ta),
mr = (sr + tr) / 2;
return 'M' + (sr*sc) + ',' + (sr*ss) +
'C' + (mr*sc) + ',' + (mr*ss) +
' ' + (mr*tc) + ',' + (mr*ts) +
' ' + (tr*tc) + ',' + (tr*ts);
}
// CONCATENATED MODULE: ./node_modules/d3-array/src/sum.js
function sum_sum(values, valueof) {
let sum = 0;
if (valueof === undefined) {
for (let value of values) {
if (value = +value) {
sum += value;
}
}
} else {
let index = -1;
for (let value of values) {
if (value = +valueof(value, ++index, values)) {
sum += value;
}
}
}
return sum;
}
// CONCATENATED MODULE: ./node_modules/vega-encode/src/Pie.js
/**
* Pie and donut chart layout.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to size pie segments.
* @param {number} [params.startAngle=0] - The start angle (in radians) of the layout.
* @param {number} [params.endAngle=2π] - The end angle (in radians) of the layout.
* @param {boolean} [params.sort] - Boolean flag for sorting sectors by value.
*/
function Pie_Pie(params) {
Transform_Transform.call(this, null, params);
}
Pie_Pie.Definition = {
"type": "Pie",
"metadata": {"modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "startAngle", "type": "number", "default": 0 },
{ "name": "endAngle", "type": "number", "default": 6.283185307179586 },
{ "name": "sort", "type": "boolean", "default": false },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": ["startAngle", "endAngle"] }
]
};
var Pie_prototype = Object(vega_util["y" /* inherits */])(Pie_Pie, Transform_Transform);
Pie_prototype.transform = function(_, pulse) {
var as = _.as || ['startAngle', 'endAngle'],
startAngle = as[0],
endAngle = as[1],
field = _.field || vega_util["O" /* one */],
start = _.startAngle || 0,
stop = _.endAngle != null ? _.endAngle : 2 * Math.PI,
data = pulse.source,
values = data.map(field),
n = values.length,
a = start,
k = (stop - start) / sum_sum(values),
index = src_range(n),
i, t, v;
if (_.sort) {
index.sort(function(a, b) {
return values[a] - values[b];
});
}
for (i=0; i<n; ++i) {
v = values[index[i]];
t = data[index[i]];
t[startAngle] = a;
t[endAngle] = (a += v * k);
}
this.value = values;
return pulse.reflow(_.modified()).modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-encode/src/Scale.js
var Scale_DEFAULT_COUNT = 5;
function Scale_includeZero(scale) {
const type = scale.type;
return !scale.bins && (
type === types_Linear || type === Pow || type === Sqrt
);
}
function Scale_includePad(type) {
return scales_isContinuous(type) && type !== Sequential;
}
var Scale_SKIP = Object(vega_util["Da" /* toSet */])([
'set', 'modified', 'clear', 'type', 'scheme', 'schemeExtent', 'schemeCount',
'domain', 'domainMin', 'domainMid', 'domainMax',
'domainRaw', 'domainImplicit', 'nice', 'zero', 'bins',
'range', 'rangeStep', 'round', 'reverse', 'interpolate', 'interpolateGamma'
]);
/**
* Maintains a scale function mapping data values to visual channels.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function Scale_Scale(params) {
Transform_Transform.call(this, null, params);
this.modified(true); // always treat as modified
}
var Scale_prototype = Object(vega_util["y" /* inherits */])(Scale_Scale, Transform_Transform);
Scale_prototype.transform = function(_, pulse) {
var df = pulse.dataflow,
scale = this.value,
key = Scale_scaleKey(_);
if (!scale || key !== scale.type) {
this.value = scale = scales_scale(key)();
}
for (key in _) if (!Scale_SKIP[key]) {
// padding is a scale property for band/point but not others
if (key === 'padding' && Scale_includePad(scale.type)) continue;
// invoke scale property setter, raise warning if not found
Object(vega_util["D" /* isFunction */])(scale[key])
? scale[key](_[key])
: df.warn('Unsupported scale property: ' + key);
}
Scale_configureRange(scale, _,
Scale_configureBins(scale, _, Scale_configureDomain(scale, _, df))
);
return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
};
function Scale_scaleKey(_) {
var t = _.type, d = '', n;
// backwards compatibility pre Vega 5.
if (t === Sequential) return Sequential + '-' + types_Linear;
if (Scale_isContinuousColor(_)) {
n = _.rawDomain ? _.rawDomain.length
: _.domain ? _.domain.length + +(_.domainMid != null)
: 0;
d = n === 2 ? Sequential + '-'
: n === 3 ? Diverging + '-'
: '';
}
return ((d + t) || types_Linear).toLowerCase();
}
function Scale_isContinuousColor(_) {
const t = _.type;
return scales_isContinuous(t) && t !== Time && t !== UTC && (
_.scheme || _.range && _.range.length && _.range.every(vega_util["H" /* isString */])
);
}
function Scale_configureDomain(scale, _, df) {
// check raw domain, if provided use that and exit early
var raw = Scale_rawDomain(scale, _.domainRaw, df);
if (raw > -1) return raw;
var domain = _.domain,
type = scale.type,
zero = _.zero || (_.zero === undefined && Scale_includeZero(scale)),
n, mid;
if (!domain) return 0;
// adjust continuous domain for minimum pixel padding
if (Scale_includePad(type) && _.padding && domain[0] !== Object(vega_util["U" /* peek */])(domain)) {
domain = Scale_padDomain(type, domain, _.range, _.padding, _.exponent, _.constant);
}
// adjust domain based on zero, min, max settings
if (zero || _.domainMin != null || _.domainMax != null || _.domainMid != null) {
n = ((domain = domain.slice()).length - 1) || 1;
if (zero) {
if (domain[0] > 0) domain[0] = 0;
if (domain[n] < 0) domain[n] = 0;
}
if (_.domainMin != null) domain[0] = _.domainMin;
if (_.domainMax != null) domain[n] = _.domainMax;
if (_.domainMid != null) {
mid = _.domainMid;
if (mid < domain[0] || mid > domain[n]) {
df.warn('Scale domainMid exceeds domain min or max.', mid);
}
domain.splice(n, 0, mid);
}
}
// set the scale domain
scale.domain(Scale_domainCheck(type, domain, df));
// if ordinal scale domain is defined, prevent implicit
// domain construction as side-effect of scale lookup
if (type === Ordinal) {
scale.unknown(_.domainImplicit ? ordinal_implicit : undefined);
}
// perform 'nice' adjustment as requested
if (_.nice && scale.nice) {
scale.nice((_.nice !== true && ticks_tickCount(scale, _.nice)) || null);
}
// return the cardinality of the domain
return domain.length;
}
function Scale_rawDomain(scale, raw, df) {
if (raw) {
scale.domain(Scale_domainCheck(scale.type, raw, df));
return raw.length;
} else {
return -1;
}
}
function Scale_padDomain(type, domain, range, pad, exponent, constant) {
var span = Math.abs(Object(vega_util["U" /* peek */])(range) - range[0]),
frac = span / (span - 2 * pad),
d = type === Log ? Object(vega_util["Ma" /* zoomLog */])(domain, null, frac)
: type === Sqrt ? Object(vega_util["Na" /* zoomPow */])(domain, null, frac, 0.5)
: type === Pow ? Object(vega_util["Na" /* zoomPow */])(domain, null, frac, exponent || 1)
: type === Symlog ? Object(vega_util["Oa" /* zoomSymlog */])(domain, null, frac, constant || 1)
: Object(vega_util["La" /* zoomLinear */])(domain, null, frac);
domain = domain.slice();
domain[0] = d[0];
domain[domain.length-1] = d[1];
return domain;
}
function Scale_domainCheck(type, domain, df) {
if (scales_isLogarithmic(type)) {
// sum signs of domain values
// if all pos or all neg, abs(sum) === domain.length
var s = Math.abs(domain.reduce(function(s, v) {
return s + (v < 0 ? -1 : v > 0 ? 1 : 0);
}, 0));
if (s !== domain.length) {
df.warn('Log scale domain includes zero: ' + Object(vega_util["Z" /* stringValue */])(domain));
}
}
return domain;
}
function Scale_configureBins(scale, _, count) {
let bins = _.bins;
if (bins && !Object(vega_util["A" /* isArray */])(bins)) {
// generate bin boundary array
let domain = scale.domain(),
lo = domain[0],
hi = Object(vega_util["U" /* peek */])(domain),
start = bins.start == null ? lo : bins.start,
stop = bins.stop == null ? hi : bins.stop,
step = bins.step;
if (!step) Object(vega_util["n" /* error */])('Scale bins parameter missing step property.');
if (start < lo) start = step * Math.ceil(lo / step);
if (stop > hi) stop = step * Math.floor(hi / step);
bins = src_range(start, stop + step / 2, step);
}
if (bins) {
// assign bin boundaries to scale instance
scale.bins = bins;
} else if (scale.bins) {
// no current bins, remove bins if previously set
delete scale.bins;
}
// special handling for bin-ordinal scales
if (scale.type === BinOrdinal) {
if (!bins) {
// the domain specifies the bins
scale.bins = scale.domain();
} else if (!_.domain && !_.domainRaw) {
// the bins specify the domain
scale.domain(bins);
count = bins.length;
}
}
// return domain cardinality
return count;
}
function Scale_configureRange(scale, _, count) {
var type = scale.type,
round = _.round || false,
range = _.range;
// if range step specified, calculate full range extent
if (_.rangeStep != null) {
range = Scale_configureRangeStep(type, _, count);
}
// else if a range scheme is defined, use that
else if (_.scheme) {
range = Scale_configureScheme(type, _, count);
if (Object(vega_util["D" /* isFunction */])(range)) {
if (scale.interpolator) {
return scale.interpolator(range);
} else {
Object(vega_util["n" /* error */])(`Scale type ${type} does not support interpolating color schemes.`);
}
}
}
// given a range array for an interpolating scale, convert to interpolator
if (range && scales_isInterpolating(type)) {
return scale.interpolator(
interpolate_interpolateColors(Scale_flip(range, _.reverse), _.interpolate, _.interpolateGamma)
);
}
// configure rounding / interpolation
if (range && _.interpolate && scale.interpolate) {
scale.interpolate(interpolate_interpolate(_.interpolate, _.interpolateGamma));
} else if (Object(vega_util["D" /* isFunction */])(scale.round)) {
scale.round(round);
} else if (Object(vega_util["D" /* isFunction */])(scale.rangeRound)) {
scale.interpolate(round ? src_round : src_value);
}
if (range) scale.range(Scale_flip(range, _.reverse));
}
function Scale_configureRangeStep(type, _, count) {
if (type !== Band && type !== Point) {
Object(vega_util["n" /* error */])('Only band and point scales support rangeStep.');
}
// calculate full range based on requested step size and padding
var outer = (_.paddingOuter != null ? _.paddingOuter : _.padding) || 0,
inner = type === Point ? 1
: ((_.paddingInner != null ? _.paddingInner : _.padding) || 0);
return [0, _.rangeStep * bandSpace(count, inner, outer)];
}
function Scale_configureScheme(type, _, count) {
var extent = _.schemeExtent,
name, scheme;
if (Object(vega_util["A" /* isArray */])(_.scheme)) {
scheme = interpolate_interpolateColors(_.scheme, _.interpolate, _.interpolateGamma);
} else {
name = _.scheme.toLowerCase();
scheme = schemes_scheme(name);
if (!scheme) Object(vega_util["n" /* error */])(`Unrecognized scheme name: ${_.scheme}`);
}
// determine size for potential discrete range
count = (type === Threshold) ? count + 1
: (type === BinOrdinal) ? count - 1
: (type === types_Quantile || type === Quantize) ? (+_.schemeCount || Scale_DEFAULT_COUNT)
: count;
// adjust and/or quantize scheme as appropriate
return scales_isInterpolating(type) ? Scale_adjustScheme(scheme, extent, _.reverse)
: Object(vega_util["D" /* isFunction */])(scheme) ? interpolate_quantizeInterpolator(Scale_adjustScheme(scheme, extent), count)
: type === Ordinal ? scheme : scheme.slice(0, count);
}
function Scale_adjustScheme(scheme, extent, reverse) {
return (Object(vega_util["D" /* isFunction */])(scheme) && (extent || reverse))
? interpolate_interpolateRange(scheme, Scale_flip(extent || [0, 1], reverse))
: scheme;
}
function Scale_flip(array, reverse) {
return reverse ? array.slice().reverse() : array;
}
// CONCATENATED MODULE: ./node_modules/vega-encode/src/SortItems.js
/**
* Sorts scenegraph items in the pulse source array.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(*,*): number} [params.sort] - A comparator
* function for sorting tuples.
*/
function SortItems_SortItems(params) {
Transform_Transform.call(this, null, params);
}
var SortItems_prototype = Object(vega_util["y" /* inherits */])(SortItems_SortItems, Transform_Transform);
SortItems_prototype.transform = function(_, pulse) {
var mod = _.modified('sort')
|| pulse.changed(pulse.ADD)
|| pulse.modified(_.sort.fields)
|| pulse.modified('datum');
if (mod) pulse.source.sort(stableCompare(_.sort));
this.modified(mod);
return pulse;
};
// CONCATENATED MODULE: ./node_modules/vega-encode/src/Stack.js
var Stack_Zero = 'zero',
Stack_Center = 'center',
Stack_Normalize = 'normalize',
Stack_DefOutput = ['y0', 'y1'];
/**
* Stack layout for visualization elements.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to stack.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
* @param {function(object,object): number} [params.sort] - A comparator for stack sorting.
* @param {string} [offset='zero'] - Stack baseline offset. One of 'zero', 'center', 'normalize'.
*/
function Stack_Stack(params) {
Transform_Transform.call(this, null, params);
}
Stack_Stack.Definition = {
"type": "Stack",
"metadata": {"modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "sort", "type": "compare" },
{ "name": "offset", "type": "enum", "default": Stack_Zero, "values": [Stack_Zero, Stack_Center, Stack_Normalize] },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": Stack_DefOutput }
]
};
var Stack_prototype = Object(vega_util["y" /* inherits */])(Stack_Stack, Transform_Transform);
Stack_prototype.transform = function(_, pulse) {
var as = _.as || Stack_DefOutput,
y0 = as[0],
y1 = as[1],
sort = stableCompare(_.sort),
field = _.field || vega_util["O" /* one */],
stack = _.offset === Stack_Center ? Stack_stackCenter
: _.offset === Stack_Normalize ? Stack_stackNormalize
: Stack_stackZero,
groups, i, n, max;
// partition, sum, and sort the stack groups
groups = Stack_partition(pulse.source, _.groupby, sort, field);
// compute stack layouts per group
for (i=0, n=groups.length, max=groups.max; i<n; ++i) {
stack(groups[i], max, field, y0, y1);
}
return pulse.reflow(_.modified()).modifies(as);
};
function Stack_stackCenter(group, max, field, y0, y1) {
var last = (max - group.sum) / 2,
m = group.length,
j = 0, t;
for (; j<m; ++j) {
t = group[j];
t[y0] = last;
t[y1] = (last += Math.abs(field(t)));
}
}
function Stack_stackNormalize(group, max, field, y0, y1) {
var scale = 1 / group.sum,
last = 0,
m = group.length,
j = 0, v = 0, t;
for (; j<m; ++j) {
t = group[j];
t[y0] = last;
t[y1] = last = scale * (v += Math.abs(field(t)));
}
}
function Stack_stackZero(group, max, field, y0, y1) {
var lastPos = 0,
lastNeg = 0,
m = group.length,
j = 0, v, t;
for (; j<m; ++j) {
t = group[j];
v = +field(t);
if (v < 0) {
t[y0] = lastNeg;
t[y1] = (lastNeg += v);
} else {
t[y0] = lastPos;
t[y1] = (lastPos += v);
}
}
}
function Stack_partition(data, groupby, sort, field) {
var groups = [],
get = function(f) { return f(t); },
map, i, n, m, t, k, g, s, max;
// partition data points into stack groups
if (groupby == null) {
groups.push(data.slice());
} else {
for (map={}, i=0, n=data.length; i<n; ++i) {
t = data[i];
k = groupby.map(get);
g = map[k];
if (!g) {
map[k] = (g = []);
groups.push(g);
}
g.push(t);
}
}
// compute sums of groups, sort groups as needed
for (k=0, max=0, m=groups.length; k<m; ++k) {
g = groups[k];
for (i=0, s=0, n=g.length; i<n; ++i) {
s += Math.abs(field(g[i]));
}
g.sum = s;
if (s > max) max = s;
if (sort) g.sort(sort);
}
groups.max = max;
return groups;
}
// CONCATENATED MODULE: ./node_modules/vega-encode/index.js
// CONCATENATED MODULE: ./node_modules/vega-geo/src/util/contours.js
function contours_noop() {}
const contours_cases = [
[],
[[[1.0, 1.5], [0.5, 1.0]]],
[[[1.5, 1.0], [1.0, 1.5]]],
[[[1.5, 1.0], [0.5, 1.0]]],
[[[1.0, 0.5], [1.5, 1.0]]],
[[[1.0, 1.5], [0.5, 1.0]], [[1.0, 0.5], [1.5, 1.0]]],
[[[1.0, 0.5], [1.0, 1.5]]],
[[[1.0, 0.5], [0.5, 1.0]]],
[[[0.5, 1.0], [1.0, 0.5]]],
[[[1.0, 1.5], [1.0, 0.5]]],
[[[0.5, 1.0], [1.0, 0.5]], [[1.5, 1.0], [1.0, 1.5]]],
[[[1.5, 1.0], [1.0, 0.5]]],
[[[0.5, 1.0], [1.5, 1.0]]],
[[[1.0, 1.5], [1.5, 1.0]]],
[[[0.5, 1.0], [1.0, 1.5]]],
[]
];
// Implementation adapted from d3/d3-contour. Thanks!
/* harmony default export */ var util_contours = (function() {
var dx = 1,
dy = 1,
smooth = smoothLinear;
function contours(values, tz) {
return tz.map(value => contour(values, value));
}
// Accumulate, smooth contour rings, assign holes to exterior rings.
// Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js
function contour(values, value) {
var polygons = [],
holes = [];
isorings(values, value, function(ring) {
smooth(ring, values, value);
if (contours_area(ring) > 0) polygons.push([ring]);
else holes.push(ring);
});
holes.forEach(function(hole) {
for (var i = 0, n = polygons.length, polygon; i < n; ++i) {
if (contours_contains((polygon = polygons[i])[0], hole) !== -1) {
polygon.push(hole);
return;
}
}
});
return {
type: 'MultiPolygon',
value: value,
coordinates: polygons
};
}
// Marching squares with isolines stitched into rings.
// Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js
function isorings(values, value, callback) {
var fragmentByStart = new Array,
fragmentByEnd = new Array,
x, y, t0, t1, t2, t3;
// Special case for the first row (y = -1, t2 = t3 = 0).
x = y = -1;
t1 = values[0] >= value;
contours_cases[t1 << 1].forEach(stitch);
while (++x < dx - 1) {
t0 = t1, t1 = values[x + 1] >= value;
contours_cases[t0 | t1 << 1].forEach(stitch);
}
contours_cases[t1 << 0].forEach(stitch);
// General case for the intermediate rows.
while (++y < dy - 1) {
x = -1;
t1 = values[y * dx + dx] >= value;
t2 = values[y * dx] >= value;
contours_cases[t1 << 1 | t2 << 2].forEach(stitch);
while (++x < dx - 1) {
t0 = t1, t1 = values[y * dx + dx + x + 1] >= value;
t3 = t2, t2 = values[y * dx + x + 1] >= value;
contours_cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch);
}
contours_cases[t1 | t2 << 3].forEach(stitch);
}
// Special case for the last row (y = dy - 1, t0 = t1 = 0).
x = -1;
t2 = values[y * dx] >= value;
contours_cases[t2 << 2].forEach(stitch);
while (++x < dx - 1) {
t3 = t2, t2 = values[y * dx + x + 1] >= value;
contours_cases[t2 << 2 | t3 << 3].forEach(stitch);
}
contours_cases[t2 << 3].forEach(stitch);
function stitch(line) {
var start = [line[0][0] + x, line[0][1] + y],
end = [line[1][0] + x, line[1][1] + y],
startIndex = index(start),
endIndex = index(end),
f, g;
if (f = fragmentByEnd[startIndex]) {
if (g = fragmentByStart[endIndex]) {
delete fragmentByEnd[f.end];
delete fragmentByStart[g.start];
if (f === g) {
f.ring.push(end);
callback(f.ring);
} else {
fragmentByStart[f.start] = fragmentByEnd[g.end] = {start: f.start, end: g.end, ring: f.ring.concat(g.ring)};
}
} else {
delete fragmentByEnd[f.end];
f.ring.push(end);
fragmentByEnd[f.end = endIndex] = f;
}
} else if (f = fragmentByStart[endIndex]) {
if (g = fragmentByEnd[startIndex]) {
delete fragmentByStart[f.start];
delete fragmentByEnd[g.end];
if (f === g) {
f.ring.push(end);
callback(f.ring);
} else {
fragmentByStart[g.start] = fragmentByEnd[f.end] = {start: g.start, end: f.end, ring: g.ring.concat(f.ring)};
}
} else {
delete fragmentByStart[f.start];
f.ring.unshift(start);
fragmentByStart[f.start = startIndex] = f;
}
} else {
fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {start: startIndex, end: endIndex, ring: [start, end]};
}
}
}
function index(point) {
return point[0] * 2 + point[1] * (dx + 1) * 4;
}
function smoothLinear(ring, values, value) {
ring.forEach(function(point) {
var x = point[0],
y = point[1],
xt = x | 0,
yt = y | 0,
v0,
v1 = values[yt * dx + xt];
if (x > 0 && x < dx && xt === x) {
v0 = values[yt * dx + xt - 1];
point[0] = x + (value - v0) / (v1 - v0) - 0.5;
}
if (y > 0 && y < dy && yt === y) {
v0 = values[(yt - 1) * dx + xt];
point[1] = y + (value - v0) / (v1 - v0) - 0.5;
}
});
}
contours.contour = contour;
contours.size = function(_) {
if (!arguments.length) return [dx, dy];
var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);
if (!(_0 > 0) || !(_1 > 0)) Object(vega_util["n" /* error */])('invalid size');
return dx = _0, dy = _1, contours;
};
contours.smooth = function(_) {
return arguments.length ? (smooth = _ ? smoothLinear : contours_noop, contours) : smooth === smoothLinear;
};
return contours;
});
function contours_area(ring) {
var i = 0,
n = ring.length,
area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
return area;
}
function contours_contains(ring, hole) {
var i = -1, n = hole.length, c;
while (++i < n) if (c = contours_ringContains(ring, hole[i])) return c;
return 0;
}
function contours_ringContains(ring, point) {
var x = point[0], y = point[1], contains = -1;
for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
if (contours_segmentContains(pi, pj, point)) return 0;
if (((yi > y) !== (yj > y)) && ((x < (xj - xi) * (y - yi) / (yj - yi) + xi))) contains = -contains;
}
return contains;
}
function contours_segmentContains(a, b, c) {
var i; return contours_collinear(a, b, c) && contours_within(a[i = +(a[0] === b[0])], c[i], b[i]);
}
function contours_collinear(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]);
}
function contours_within(p, q, r) {
return p <= q && q <= r || r <= q && q <= p;
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/util/quantize.js
/* harmony default export */ var util_quantize = (function(k, nice, zero) {
return function(values) {
var ex = Object(vega_util["p" /* extent */])(values),
start = zero ? Math.min(ex[0], 0) : ex[0],
stop = ex[1],
span = stop - start,
step = nice ? tickStep(start, stop, k) : (span / (k + 1));
return src_range(step, stop, step);
};
});
// CONCATENATED MODULE: ./node_modules/vega-geo/src/Isocontour.js
/**
* Generate isocontours (level sets) based on input raster grid data.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} [params.field] - The field with raster grid
* data. If unspecified, the tuple itself is interpreted as a raster grid.
* @param {Array<number>} [params.thresholds] - Contour threshold array. If
* specified, the levels, nice, resolve, and zero parameters are ignored.
* @param {number} [params.levels] - The desired number of contour levels.
* @param {boolean} [params.nice] - Boolean flag indicating if the contour
* threshold values should be automatically aligned to "nice"
* human-friendly values. Setting this flag may cause the number of
* thresholds to deviate from the specified levels.
* @param {string} [params.resolve] - The method for resolving thresholds
* across multiple input grids. If 'independent' (the default), threshold
* calculation will be performed separately for each grid. If 'shared', a
* single set of threshold values will be used for all input grids.
* @param {boolean} [params.zero] - Boolean flag indicating if the contour
* threshold values should include zero.
* @param {boolean} [params.smooth] - Boolean flag indicating if the contour
* polygons should be smoothed using linear interpolation. The default is
* true. The parameter is ignored when using density estimation.
* @param {boolean} [params.scale] - Optional numerical value by which to
* scale the output isocontour coordinates. This parameter can be useful
* to scale the contours to match a desired output resolution.
* @param {string} [params.as='contour'] - The output field in which to store
* the generated isocontour data (default 'contour').
*/
function Isocontour_Isocontour(params) {
Transform_Transform.call(this, null, params);
}
Isocontour_Isocontour.Definition = {
"type": "Isocontour",
"metadata": {"generates": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "thresholds", "type": "number", "array": true },
{ "name": "levels", "type": "number" },
{ "name": "nice", "type": "boolean", "default": false },
{ "name": "resolve", "type": "enum", "values": ["shared", "independent"], "default": "independent" },
{ "name": "zero", "type": "boolean", "default": true },
{ "name": "smooth", "type": "boolean", "default": true },
{ "name": "scale", "type": "number", "expr": true },
{ "name": "translate", "type": "number", "array": true, "expr": true },
{ "name": "as", "type": "string", "null": true, "default": "contour" }
]
};
var Isocontour_prototype = Object(vega_util["y" /* inherits */])(Isocontour_Isocontour, Transform_Transform);
Isocontour_prototype.transform = function(_, pulse) {
if (this.value && !pulse.changed() && !_.modified()) {
return pulse.StopPropagation;
}
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
source = pulse.materialize(pulse.SOURCE).source,
field = _.field || vega_util["x" /* identity */],
contour = util_contours().smooth(_.smooth !== false),
tz = _.thresholds || Isocontour_levels(source, field, _),
as = _.as === null ? null : _.as || 'contour',
values = [];
source.forEach(t => {
const grid = field(t);
// generate contour paths in GeoJSON format
const paths = contour.size([grid.width, grid.height])(
grid.values, Object(vega_util["A" /* isArray */])(tz) ? tz : tz(grid.values)
);
// adjust contour path coordinates as needed
Isocontour_transformPaths(paths, grid, t, _);
// ingest; copy source data properties to output
paths.forEach(p => {
values.push(rederive(t, Tuple_ingest(as != null ? {[as]: p} : p)));
});
});
if (this.value) out.rem = this.value;
this.value = out.source = out.add = values;
return out;
};
function Isocontour_levels(values, f, _) {
const q = util_quantize(_.levels || 10, _.nice, _.zero !== false);
return _.resolve !== 'shared'
? q
: q(values.map(t => max_max(f(t).values)));
}
function Isocontour_transformPaths(paths, grid, datum, _) {
let s = _.scale || grid.scale,
t = _.translate || grid.translate;
if (Object(vega_util["D" /* isFunction */])(s)) s = s(datum, _);
if (Object(vega_util["D" /* isFunction */])(t)) t = t(datum, _);
if ((s === 1 || s == null) && !t) return;
const sx = (Object(vega_util["E" /* isNumber */])(s) ? s : s[0]) || 1,
sy = (Object(vega_util["E" /* isNumber */])(s) ? s : s[1]) || 1,
tx = t && t[0] || 0,
ty = t && t[1] || 0;
paths.forEach(Isocontour_transform(grid, sx, sy, tx, ty));
}
function Isocontour_transform(grid, sx, sy, tx, ty) {
const x1 = grid.x1 || 0,
y1 = grid.y1 || 0,
flip = sx * sy < 0;
function transformPolygon(coordinates) {
coordinates.forEach(transformRing);
}
function transformRing(coordinates) {
if (flip) coordinates.reverse(); // maintain winding order
coordinates.forEach(transformPoint);
}
function transformPoint(coordinates) {
coordinates[0] = (coordinates[0] - x1) * sx + tx;
coordinates[1] = (coordinates[1] - y1) * sy + ty;
}
return function(geometry) {
geometry.coordinates.forEach(transformPolygon);
return geometry;
};
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/util/density2D.js
function density2D_radius(bw, data, f) {
const v = bw >= 0 ? bw : src_bandwidth(data, f);
return Math.round((Math.sqrt(4 * v * v + 1) - 1) / 2);
}
function density2D_number(_) {
return Object(vega_util["D" /* isFunction */])(_) ? _ : Object(vega_util["l" /* constant */])(+_);
}
// Implementation adapted from d3/d3-contour. Thanks!
/* harmony default export */ var density2D = (function() {
var x = d => d[0],
y = d => d[1],
weight = vega_util["O" /* one */],
bandwidth = [-1, -1],
dx = 960,
dy = 500,
k = 2; // log2(cellSize)
function density(data, counts) {
const rx = density2D_radius(bandwidth[0], data, x) >> k, // blur x-radius
ry = density2D_radius(bandwidth[1], data, y) >> k, // blur y-radius
ox = rx ? rx + 2 : 0, // x-offset padding for blur
oy = ry ? ry + 2 : 0, // y-offset padding for blur
n = 2 * ox + (dx >> k), // grid width
m = 2 * oy + (dy >> k), // grid height
values0 = new Float32Array(n * m),
values1 = new Float32Array(n * m);
let values = values0;
data.forEach(d => {
const xi = ox + (+x(d) >> k),
yi = oy + (+y(d) >> k);
if (xi >= 0 && xi < n && yi >= 0 && yi < m) {
values0[xi + yi * n] += +weight(d);
}
});
if (rx > 0 && ry > 0) {
density2D_blurX(n, m, values0, values1, rx);
density2D_blurY(n, m, values1, values0, ry);
density2D_blurX(n, m, values0, values1, rx);
density2D_blurY(n, m, values1, values0, ry);
density2D_blurX(n, m, values0, values1, rx);
density2D_blurY(n, m, values1, values0, ry);
} else if (rx > 0) {
density2D_blurX(n, m, values0, values1, rx);
density2D_blurX(n, m, values1, values0, rx);
density2D_blurX(n, m, values0, values1, rx);
values = values1;
} else if (ry > 0) {
density2D_blurY(n, m, values0, values1, ry);
density2D_blurY(n, m, values1, values0, ry);
density2D_blurY(n, m, values0, values1, ry);
values = values1;
}
// scale density estimates
// density in points per square pixel or probability density
let s = counts ? Math.pow(2, -2 * k) : 1 / sum_sum(values);
for (let i=0, sz=n*m; i<sz; ++i) values[i] *= s;
return {
values: values,
scale: 1 << k,
width: n,
height: m,
x1: ox,
y1: oy,
x2: ox + (dx >> k),
y2: oy + (dy >> k)
};
}
density.x = function(_) {
return arguments.length ? (x = density2D_number(_), density) : x;
};
density.y = function(_) {
return arguments.length ? (y = density2D_number(_), density) : y;
};
density.weight = function(_) {
return arguments.length ? (weight = density2D_number(_), density) : weight;
};
density.size = function(_) {
if (!arguments.length) return [dx, dy];
var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);
if (!(_0 >= 0) && !(_0 >= 0)) Object(vega_util["n" /* error */])('invalid size');
return dx = _0, dy = _1, density;
};
density.cellSize = function(_) {
if (!arguments.length) return 1 << k;
if (!((_ = +_) >= 1)) Object(vega_util["n" /* error */])('invalid cell size');
k = Math.floor(Math.log(_) / Math.LN2);
return density;
};
density.bandwidth = function(_) {
if (!arguments.length) return bandwidth;
_ = Object(vega_util["i" /* array */])(_);
if (_.length === 1) _ = [+_[0], +_[0]];
if (_.length !== 2) Object(vega_util["n" /* error */])('invalid bandwidth');
return bandwidth = _, density;
};
return density;
});
function density2D_blurX(n, m, source, target, r) {
const w = (r << 1) + 1;
for (let j = 0; j < m; ++j) {
for (let i = 0, sr = 0; i < n + r; ++i) {
if (i < n) {
sr += source[i + j * n];
}
if (i >= r) {
if (i >= w) {
sr -= source[i - w + j * n];
}
target[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w);
}
}
}
}
function density2D_blurY(n, m, source, target, r) {
const w = (r << 1) + 1;
for (let i = 0; i < n; ++i) {
for (let j = 0, sr = 0; j < m + r; ++j) {
if (j < m) {
sr += source[i + j * n];
}
if (j >= r) {
if (j >= w) {
sr -= source[i + (j - w) * n];
}
target[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w);
}
}
}
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/KDE2D.js
/**
* Perform 2D kernel-density estimation of point data.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<number>} params.size - The [width, height] extent (in
* units of input pixels) over which to perform density estimation.
* @param {function(object): number} params.x - The x-coordinate accessor.
* @param {function(object): number} params.y - The y-coordinate accessor.
* @param {function(object): number} [params.weight] - The weight accessor.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors
* to groupby.
* @param {number} [params.cellSize] - Contour density calculation cell size.
* This parameter determines the level of spatial approximation. For example,
* the default value of 4 maps to 2x reductions in both x- and y- dimensions.
* A value of 1 will result in an output raster grid whose dimensions exactly
* matches the size parameter.
* @param {Array<number>} [params.bandwidth] - The KDE kernel bandwidths,
* in pixels. The input can be a two-element array specifying separate
* x and y bandwidths, or a single-element array specifying both. If the
* bandwidth is unspecified or less than zero, the bandwidth will be
* automatically determined.
* @param {boolean} [params.counts=false] - A boolean flag indicating if the
* output values should be probability estimates (false, default) or
* smoothed counts (true).
* @param {string} [params.as='grid'] - The output field in which to store
* the generated raster grid (default 'grid').
*/
function KDE2D_KDE2D(params) {
Transform_Transform.call(this, null, params);
}
KDE2D_KDE2D.Definition = {
"type": "KDE2D",
"metadata": {"generates": true},
"params": [
{ "name": "size", "type": "number", "array": true, "length": 2, "required": true },
{ "name": "x", "type": "field", "required": true },
{ "name": "y", "type": "field", "required": true },
{ "name": "weight", "type": "field" },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "cellSize", "type": "number" },
{ "name": "bandwidth", "type": "number", "array": true, "length": 2 },
{ "name": "counts", "type": "boolean", "default": false },
{ "name": "as", "type": "string", "default": "grid"}
]
};
var KDE2D_prototype = Object(vega_util["y" /* inherits */])(KDE2D_KDE2D, Transform_Transform);
const KDE2D_PARAMS = ['x', 'y', 'weight', 'size', 'cellSize', 'bandwidth'];
function KDE2D_params(obj, _) {
KDE2D_PARAMS.forEach(param => _[param] != null ? obj[param](_[param]) : 0);
return obj;
}
KDE2D_prototype.transform = function(_, pulse) {
if (this.value && !pulse.changed() && !_.modified())
return pulse.StopPropagation;
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
source = pulse.materialize(pulse.SOURCE).source,
groups = KDE2D_partition(source, _.groupby),
names = (_.groupby || []).map(vega_util["h" /* accessorName */]),
kde = KDE2D_params(density2D(), _),
as = _.as || 'grid',
values = [];
function set(t, vals) {
for (let i=0; i<names.length; ++i) t[names[i]] = vals[i];
return t;
}
// generate density raster grids
values = groups.map(g => Tuple_ingest(
set({[as]: kde(g, _.counts)}, g.dims)
));
if (this.value) out.rem = this.value;
this.value = out.source = out.add = values;
return out;
};
function KDE2D_partition(data, groupby) {
var groups = [],
get = f => f(t),
map, i, n, t, k, g;
// partition data points into groups
if (groupby == null) {
groups.push(data);
} else {
for (map={}, i=0, n=data.length; i<n; ++i) {
t = data[i];
k = groupby.map(get);
g = map[k];
if (!g) {
map[k] = (g = []);
g.dims = k;
groups.push(g);
}
g.push(t);
}
}
return groups;
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/Contour.js
/**
* Generate contours based on kernel-density estimation of point data.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<number>} params.size - The dimensions [width, height] over which to compute contours.
* If the values parameter is provided, this must be the dimensions of the input data.
* If density estimation is performed, this is the output view dimensions in pixels.
* @param {Array<number>} [params.values] - An array of numeric values representing an
* width x height grid of values over which to compute contours. If unspecified, this
* transform will instead attempt to compute contours for the kernel density estimate
* using values drawn from data tuples in the input pulse.
* @param {function(object): number} [params.x] - The pixel x-coordinate accessor for density estimation.
* @param {function(object): number} [params.y] - The pixel y-coordinate accessor for density estimation.
* @param {function(object): number} [params.weight] - The data point weight accessor for density estimation.
* @param {number} [params.cellSize] - Contour density calculation cell size.
* @param {number} [params.bandwidth] - Kernel density estimation bandwidth.
* @param {Array<number>} [params.thresholds] - Contour threshold array. If
* this parameter is set, the count and nice parameters will be ignored.
* @param {number} [params.count] - The desired number of contours.
* @param {boolean} [params.nice] - Boolean flag indicating if the contour
* threshold values should be automatically aligned to "nice"
* human-friendly values. Setting this flag may cause the number of
* thresholds to deviate from the specified count.
* @param {boolean} [params.smooth] - Boolean flag indicating if the contour
* polygons should be smoothed using linear interpolation. The default is
* true. The parameter is ignored when using density estimation.
*/
function Contour_Contour(params) {
Transform_Transform.call(this, null, params);
}
Contour_Contour.Definition = {
"type": "Contour",
"metadata": {"generates": true},
"params": [
{ "name": "size", "type": "number", "array": true, "length": 2, "required": true },
{ "name": "values", "type": "number", "array": true },
{ "name": "x", "type": "field" },
{ "name": "y", "type": "field" },
{ "name": "weight", "type": "field" },
{ "name": "cellSize", "type": "number" },
{ "name": "bandwidth", "type": "number" },
{ "name": "count", "type": "number" },
{ "name": "nice", "type": "boolean", "default": false },
{ "name": "thresholds", "type": "number", "array": true },
{ "name": "smooth", "type": "boolean", "default": true }
]
};
var Contour_prototype = Object(vega_util["y" /* inherits */])(Contour_Contour, Transform_Transform);
Contour_prototype.transform = function(_, pulse) {
if (this.value && !pulse.changed() && !_.modified()) {
return pulse.StopPropagation;
}
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
contour = util_contours().smooth(_.smooth !== false),
values = _.values,
thresh = _.thresholds || util_quantize(_.count || 10, _.nice, !!values),
size = _.size, grid, post;
if (!values) {
values = pulse.materialize(pulse.SOURCE).source;
grid = KDE2D_params(density2D(), _)(values, true);
post = Isocontour_transform(grid, grid.scale || 1, grid.scale || 1, 0, 0);
size = [grid.width, grid.height];
values = grid.values;
}
thresh = Object(vega_util["A" /* isArray */])(thresh) ? thresh : thresh(values);
values = contour.size(size)(values, thresh);
if (post) values.forEach(post);
if (this.value) out.rem = this.value;
this.value = out.source = out.add = (values || []).map(Tuple_ingest);
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-geo/src/constants.js
var Feature = 'Feature';
var FeatureCollection = 'FeatureCollection';
var MultiPoint = 'MultiPoint';
// CONCATENATED MODULE: ./node_modules/vega-geo/src/GeoJSON.js
/**
* Consolidate an array of [longitude, latitude] points or GeoJSON features
* into a combined GeoJSON object. This transform is particularly useful for
* combining geo data for a Projection's fit argument. The resulting GeoJSON
* data is available as this transform's value. Input pulses are unchanged.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *>} [params.fields] - A two-element array
* of field accessors for the longitude and latitude values.
* @param {function(object): *} params.geojson - A field accessor for
* retrieving GeoJSON feature data.
*/
function GeoJSON_GeoJSON(params) {
Transform_Transform.call(this, null, params);
}
GeoJSON_GeoJSON.Definition = {
"type": "GeoJSON",
"metadata": {},
"params": [
{ "name": "fields", "type": "field", "array": true, "length": 2 },
{ "name": "geojson", "type": "field" },
]
};
var GeoJSON_prototype = Object(vega_util["y" /* inherits */])(GeoJSON_GeoJSON, Transform_Transform);
GeoJSON_prototype.transform = function(_, pulse) {
var features = this._features,
points = this._points,
fields = _.fields,
lon = fields && fields[0],
lat = fields && fields[1],
geojson = _.geojson || (!fields && vega_util["x" /* identity */]),
flag = pulse.ADD,
mod;
mod = _.modified()
|| pulse.changed(pulse.REM)
|| pulse.modified(Object(vega_util["g" /* accessorFields */])(geojson))
|| (lon && (pulse.modified(Object(vega_util["g" /* accessorFields */])(lon))))
|| (lat && (pulse.modified(Object(vega_util["g" /* accessorFields */])(lat))));
if (!this.value || mod) {
flag = pulse.SOURCE;
this._features = (features = []);
this._points = (points = []);
}
if (geojson) {
pulse.visit(flag, function(t) {
features.push(geojson(t));
});
}
if (lon && lat) {
pulse.visit(flag, function(t) {
var x = lon(t),
y = lat(t);
if (x != null && y != null && (x = +x) === x && (y = +y) === y) {
points.push([x, y]);
}
});
features = features.concat({
type: Feature,
geometry: {
type: MultiPoint,
coordinates: points
}
});
}
this.value = {
type: FeatureCollection,
features: features
};
};
// CONCATENATED MODULE: ./node_modules/d3-geo/src/identity.js
/* harmony default export */ var d3_geo_src_identity = (function(x) {
return x;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/stream.js
function streamGeometry(geometry, stream) {
if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
streamGeometryType[geometry.type](geometry, stream);
}
}
var streamObjectType = {
Feature: function(object, stream) {
streamGeometry(object.geometry, stream);
},
FeatureCollection: function(object, stream) {
var features = object.features, i = -1, n = features.length;
while (++i < n) streamGeometry(features[i].geometry, stream);
}
};
var streamGeometryType = {
Sphere: function(object, stream) {
stream.sphere();
},
Point: function(object, stream) {
object = object.coordinates;
stream.point(object[0], object[1], object[2]);
},
MultiPoint: function(object, stream) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);
},
LineString: function(object, stream) {
streamLine(object.coordinates, stream, 0);
},
MultiLineString: function(object, stream) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) streamLine(coordinates[i], stream, 0);
},
Polygon: function(object, stream) {
streamPolygon(object.coordinates, stream);
},
MultiPolygon: function(object, stream) {
var coordinates = object.coordinates, i = -1, n = coordinates.length;
while (++i < n) streamPolygon(coordinates[i], stream);
},
GeometryCollection: function(object, stream) {
var geometries = object.geometries, i = -1, n = geometries.length;
while (++i < n) streamGeometry(geometries[i], stream);
}
};
function streamLine(coordinates, stream, closed) {
var i = -1, n = coordinates.length - closed, coordinate;
stream.lineStart();
while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
stream.lineEnd();
}
function streamPolygon(coordinates, stream) {
var i = -1, n = coordinates.length;
stream.polygonStart();
while (++i < n) streamLine(coordinates[i], stream, 1);
stream.polygonEnd();
}
/* harmony default export */ var src_stream = (function(object, stream) {
if (object && streamObjectType.hasOwnProperty(object.type)) {
streamObjectType[object.type](object, stream);
} else {
streamGeometry(object, stream);
}
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/adder.js
// Adds floating point numbers with twice the normal precision.
// Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and
// Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3)
// 305363 (1997).
// Code adapted from GeographicLib by Charles F. F. Karney,
// http://geographiclib.sourceforge.net/
/* harmony default export */ var adder = (function() {
return new Adder;
});
function Adder() {
this.reset();
}
Adder.prototype = {
constructor: Adder,
reset: function() {
this.s = // rounded value
this.t = 0; // exact error
},
add: function(y) {
adder_add(adder_temp, y, this.t);
adder_add(this, adder_temp.s, this.s);
if (this.s) this.t += adder_temp.t;
else this.s = adder_temp.t;
},
valueOf: function() {
return this.s;
}
};
var adder_temp = new Adder;
function adder_add(adder, a, b) {
var x = adder.s = a + b,
bv = x - a,
av = x - bv;
adder.t = (a - av) + (b - bv);
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/math.js
var src_math_epsilon = 1e-6;
var math_epsilon2 = 1e-12;
var math_pi = Math.PI;
var math_halfPi = math_pi / 2;
var quarterPi = math_pi / 4;
var src_math_tau = math_pi * 2;
var math_degrees = 180 / math_pi;
var radians = math_pi / 180;
var math_abs = Math.abs;
var atan = Math.atan;
var math_atan2 = Math.atan2;
var src_math_cos = Math.cos;
var ceil = Math.ceil;
var math_exp = Math.exp;
var math_floor = Math.floor;
var math_log = Math.log;
var math_pow = Math.pow;
var src_math_sin = Math.sin;
var math_sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };
var src_math_sqrt = Math.sqrt;
var tan = Math.tan;
function math_acos(x) {
return x > 1 ? 0 : x < -1 ? math_pi : Math.acos(x);
}
function math_asin(x) {
return x > 1 ? math_halfPi : x < -1 ? -math_halfPi : Math.asin(x);
}
function haversin(x) {
return (x = src_math_sin(x / 2)) * x;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/noop.js
function noop_noop() {}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/area.js
var area_areaSum = adder(),
area_areaRingSum = adder(),
area_x00,
area_y00,
area_x0,
area_y0;
var area_areaStream = {
point: noop_noop,
lineStart: noop_noop,
lineEnd: noop_noop,
polygonStart: function() {
area_areaStream.lineStart = area_areaRingStart;
area_areaStream.lineEnd = area_areaRingEnd;
},
polygonEnd: function() {
area_areaStream.lineStart = area_areaStream.lineEnd = area_areaStream.point = noop_noop;
area_areaSum.add(math_abs(area_areaRingSum));
area_areaRingSum.reset();
},
result: function() {
var area = area_areaSum / 2;
area_areaSum.reset();
return area;
}
};
function area_areaRingStart() {
area_areaStream.point = area_areaPointFirst;
}
function area_areaPointFirst(x, y) {
area_areaStream.point = area_areaPoint;
area_x00 = area_x0 = x, area_y00 = area_y0 = y;
}
function area_areaPoint(x, y) {
area_areaRingSum.add(area_y0 * x - area_x0 * y);
area_x0 = x, area_y0 = y;
}
function area_areaRingEnd() {
area_areaPoint(area_x00, area_y00);
}
/* harmony default export */ var path_area = (area_areaStream);
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/bounds.js
var bounds_x0 = Infinity,
bounds_y0 = bounds_x0,
bounds_x1 = -bounds_x0,
bounds_y1 = bounds_x1;
var bounds_boundsStream = {
point: bounds_boundsPoint,
lineStart: noop_noop,
lineEnd: noop_noop,
polygonStart: noop_noop,
polygonEnd: noop_noop,
result: function() {
var bounds = [[bounds_x0, bounds_y0], [bounds_x1, bounds_y1]];
bounds_x1 = bounds_y1 = -(bounds_y0 = bounds_x0 = Infinity);
return bounds;
}
};
function bounds_boundsPoint(x, y) {
if (x < bounds_x0) bounds_x0 = x;
if (x > bounds_x1) bounds_x1 = x;
if (y < bounds_y0) bounds_y0 = y;
if (y > bounds_y1) bounds_y1 = y;
}
/* harmony default export */ var path_bounds = (bounds_boundsStream);
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/centroid.js
// TODO Enforce positive area for exterior, negative area for interior?
var centroid_X0 = 0,
centroid_Y0 = 0,
centroid_Z0 = 0,
centroid_X1 = 0,
centroid_Y1 = 0,
centroid_Z1 = 0,
centroid_X2 = 0,
centroid_Y2 = 0,
centroid_Z2 = 0,
centroid_x00,
centroid_y00,
centroid_x0,
centroid_y0;
var centroid_centroidStream = {
point: centroid_centroidPoint,
lineStart: centroid_centroidLineStart,
lineEnd: centroid_centroidLineEnd,
polygonStart: function() {
centroid_centroidStream.lineStart = centroid_centroidRingStart;
centroid_centroidStream.lineEnd = centroid_centroidRingEnd;
},
polygonEnd: function() {
centroid_centroidStream.point = centroid_centroidPoint;
centroid_centroidStream.lineStart = centroid_centroidLineStart;
centroid_centroidStream.lineEnd = centroid_centroidLineEnd;
},
result: function() {
var centroid = centroid_Z2 ? [centroid_X2 / centroid_Z2, centroid_Y2 / centroid_Z2]
: centroid_Z1 ? [centroid_X1 / centroid_Z1, centroid_Y1 / centroid_Z1]
: centroid_Z0 ? [centroid_X0 / centroid_Z0, centroid_Y0 / centroid_Z0]
: [NaN, NaN];
centroid_X0 = centroid_Y0 = centroid_Z0 =
centroid_X1 = centroid_Y1 = centroid_Z1 =
centroid_X2 = centroid_Y2 = centroid_Z2 = 0;
return centroid;
}
};
function centroid_centroidPoint(x, y) {
centroid_X0 += x;
centroid_Y0 += y;
++centroid_Z0;
}
function centroid_centroidLineStart() {
centroid_centroidStream.point = centroid_centroidPointFirstLine;
}
function centroid_centroidPointFirstLine(x, y) {
centroid_centroidStream.point = centroid_centroidPointLine;
centroid_centroidPoint(centroid_x0 = x, centroid_y0 = y);
}
function centroid_centroidPointLine(x, y) {
var dx = x - centroid_x0, dy = y - centroid_y0, z = src_math_sqrt(dx * dx + dy * dy);
centroid_X1 += z * (centroid_x0 + x) / 2;
centroid_Y1 += z * (centroid_y0 + y) / 2;
centroid_Z1 += z;
centroid_centroidPoint(centroid_x0 = x, centroid_y0 = y);
}
function centroid_centroidLineEnd() {
centroid_centroidStream.point = centroid_centroidPoint;
}
function centroid_centroidRingStart() {
centroid_centroidStream.point = centroid_centroidPointFirstRing;
}
function centroid_centroidRingEnd() {
centroid_centroidPointRing(centroid_x00, centroid_y00);
}
function centroid_centroidPointFirstRing(x, y) {
centroid_centroidStream.point = centroid_centroidPointRing;
centroid_centroidPoint(centroid_x00 = centroid_x0 = x, centroid_y00 = centroid_y0 = y);
}
function centroid_centroidPointRing(x, y) {
var dx = x - centroid_x0,
dy = y - centroid_y0,
z = src_math_sqrt(dx * dx + dy * dy);
centroid_X1 += z * (centroid_x0 + x) / 2;
centroid_Y1 += z * (centroid_y0 + y) / 2;
centroid_Z1 += z;
z = centroid_y0 * x - centroid_x0 * y;
centroid_X2 += z * (centroid_x0 + x);
centroid_Y2 += z * (centroid_y0 + y);
centroid_Z2 += z * 3;
centroid_centroidPoint(centroid_x0 = x, centroid_y0 = y);
}
/* harmony default export */ var centroid = (centroid_centroidStream);
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/context.js
function context_PathContext(context) {
this._context = context;
}
context_PathContext.prototype = {
_radius: 4.5,
pointRadius: function(_) {
return this._radius = _, this;
},
polygonStart: function() {
this._line = 0;
},
polygonEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
if (this._line === 0) this._context.closePath();
this._point = NaN;
},
point: function(x, y) {
switch (this._point) {
case 0: {
this._context.moveTo(x, y);
this._point = 1;
break;
}
case 1: {
this._context.lineTo(x, y);
break;
}
default: {
this._context.moveTo(x + this._radius, y);
this._context.arc(x, y, this._radius, 0, src_math_tau);
break;
}
}
},
result: noop_noop
};
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/measure.js
var measure_lengthSum = adder(),
measure_lengthRing,
measure_x00,
measure_y00,
measure_x0,
measure_y0;
var measure_lengthStream = {
point: noop_noop,
lineStart: function() {
measure_lengthStream.point = measure_lengthPointFirst;
},
lineEnd: function() {
if (measure_lengthRing) measure_lengthPoint(measure_x00, measure_y00);
measure_lengthStream.point = noop_noop;
},
polygonStart: function() {
measure_lengthRing = true;
},
polygonEnd: function() {
measure_lengthRing = null;
},
result: function() {
var length = +measure_lengthSum;
measure_lengthSum.reset();
return length;
}
};
function measure_lengthPointFirst(x, y) {
measure_lengthStream.point = measure_lengthPoint;
measure_x00 = measure_x0 = x, measure_y00 = measure_y0 = y;
}
function measure_lengthPoint(x, y) {
measure_x0 -= x, measure_y0 -= y;
measure_lengthSum.add(src_math_sqrt(measure_x0 * measure_x0 + measure_y0 * measure_y0));
measure_x0 = x, measure_y0 = y;
}
/* harmony default export */ var path_measure = (measure_lengthStream);
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/string.js
function PathString() {
this._string = [];
}
PathString.prototype = {
_radius: 4.5,
_circle: string_circle(4.5),
pointRadius: function(_) {
if ((_ = +_) !== this._radius) this._radius = _, this._circle = null;
return this;
},
polygonStart: function() {
this._line = 0;
},
polygonEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
if (this._line === 0) this._string.push("Z");
this._point = NaN;
},
point: function(x, y) {
switch (this._point) {
case 0: {
this._string.push("M", x, ",", y);
this._point = 1;
break;
}
case 1: {
this._string.push("L", x, ",", y);
break;
}
default: {
if (this._circle == null) this._circle = string_circle(this._radius);
this._string.push("M", x, ",", y, this._circle);
break;
}
}
},
result: function() {
if (this._string.length) {
var result = this._string.join("");
this._string = [];
return result;
} else {
return null;
}
}
};
function string_circle(radius) {
return "m0," + radius
+ "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius
+ "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius
+ "z";
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/path/index.js
/* harmony default export */ var d3_geo_src_path = (function(projection, context) {
var pointRadius = 4.5,
projectionStream,
contextStream;
function path(object) {
if (object) {
if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
src_stream(object, projectionStream(contextStream));
}
return contextStream.result();
}
path.area = function(object) {
src_stream(object, projectionStream(path_area));
return path_area.result();
};
path.measure = function(object) {
src_stream(object, projectionStream(path_measure));
return path_measure.result();
};
path.bounds = function(object) {
src_stream(object, projectionStream(path_bounds));
return path_bounds.result();
};
path.centroid = function(object) {
src_stream(object, projectionStream(centroid));
return centroid.result();
};
path.projection = function(_) {
return arguments.length ? (projectionStream = _ == null ? (projection = null, d3_geo_src_identity) : (projection = _).stream, path) : projection;
};
path.context = function(_) {
if (!arguments.length) return context;
contextStream = _ == null ? (context = null, new PathString) : new context_PathContext(context = _);
if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
return path;
};
path.pointRadius = function(_) {
if (!arguments.length) return pointRadius;
pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
return path;
};
return path.projection(projection).context(context);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/buffer.js
/* harmony default export */ var clip_buffer = (function() {
var lines = [],
line;
return {
point: function(x, y) {
line.push([x, y]);
},
lineStart: function() {
lines.push(line = []);
},
lineEnd: noop_noop,
rejoin: function() {
if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
},
result: function() {
var result = lines;
lines = [];
line = null;
return result;
}
};
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/pointEqual.js
/* harmony default export */ var pointEqual = (function(a, b) {
return math_abs(a[0] - b[0]) < src_math_epsilon && math_abs(a[1] - b[1]) < src_math_epsilon;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/rejoin.js
function rejoin_Intersection(point, points, other, entry) {
this.x = point;
this.z = points;
this.o = other; // another intersection
this.e = entry; // is an entry?
this.v = false; // visited
this.n = this.p = null; // next & previous
}
// A generalized polygon clipping algorithm: given a polygon that has been cut
// into its visible line segments, and rejoins the segments by interpolating
// along the clip edge.
/* harmony default export */ var rejoin = (function(segments, compareIntersection, startInside, interpolate, stream) {
var subject = [],
clip = [],
i,
n;
segments.forEach(function(segment) {
if ((n = segment.length - 1) <= 0) return;
var n, p0 = segment[0], p1 = segment[n], x;
// If the first and last points of a segment are coincident, then treat as a
// closed ring. TODO if all rings are closed, then the winding order of the
// exterior ring should be checked.
if (pointEqual(p0, p1)) {
stream.lineStart();
for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);
stream.lineEnd();
return;
}
subject.push(x = new rejoin_Intersection(p0, segment, null, true));
clip.push(x.o = new rejoin_Intersection(p0, null, x, false));
subject.push(x = new rejoin_Intersection(p1, segment, null, false));
clip.push(x.o = new rejoin_Intersection(p1, null, x, true));
});
if (!subject.length) return;
clip.sort(compareIntersection);
rejoin_link(subject);
rejoin_link(clip);
for (i = 0, n = clip.length; i < n; ++i) {
clip[i].e = startInside = !startInside;
}
var start = subject[0],
points,
point;
while (1) {
// Find first unvisited intersection.
var current = start,
isSubject = true;
while (current.v) if ((current = current.n) === start) return;
points = current.z;
stream.lineStart();
do {
current.v = current.o.v = true;
if (current.e) {
if (isSubject) {
for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);
} else {
interpolate(current.x, current.n.x, 1, stream);
}
current = current.n;
} else {
if (isSubject) {
points = current.p.z;
for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);
} else {
interpolate(current.x, current.p.x, -1, stream);
}
current = current.p;
}
current = current.o;
points = current.z;
isSubject = !isSubject;
} while (!current.v);
stream.lineEnd();
}
});
function rejoin_link(array) {
if (!(n = array.length)) return;
var n,
i = 0,
a = array[0],
b;
while (++i < n) {
a.n = b = array[i];
b.p = a;
a = b;
}
a.n = b = array[0];
b.p = a;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/cartesian.js
function cartesian_spherical(cartesian) {
return [math_atan2(cartesian[1], cartesian[0]), math_asin(cartesian[2])];
}
function cartesian_cartesian(spherical) {
var lambda = spherical[0], phi = spherical[1], cosPhi = src_math_cos(phi);
return [cosPhi * src_math_cos(lambda), cosPhi * src_math_sin(lambda), src_math_sin(phi)];
}
function cartesian_cartesianDot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
function cartesian_cartesianCross(a, b) {
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
}
// TODO return a
function cartesian_cartesianAddInPlace(a, b) {
a[0] += b[0], a[1] += b[1], a[2] += b[2];
}
function cartesian_cartesianScale(vector, k) {
return [vector[0] * k, vector[1] * k, vector[2] * k];
}
// TODO return d
function cartesian_cartesianNormalizeInPlace(d) {
var l = src_math_sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
d[0] /= l, d[1] /= l, d[2] /= l;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/polygonContains.js
var polygonContains_sum = adder();
function polygonContains_longitude(point) {
if (math_abs(point[0]) <= math_pi)
return point[0];
else
return math_sign(point[0]) * ((math_abs(point[0]) + math_pi) % src_math_tau - math_pi);
}
/* harmony default export */ var polygonContains = (function(polygon, point) {
var lambda = polygonContains_longitude(point),
phi = point[1],
sinPhi = src_math_sin(phi),
normal = [src_math_sin(lambda), -src_math_cos(lambda), 0],
angle = 0,
winding = 0;
polygonContains_sum.reset();
if (sinPhi === 1) phi = math_halfPi + src_math_epsilon;
else if (sinPhi === -1) phi = -math_halfPi - src_math_epsilon;
for (var i = 0, n = polygon.length; i < n; ++i) {
if (!(m = (ring = polygon[i]).length)) continue;
var ring,
m,
point0 = ring[m - 1],
lambda0 = polygonContains_longitude(point0),
phi0 = point0[1] / 2 + quarterPi,
sinPhi0 = src_math_sin(phi0),
cosPhi0 = src_math_cos(phi0);
for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {
var point1 = ring[j],
lambda1 = polygonContains_longitude(point1),
phi1 = point1[1] / 2 + quarterPi,
sinPhi1 = src_math_sin(phi1),
cosPhi1 = src_math_cos(phi1),
delta = lambda1 - lambda0,
sign = delta >= 0 ? 1 : -1,
absDelta = sign * delta,
antimeridian = absDelta > math_pi,
k = sinPhi0 * sinPhi1;
polygonContains_sum.add(math_atan2(k * sign * src_math_sin(absDelta), cosPhi0 * cosPhi1 + k * src_math_cos(absDelta)));
angle += antimeridian ? delta + sign * src_math_tau : delta;
// Are the longitudes either side of the points meridian (lambda),
// and are the latitudes smaller than the parallel (phi)?
if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
var arc = cartesian_cartesianCross(cartesian_cartesian(point0), cartesian_cartesian(point1));
cartesian_cartesianNormalizeInPlace(arc);
var intersection = cartesian_cartesianCross(normal, arc);
cartesian_cartesianNormalizeInPlace(intersection);
var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * math_asin(intersection[2]);
if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
winding += antimeridian ^ delta >= 0 ? 1 : -1;
}
}
}
}
// First, determine whether the South pole is inside or outside:
//
// It is inside if:
// * the polygon winds around it in a clockwise direction.
// * the polygon does not (cumulatively) wind around it, but has a negative
// (counter-clockwise) area.
//
// Second, count the (signed) number of times a segment crosses a lambda
// from the point to the South pole. If it is zero, then the point is the
// same side as the South pole.
return (angle < -src_math_epsilon || angle < src_math_epsilon && polygonContains_sum < -src_math_epsilon) ^ (winding & 1);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/ascending.js
/* harmony default export */ var d3_array_src_ascending = (function(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/bisector.js
/* harmony default export */ var src_bisector = (function(compare) {
if (compare.length === 1) compare = src_bisector_ascendingComparator(compare);
return {
left: function(a, x, lo, hi) {
if (lo == null) lo = 0;
if (hi == null) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
},
right: function(a, x, lo, hi) {
if (lo == null) lo = 0;
if (hi == null) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) > 0) hi = mid;
else lo = mid + 1;
}
return lo;
}
};
});
function src_bisector_ascendingComparator(f) {
return function(d, x) {
return d3_array_src_ascending(f(d), x);
};
}
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/bisect.js
var src_bisect_ascendingBisect = src_bisector(d3_array_src_ascending);
var src_bisect_bisectRight = src_bisect_ascendingBisect.right;
var src_bisect_bisectLeft = src_bisect_ascendingBisect.left;
/* harmony default export */ var node_modules_d3_array_src_bisect = (src_bisect_bisectRight);
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/pairs.js
/* harmony default export */ var pairs = (function(array, f) {
if (f == null) f = pairs_pair;
var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);
while (i < n) pairs[i] = f(p, p = array[++i]);
return pairs;
});
function pairs_pair(a, b) {
return [a, b];
}
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/cross.js
/* harmony default export */ var src_cross = (function(values0, values1, reduce) {
var n0 = values0.length,
n1 = values1.length,
values = new Array(n0 * n1),
i0,
i1,
i,
value0;
if (reduce == null) reduce = pairs_pair;
for (i0 = i = 0; i0 < n0; ++i0) {
for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {
values[i] = reduce(value0, values1[i1]);
}
}
return values;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/descending.js
/* harmony default export */ var descending = (function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/number.js
/* harmony default export */ var d3_array_src_number = (function(x) {
return x === null ? NaN : +x;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/variance.js
/* harmony default export */ var src_variance = (function(values, valueof) {
var n = values.length,
m = 0,
i = -1,
mean = 0,
value,
delta,
sum = 0;
if (valueof == null) {
while (++i < n) {
if (!isNaN(value = d3_array_src_number(values[i]))) {
delta = value - mean;
mean += delta / ++m;
sum += delta * (value - mean);
}
}
}
else {
while (++i < n) {
if (!isNaN(value = d3_array_src_number(valueof(values[i], i, values)))) {
delta = value - mean;
mean += delta / ++m;
sum += delta * (value - mean);
}
}
}
if (m > 1) return sum / (m - 1);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/deviation.js
/* harmony default export */ var src_deviation = (function(array, f) {
var v = src_variance(array, f);
return v ? Math.sqrt(v) : v;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/extent.js
/* harmony default export */ var src_extent = (function(values, valueof) {
var n = values.length,
i = -1,
value,
min,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
min = max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null) {
if (min > value) min = value;
if (max < value) max = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
min = max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null) {
if (min > value) min = value;
if (max < value) max = value;
}
}
}
}
}
return [min, max];
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/array.js
var array_array = Array.prototype;
var array_slice = array_array.slice;
var array_map = array_array.map;
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/constant.js
/* harmony default export */ var d3_array_src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/identity.js
/* harmony default export */ var d3_array_src_identity = (function(x) {
return x;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/range.js
/* harmony default export */ var d3_array_src_range = (function(start, stop, step) {
start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
var i = -1,
n = Math.max(0, Math.ceil((stop - start) / step)) | 0,
range = new Array(n);
while (++i < n) {
range[i] = start + i * step;
}
return range;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/ticks.js
var ticks_e10 = Math.sqrt(50),
ticks_e5 = Math.sqrt(10),
ticks_e2 = Math.sqrt(2);
/* harmony default export */ var d3_array_src_ticks = (function(start, stop, count) {
var reverse,
i = -1,
n,
ticks,
step;
stop = +stop, start = +start, count = +count;
if (start === stop && count > 0) return [start];
if (reverse = stop < start) n = start, start = stop, stop = n;
if ((step = ticks_tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];
if (step > 0) {
start = Math.ceil(start / step);
stop = Math.floor(stop / step);
ticks = new Array(n = Math.ceil(stop - start + 1));
while (++i < n) ticks[i] = (start + i) * step;
} else {
start = Math.floor(start * step);
stop = Math.ceil(stop * step);
ticks = new Array(n = Math.ceil(start - stop + 1));
while (++i < n) ticks[i] = (start - i) / step;
}
if (reverse) ticks.reverse();
return ticks;
});
function ticks_tickIncrement(start, stop, count) {
var step = (stop - start) / Math.max(0, count),
power = Math.floor(Math.log(step) / Math.LN10),
error = step / Math.pow(10, power);
return power >= 0
? (error >= ticks_e10 ? 10 : error >= ticks_e5 ? 5 : error >= ticks_e2 ? 2 : 1) * Math.pow(10, power)
: -Math.pow(10, -power) / (error >= ticks_e10 ? 10 : error >= ticks_e5 ? 5 : error >= ticks_e2 ? 2 : 1);
}
function ticks_tickStep(start, stop, count) {
var step0 = Math.abs(stop - start) / Math.max(0, count),
step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),
error = step0 / step1;
if (error >= ticks_e10) step1 *= 10;
else if (error >= ticks_e5) step1 *= 5;
else if (error >= ticks_e2) step1 *= 2;
return stop < start ? -step1 : step1;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/threshold/sturges.js
/* harmony default export */ var sturges = (function(values) {
return Math.ceil(Math.log(values.length) / Math.LN2) + 1;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/histogram.js
/* harmony default export */ var src_histogram = (function() {
var value = d3_array_src_identity,
domain = src_extent,
threshold = sturges;
function histogram(data) {
var i,
n = data.length,
x,
values = new Array(n);
for (i = 0; i < n; ++i) {
values[i] = value(data[i], i, data);
}
var xz = domain(values),
x0 = xz[0],
x1 = xz[1],
tz = threshold(values, x0, x1);
// Convert number of thresholds into uniform thresholds.
if (!Array.isArray(tz)) {
tz = ticks_tickStep(x0, x1, tz);
tz = d3_array_src_range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive
}
// Remove any thresholds outside the domain.
var m = tz.length;
while (tz[0] <= x0) tz.shift(), --m;
while (tz[m - 1] > x1) tz.pop(), --m;
var bins = new Array(m + 1),
bin;
// Initialize bins.
for (i = 0; i <= m; ++i) {
bin = bins[i] = [];
bin.x0 = i > 0 ? tz[i - 1] : x0;
bin.x1 = i < m ? tz[i] : x1;
}
// Assign data to bins by value, ignoring any outside the domain.
for (i = 0; i < n; ++i) {
x = values[i];
if (x0 <= x && x <= x1) {
bins[node_modules_d3_array_src_bisect(tz, x, 0, m)].push(data[i]);
}
}
return bins;
}
histogram.value = function(_) {
return arguments.length ? (value = typeof _ === "function" ? _ : d3_array_src_constant(_), histogram) : value;
};
histogram.domain = function(_) {
return arguments.length ? (domain = typeof _ === "function" ? _ : d3_array_src_constant([_[0], _[1]]), histogram) : domain;
};
histogram.thresholds = function(_) {
return arguments.length ? (threshold = typeof _ === "function" ? _ : Array.isArray(_) ? d3_array_src_constant(array_slice.call(_)) : d3_array_src_constant(_), histogram) : threshold;
};
return histogram;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/quantile.js
/* harmony default export */ var src_quantile = (function(values, p, valueof) {
if (valueof == null) valueof = d3_array_src_number;
if (!(n = values.length)) return;
if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);
if (p >= 1) return +valueof(values[n - 1], n - 1, values);
var n,
i = (n - 1) * p,
i0 = Math.floor(i),
value0 = +valueof(values[i0], i0, values),
value1 = +valueof(values[i0 + 1], i0 + 1, values);
return value0 + (value1 - value0) * (i - i0);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/threshold/freedmanDiaconis.js
/* harmony default export */ var freedmanDiaconis = (function(values, min, max) {
values = array_map.call(values, d3_array_src_number).sort(d3_array_src_ascending);
return Math.ceil((max - min) / (2 * (src_quantile(values, 0.75) - src_quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/threshold/scott.js
/* harmony default export */ var scott = (function(values, min, max) {
return Math.ceil((max - min) / (3.5 * src_deviation(values) * Math.pow(values.length, -1 / 3)));
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/max.js
/* harmony default export */ var src_max = (function(values, valueof) {
var n = values.length,
i = -1,
value,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && value > max) {
max = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && value > max) {
max = value;
}
}
}
}
}
return max;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/mean.js
/* harmony default export */ var src_mean = (function(values, valueof) {
var n = values.length,
m = n,
i = -1,
value,
sum = 0;
if (valueof == null) {
while (++i < n) {
if (!isNaN(value = d3_array_src_number(values[i]))) sum += value;
else --m;
}
}
else {
while (++i < n) {
if (!isNaN(value = d3_array_src_number(valueof(values[i], i, values)))) sum += value;
else --m;
}
}
if (m) return sum / m;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/median.js
/* harmony default export */ var src_median = (function(values, valueof) {
var n = values.length,
i = -1,
value,
numbers = [];
if (valueof == null) {
while (++i < n) {
if (!isNaN(value = d3_array_src_number(values[i]))) {
numbers.push(value);
}
}
}
else {
while (++i < n) {
if (!isNaN(value = d3_array_src_number(valueof(values[i], i, values)))) {
numbers.push(value);
}
}
}
return src_quantile(numbers.sort(d3_array_src_ascending), 0.5);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/merge.js
/* harmony default export */ var d3_array_src_merge = (function(arrays) {
var n = arrays.length,
m,
i = -1,
j = 0,
merged,
array;
while (++i < n) j += arrays[i].length;
merged = new Array(j);
while (--n >= 0) {
array = arrays[n];
m = array.length;
while (--m >= 0) {
merged[--j] = array[m];
}
}
return merged;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/min.js
/* harmony default export */ var src_min = (function(values, valueof) {
var n = values.length,
i = -1,
value,
min;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
min = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && min > value) {
min = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
min = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && min > value) {
min = value;
}
}
}
}
}
return min;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/permute.js
/* harmony default export */ var permute = (function(array, indexes) {
var i = indexes.length, permutes = new Array(i);
while (i--) permutes[i] = array[indexes[i]];
return permutes;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/scan.js
/* harmony default export */ var scan = (function(values, compare) {
if (!(n = values.length)) return;
var n,
i = 0,
j = 0,
xi,
xj = values[j];
if (compare == null) compare = d3_array_src_ascending;
while (++i < n) {
if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {
xj = xi, j = i;
}
}
if (compare(xj, xj) === 0) return j;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/shuffle.js
/* harmony default export */ var shuffle = (function(array, i0, i1) {
var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),
t,
i;
while (m) {
i = Math.random() * m-- | 0;
t = array[m + i0];
array[m + i0] = array[i + i0];
array[i + i0] = t;
}
return array;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/sum.js
/* harmony default export */ var src_sum = (function(values, valueof) {
var n = values.length,
i = -1,
value,
sum = 0;
if (valueof == null) {
while (++i < n) {
if (value = +values[i]) sum += value; // Note: zero and null are equivalent.
}
}
else {
while (++i < n) {
if (value = +valueof(values[i], i, values)) sum += value;
}
}
return sum;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/transpose.js
/* harmony default export */ var src_transpose = (function(matrix) {
if (!(n = matrix.length)) return [];
for (var i = -1, m = src_min(matrix, transpose_length), transpose = new Array(m); ++i < m;) {
for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {
row[j] = matrix[j][i];
}
}
return transpose;
});
function transpose_length(d) {
return d.length;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/zip.js
/* harmony default export */ var zip = (function() {
return src_transpose(arguments);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/node_modules/d3-array/src/index.js
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/index.js
/* harmony default export */ var src_clip = (function(pointVisible, clipLine, interpolate, start) {
return function(sink) {
var line = clipLine(sink),
ringBuffer = clip_buffer(),
ringSink = clipLine(ringBuffer),
polygonStarted = false,
polygon,
segments,
ring;
var clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
clip.point = pointRing;
clip.lineStart = ringStart;
clip.lineEnd = ringEnd;
segments = [];
polygon = [];
},
polygonEnd: function() {
clip.point = point;
clip.lineStart = lineStart;
clip.lineEnd = lineEnd;
segments = d3_array_src_merge(segments);
var startInside = polygonContains(polygon, start);
if (segments.length) {
if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
rejoin(segments, clip_compareIntersection, startInside, interpolate, sink);
} else if (startInside) {
if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
sink.lineStart();
interpolate(null, null, 1, sink);
sink.lineEnd();
}
if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
segments = polygon = null;
},
sphere: function() {
sink.polygonStart();
sink.lineStart();
interpolate(null, null, 1, sink);
sink.lineEnd();
sink.polygonEnd();
}
};
function point(lambda, phi) {
if (pointVisible(lambda, phi)) sink.point(lambda, phi);
}
function pointLine(lambda, phi) {
line.point(lambda, phi);
}
function lineStart() {
clip.point = pointLine;
line.lineStart();
}
function lineEnd() {
clip.point = point;
line.lineEnd();
}
function pointRing(lambda, phi) {
ring.push([lambda, phi]);
ringSink.point(lambda, phi);
}
function ringStart() {
ringSink.lineStart();
ring = [];
}
function ringEnd() {
pointRing(ring[0][0], ring[0][1]);
ringSink.lineEnd();
var clean = ringSink.clean(),
ringSegments = ringBuffer.result(),
i, n = ringSegments.length, m,
segment,
point;
ring.pop();
polygon.push(ring);
ring = null;
if (!n) return;
// No intersections.
if (clean & 1) {
segment = ringSegments[0];
if ((m = segment.length - 1) > 0) {
if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
sink.lineStart();
for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);
sink.lineEnd();
}
return;
}
// Rejoin connected segments.
// TODO reuse ringBuffer.rejoin()?
if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
segments.push(ringSegments.filter(clip_validSegment));
}
return clip;
};
});
function clip_validSegment(segment) {
return segment.length > 1;
}
// Intersections are sorted along the clip edge. For both antimeridian cutting
// and circle clipping, the same comparison is used.
function clip_compareIntersection(a, b) {
return ((a = a.x)[0] < 0 ? a[1] - math_halfPi - src_math_epsilon : math_halfPi - a[1])
- ((b = b.x)[0] < 0 ? b[1] - math_halfPi - src_math_epsilon : math_halfPi - b[1]);
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/antimeridian.js
/* harmony default export */ var clip_antimeridian = (src_clip(
function() { return true; },
antimeridian_clipAntimeridianLine,
antimeridian_clipAntimeridianInterpolate,
[-math_pi, -math_halfPi]
));
// Takes a line and cuts into visible segments. Return values: 0 - there were
// intersections or the line was empty; 1 - no intersections; 2 - there were
// intersections, and the first and last segments should be rejoined.
function antimeridian_clipAntimeridianLine(stream) {
var lambda0 = NaN,
phi0 = NaN,
sign0 = NaN,
clean; // no intersections
return {
lineStart: function() {
stream.lineStart();
clean = 1;
},
point: function(lambda1, phi1) {
var sign1 = lambda1 > 0 ? math_pi : -math_pi,
delta = math_abs(lambda1 - lambda0);
if (math_abs(delta - math_pi) < src_math_epsilon) { // line crosses a pole
stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? math_halfPi : -math_halfPi);
stream.point(sign0, phi0);
stream.lineEnd();
stream.lineStart();
stream.point(sign1, phi0);
stream.point(lambda1, phi0);
clean = 0;
} else if (sign0 !== sign1 && delta >= math_pi) { // line crosses antimeridian
if (math_abs(lambda0 - sign0) < src_math_epsilon) lambda0 -= sign0 * src_math_epsilon; // handle degeneracies
if (math_abs(lambda1 - sign1) < src_math_epsilon) lambda1 -= sign1 * src_math_epsilon;
phi0 = antimeridian_clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);
stream.point(sign0, phi0);
stream.lineEnd();
stream.lineStart();
stream.point(sign1, phi0);
clean = 0;
}
stream.point(lambda0 = lambda1, phi0 = phi1);
sign0 = sign1;
},
lineEnd: function() {
stream.lineEnd();
lambda0 = phi0 = NaN;
},
clean: function() {
return 2 - clean; // if intersections, rejoin first and last segments
}
};
}
function antimeridian_clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {
var cosPhi0,
cosPhi1,
sinLambda0Lambda1 = src_math_sin(lambda0 - lambda1);
return math_abs(sinLambda0Lambda1) > src_math_epsilon
? atan((src_math_sin(phi0) * (cosPhi1 = src_math_cos(phi1)) * src_math_sin(lambda1)
- src_math_sin(phi1) * (cosPhi0 = src_math_cos(phi0)) * src_math_sin(lambda0))
/ (cosPhi0 * cosPhi1 * sinLambda0Lambda1))
: (phi0 + phi1) / 2;
}
function antimeridian_clipAntimeridianInterpolate(from, to, direction, stream) {
var phi;
if (from == null) {
phi = direction * math_halfPi;
stream.point(-math_pi, phi);
stream.point(0, phi);
stream.point(math_pi, phi);
stream.point(math_pi, 0);
stream.point(math_pi, -phi);
stream.point(0, -phi);
stream.point(-math_pi, -phi);
stream.point(-math_pi, 0);
stream.point(-math_pi, phi);
} else if (math_abs(from[0] - to[0]) > src_math_epsilon) {
var lambda = from[0] < to[0] ? math_pi : -math_pi;
phi = direction * lambda / 2;
stream.point(-lambda, phi);
stream.point(0, phi);
stream.point(lambda, phi);
} else {
stream.point(to[0], to[1]);
}
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/constant.js
/* harmony default export */ var d3_geo_src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/compose.js
/* harmony default export */ var compose = (function(a, b) {
function compose(x, y) {
return x = a(x, y), b(x[0], x[1]);
}
if (a.invert && b.invert) compose.invert = function(x, y) {
return x = b.invert(x, y), x && a.invert(x[0], x[1]);
};
return compose;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/rotation.js
function rotation_rotationIdentity(lambda, phi) {
return [math_abs(lambda) > math_pi ? lambda + Math.round(-lambda / src_math_tau) * src_math_tau : lambda, phi];
}
rotation_rotationIdentity.invert = rotation_rotationIdentity;
function rotation_rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
return (deltaLambda %= src_math_tau) ? (deltaPhi || deltaGamma ? compose(rotation_rotationLambda(deltaLambda), rotation_rotationPhiGamma(deltaPhi, deltaGamma))
: rotation_rotationLambda(deltaLambda))
: (deltaPhi || deltaGamma ? rotation_rotationPhiGamma(deltaPhi, deltaGamma)
: rotation_rotationIdentity);
}
function rotation_forwardRotationLambda(deltaLambda) {
return function(lambda, phi) {
return lambda += deltaLambda, [lambda > math_pi ? lambda - src_math_tau : lambda < -math_pi ? lambda + src_math_tau : lambda, phi];
};
}
function rotation_rotationLambda(deltaLambda) {
var rotation = rotation_forwardRotationLambda(deltaLambda);
rotation.invert = rotation_forwardRotationLambda(-deltaLambda);
return rotation;
}
function rotation_rotationPhiGamma(deltaPhi, deltaGamma) {
var cosDeltaPhi = src_math_cos(deltaPhi),
sinDeltaPhi = src_math_sin(deltaPhi),
cosDeltaGamma = src_math_cos(deltaGamma),
sinDeltaGamma = src_math_sin(deltaGamma);
function rotation(lambda, phi) {
var cosPhi = src_math_cos(phi),
x = src_math_cos(lambda) * cosPhi,
y = src_math_sin(lambda) * cosPhi,
z = src_math_sin(phi),
k = z * cosDeltaPhi + x * sinDeltaPhi;
return [
math_atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),
math_asin(k * cosDeltaGamma + y * sinDeltaGamma)
];
}
rotation.invert = function(lambda, phi) {
var cosPhi = src_math_cos(phi),
x = src_math_cos(lambda) * cosPhi,
y = src_math_sin(lambda) * cosPhi,
z = src_math_sin(phi),
k = z * cosDeltaGamma - y * sinDeltaGamma;
return [
math_atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),
math_asin(k * cosDeltaPhi - x * sinDeltaPhi)
];
};
return rotation;
}
/* harmony default export */ var src_rotation = (function(rotate) {
rotate = rotation_rotateRadians(rotate[0] * radians, rotate[1] * radians, rotate.length > 2 ? rotate[2] * radians : 0);
function forward(coordinates) {
coordinates = rotate(coordinates[0] * radians, coordinates[1] * radians);
return coordinates[0] *= math_degrees, coordinates[1] *= math_degrees, coordinates;
}
forward.invert = function(coordinates) {
coordinates = rotate.invert(coordinates[0] * radians, coordinates[1] * radians);
return coordinates[0] *= math_degrees, coordinates[1] *= math_degrees, coordinates;
};
return forward;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/circle.js
// Generates a circle centered at [0°, 0°], with a given radius and precision.
function circle_circleStream(stream, radius, delta, direction, t0, t1) {
if (!delta) return;
var cosRadius = src_math_cos(radius),
sinRadius = src_math_sin(radius),
step = direction * delta;
if (t0 == null) {
t0 = radius + direction * src_math_tau;
t1 = radius - step / 2;
} else {
t0 = circle_circleRadius(cosRadius, t0);
t1 = circle_circleRadius(cosRadius, t1);
if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * src_math_tau;
}
for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {
point = cartesian_spherical([cosRadius, -sinRadius * src_math_cos(t), -sinRadius * src_math_sin(t)]);
stream.point(point[0], point[1]);
}
}
// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].
function circle_circleRadius(cosRadius, point) {
point = cartesian_cartesian(point), point[0] -= cosRadius;
cartesian_cartesianNormalizeInPlace(point);
var radius = math_acos(-point[1]);
return ((-point[2] < 0 ? -radius : radius) + src_math_tau - src_math_epsilon) % src_math_tau;
}
/* harmony default export */ var src_circle = (function() {
var center = d3_geo_src_constant([0, 0]),
radius = d3_geo_src_constant(90),
precision = d3_geo_src_constant(6),
ring,
rotate,
stream = {point: point};
function point(x, y) {
ring.push(x = rotate(x, y));
x[0] *= math_degrees, x[1] *= math_degrees;
}
function circle() {
var c = center.apply(this, arguments),
r = radius.apply(this, arguments) * radians,
p = precision.apply(this, arguments) * radians;
ring = [];
rotate = rotation_rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;
circle_circleStream(stream, r, p, 1);
c = {type: "Polygon", coordinates: [ring]};
ring = rotate = null;
return c;
}
circle.center = function(_) {
return arguments.length ? (center = typeof _ === "function" ? _ : d3_geo_src_constant([+_[0], +_[1]]), circle) : center;
};
circle.radius = function(_) {
return arguments.length ? (radius = typeof _ === "function" ? _ : d3_geo_src_constant(+_), circle) : radius;
};
circle.precision = function(_) {
return arguments.length ? (precision = typeof _ === "function" ? _ : d3_geo_src_constant(+_), circle) : precision;
};
return circle;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/circle.js
/* harmony default export */ var clip_circle = (function(radius) {
var cr = src_math_cos(radius),
delta = 6 * radians,
smallRadius = cr > 0,
notHemisphere = math_abs(cr) > src_math_epsilon; // TODO optimise for this common case
function interpolate(from, to, direction, stream) {
circle_circleStream(stream, radius, delta, direction, from, to);
}
function visible(lambda, phi) {
return src_math_cos(lambda) * src_math_cos(phi) > cr;
}
// Takes a line and cuts into visible segments. Return values used for polygon
// clipping: 0 - there were intersections or the line was empty; 1 - no
// intersections 2 - there were intersections, and the first and last segments
// should be rejoined.
function clipLine(stream) {
var point0, // previous point
c0, // code for previous point
v0, // visibility of previous point
v00, // visibility of first point
clean; // no intersections
return {
lineStart: function() {
v00 = v0 = false;
clean = 1;
},
point: function(lambda, phi) {
var point1 = [lambda, phi],
point2,
v = visible(lambda, phi),
c = smallRadius
? v ? 0 : code(lambda, phi)
: v ? code(lambda + (lambda < 0 ? math_pi : -math_pi), phi) : 0;
if (!point0 && (v00 = v0 = v)) stream.lineStart();
// Handle degeneracies.
// TODO ignore if not clipping polygons.
if (v !== v0) {
point2 = intersect(point0, point1);
if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2)) {
point1[0] += src_math_epsilon;
point1[1] += src_math_epsilon;
v = visible(point1[0], point1[1]);
}
}
if (v !== v0) {
clean = 0;
if (v) {
// outside going in
stream.lineStart();
point2 = intersect(point1, point0);
stream.point(point2[0], point2[1]);
} else {
// inside going out
point2 = intersect(point0, point1);
stream.point(point2[0], point2[1]);
stream.lineEnd();
}
point0 = point2;
} else if (notHemisphere && point0 && smallRadius ^ v) {
var t;
// If the codes for two points are different, or are both zero,
// and there this segment intersects with the small circle.
if (!(c & c0) && (t = intersect(point1, point0, true))) {
clean = 0;
if (smallRadius) {
stream.lineStart();
stream.point(t[0][0], t[0][1]);
stream.point(t[1][0], t[1][1]);
stream.lineEnd();
} else {
stream.point(t[1][0], t[1][1]);
stream.lineEnd();
stream.lineStart();
stream.point(t[0][0], t[0][1]);
}
}
}
if (v && (!point0 || !pointEqual(point0, point1))) {
stream.point(point1[0], point1[1]);
}
point0 = point1, v0 = v, c0 = c;
},
lineEnd: function() {
if (v0) stream.lineEnd();
point0 = null;
},
// Rejoin first and last segments if there were intersections and the first
// and last points were visible.
clean: function() {
return clean | ((v00 && v0) << 1);
}
};
}
// Intersects the great circle between a and b with the clip circle.
function intersect(a, b, two) {
var pa = cartesian_cartesian(a),
pb = cartesian_cartesian(b);
// We have two planes, n1.p = d1 and n2.p = d2.
// Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 n2).
var n1 = [1, 0, 0], // normal
n2 = cartesian_cartesianCross(pa, pb),
n2n2 = cartesian_cartesianDot(n2, n2),
n1n2 = n2[0], // cartesianDot(n1, n2),
determinant = n2n2 - n1n2 * n1n2;
// Two polar points.
if (!determinant) return !two && a;
var c1 = cr * n2n2 / determinant,
c2 = -cr * n1n2 / determinant,
n1xn2 = cartesian_cartesianCross(n1, n2),
A = cartesian_cartesianScale(n1, c1),
B = cartesian_cartesianScale(n2, c2);
cartesian_cartesianAddInPlace(A, B);
// Solve |p(t)|^2 = 1.
var u = n1xn2,
w = cartesian_cartesianDot(A, u),
uu = cartesian_cartesianDot(u, u),
t2 = w * w - uu * (cartesian_cartesianDot(A, A) - 1);
if (t2 < 0) return;
var t = src_math_sqrt(t2),
q = cartesian_cartesianScale(u, (-w - t) / uu);
cartesian_cartesianAddInPlace(q, A);
q = cartesian_spherical(q);
if (!two) return q;
// Two intersection points.
var lambda0 = a[0],
lambda1 = b[0],
phi0 = a[1],
phi1 = b[1],
z;
if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;
var delta = lambda1 - lambda0,
polar = math_abs(delta - math_pi) < src_math_epsilon,
meridian = polar || delta < src_math_epsilon;
if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;
// Check that the first point is between a and b.
if (meridian
? polar
? phi0 + phi1 > 0 ^ q[1] < (math_abs(q[0] - lambda0) < src_math_epsilon ? phi0 : phi1)
: phi0 <= q[1] && q[1] <= phi1
: delta > math_pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
var q1 = cartesian_cartesianScale(u, (-w + t) / uu);
cartesian_cartesianAddInPlace(q1, A);
return [q, cartesian_spherical(q1)];
}
}
// Generates a 4-bit vector representing the location of a point relative to
// the small circle's bounding box.
function code(lambda, phi) {
var r = smallRadius ? radius : math_pi - radius,
code = 0;
if (lambda < -r) code |= 1; // left
else if (lambda > r) code |= 2; // right
if (phi < -r) code |= 4; // below
else if (phi > r) code |= 8; // above
return code;
}
return src_clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-math_pi, radius - math_pi]);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/line.js
/* harmony default export */ var clip_line = (function(a, b, x0, y0, x1, y1) {
var ax = a[0],
ay = a[1],
bx = b[0],
by = b[1],
t0 = 0,
t1 = 1,
dx = bx - ax,
dy = by - ay,
r;
r = x0 - ax;
if (!dx && r > 0) return;
r /= dx;
if (dx < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dx > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = x1 - ax;
if (!dx && r < 0) return;
r /= dx;
if (dx < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dx > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
r = y0 - ay;
if (!dy && r > 0) return;
r /= dy;
if (dy < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dy > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = y1 - ay;
if (!dy && r < 0) return;
r /= dy;
if (dy < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dy > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;
if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;
return true;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/clip/rectangle.js
var rectangle_clipMax = 1e9, rectangle_clipMin = -rectangle_clipMax;
// TODO Use d3-polygons polygonContains here for the ring check?
// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?
function rectangle_clipRectangle(x0, y0, x1, y1) {
function visible(x, y) {
return x0 <= x && x <= x1 && y0 <= y && y <= y1;
}
function interpolate(from, to, direction, stream) {
var a = 0, a1 = 0;
if (from == null
|| (a = corner(from, direction)) !== (a1 = corner(to, direction))
|| comparePoint(from, to) < 0 ^ direction > 0) {
do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
while ((a = (a + direction + 4) % 4) !== a1);
} else {
stream.point(to[0], to[1]);
}
}
function corner(p, direction) {
return math_abs(p[0] - x0) < src_math_epsilon ? direction > 0 ? 0 : 3
: math_abs(p[0] - x1) < src_math_epsilon ? direction > 0 ? 2 : 1
: math_abs(p[1] - y0) < src_math_epsilon ? direction > 0 ? 1 : 0
: direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon
}
function compareIntersection(a, b) {
return comparePoint(a.x, b.x);
}
function comparePoint(a, b) {
var ca = corner(a, 1),
cb = corner(b, 1);
return ca !== cb ? ca - cb
: ca === 0 ? b[1] - a[1]
: ca === 1 ? a[0] - b[0]
: ca === 2 ? a[1] - b[1]
: b[0] - a[0];
}
return function(stream) {
var activeStream = stream,
bufferStream = clip_buffer(),
segments,
polygon,
ring,
x__, y__, v__, // first point
x_, y_, v_, // previous point
first,
clean;
var clipStream = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: polygonStart,
polygonEnd: polygonEnd
};
function point(x, y) {
if (visible(x, y)) activeStream.point(x, y);
}
function polygonInside() {
var winding = 0;
for (var i = 0, n = polygon.length; i < n; ++i) {
for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {
a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];
if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }
else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }
}
}
return winding;
}
// Buffer geometry within a polygon and then clip it en masse.
function polygonStart() {
activeStream = bufferStream, segments = [], polygon = [], clean = true;
}
function polygonEnd() {
var startInside = polygonInside(),
cleanInside = clean && startInside,
visible = (segments = d3_array_src_merge(segments)).length;
if (cleanInside || visible) {
stream.polygonStart();
if (cleanInside) {
stream.lineStart();
interpolate(null, null, 1, stream);
stream.lineEnd();
}
if (visible) {
rejoin(segments, compareIntersection, startInside, interpolate, stream);
}
stream.polygonEnd();
}
activeStream = stream, segments = polygon = ring = null;
}
function lineStart() {
clipStream.point = linePoint;
if (polygon) polygon.push(ring = []);
first = true;
v_ = false;
x_ = y_ = NaN;
}
// TODO rather than special-case polygons, simply handle them separately.
// Ideally, coincident intersection points should be jittered to avoid
// clipping issues.
function lineEnd() {
if (segments) {
linePoint(x__, y__);
if (v__ && v_) bufferStream.rejoin();
segments.push(bufferStream.result());
}
clipStream.point = point;
if (v_) activeStream.lineEnd();
}
function linePoint(x, y) {
var v = visible(x, y);
if (polygon) ring.push([x, y]);
if (first) {
x__ = x, y__ = y, v__ = v;
first = false;
if (v) {
activeStream.lineStart();
activeStream.point(x, y);
}
} else {
if (v && v_) activeStream.point(x, y);
else {
var a = [x_ = Math.max(rectangle_clipMin, Math.min(rectangle_clipMax, x_)), y_ = Math.max(rectangle_clipMin, Math.min(rectangle_clipMax, y_))],
b = [x = Math.max(rectangle_clipMin, Math.min(rectangle_clipMax, x)), y = Math.max(rectangle_clipMin, Math.min(rectangle_clipMax, y))];
if (clip_line(a, b, x0, y0, x1, y1)) {
if (!v_) {
activeStream.lineStart();
activeStream.point(a[0], a[1]);
}
activeStream.point(b[0], b[1]);
if (!v) activeStream.lineEnd();
clean = false;
} else if (v) {
activeStream.lineStart();
activeStream.point(x, y);
clean = false;
}
}
}
x_ = x, y_ = y, v_ = v;
}
return clipStream;
};
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/transform.js
/* harmony default export */ var d3_geo_src_transform = (function(methods) {
return {
stream: transform_transformer(methods)
};
});
function transform_transformer(methods) {
return function(stream) {
var s = new TransformStream;
for (var key in methods) s[key] = methods[key];
s.stream = stream;
return s;
};
}
function TransformStream() {}
TransformStream.prototype = {
constructor: TransformStream,
point: function(x, y) { this.stream.point(x, y); },
sphere: function() { this.stream.sphere(); },
lineStart: function() { this.stream.lineStart(); },
lineEnd: function() { this.stream.lineEnd(); },
polygonStart: function() { this.stream.polygonStart(); },
polygonEnd: function() { this.stream.polygonEnd(); }
};
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/fit.js
function fit_fit(projection, fitBounds, object) {
var clip = projection.clipExtent && projection.clipExtent();
projection.scale(150).translate([0, 0]);
if (clip != null) projection.clipExtent(null);
src_stream(object, projection.stream(path_bounds));
fitBounds(path_bounds.result());
if (clip != null) projection.clipExtent(clip);
return projection;
}
function fit_fitExtent(projection, extent, object) {
return fit_fit(projection, function(b) {
var w = extent[1][0] - extent[0][0],
h = extent[1][1] - extent[0][1],
k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),
x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,
y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
projection.scale(150 * k).translate([x, y]);
}, object);
}
function fit_fitSize(projection, size, object) {
return fit_fitExtent(projection, [[0, 0], size], object);
}
function fit_fitWidth(projection, width, object) {
return fit_fit(projection, function(b) {
var w = +width,
k = w / (b[1][0] - b[0][0]),
x = (w - k * (b[1][0] + b[0][0])) / 2,
y = -k * b[0][1];
projection.scale(150 * k).translate([x, y]);
}, object);
}
function fit_fitHeight(projection, height, object) {
return fit_fit(projection, function(b) {
var h = +height,
k = h / (b[1][1] - b[0][1]),
x = -k * b[0][0],
y = (h - k * (b[1][1] + b[0][1])) / 2;
projection.scale(150 * k).translate([x, y]);
}, object);
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/resample.js
var resample_maxDepth = 16, // maximum depth of subdivision
resample_cosMinDistance = src_math_cos(30 * radians); // cos(minimum angular distance)
/* harmony default export */ var projection_resample = (function(project, delta2) {
return +delta2 ? resample_resample(project, delta2) : resample_resampleNone(project);
});
function resample_resampleNone(project) {
return transform_transformer({
point: function(x, y) {
x = project(x, y);
this.stream.point(x[0], x[1]);
}
});
}
function resample_resample(project, delta2) {
function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {
var dx = x1 - x0,
dy = y1 - y0,
d2 = dx * dx + dy * dy;
if (d2 > 4 * delta2 && depth--) {
var a = a0 + a1,
b = b0 + b1,
c = c0 + c1,
m = src_math_sqrt(a * a + b * b + c * c),
phi2 = math_asin(c /= m),
lambda2 = math_abs(math_abs(c) - 1) < src_math_epsilon || math_abs(lambda0 - lambda1) < src_math_epsilon ? (lambda0 + lambda1) / 2 : math_atan2(b, a),
p = project(lambda2, phi2),
x2 = p[0],
y2 = p[1],
dx2 = x2 - x0,
dy2 = y2 - y0,
dz = dy * dx2 - dx * dy2;
if (dz * dz / d2 > delta2 // perpendicular projected distance
|| math_abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end
|| a0 * a1 + b0 * b1 + c0 * c1 < resample_cosMinDistance) { // angular distance
resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);
stream.point(x2, y2);
resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);
}
}
}
return function(stream) {
var lambda00, x00, y00, a00, b00, c00, // first point
lambda0, x0, y0, a0, b0, c0; // previous point
var resampleStream = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },
polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }
};
function point(x, y) {
x = project(x, y);
stream.point(x[0], x[1]);
}
function lineStart() {
x0 = NaN;
resampleStream.point = linePoint;
stream.lineStart();
}
function linePoint(lambda, phi) {
var c = cartesian_cartesian([lambda, phi]), p = project(lambda, phi);
resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], resample_maxDepth, stream);
stream.point(x0, y0);
}
function lineEnd() {
resampleStream.point = point;
stream.lineEnd();
}
function ringStart() {
lineStart();
resampleStream.point = ringPoint;
resampleStream.lineEnd = ringEnd;
}
function ringPoint(lambda, phi) {
linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
resampleStream.point = linePoint;
}
function ringEnd() {
resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, resample_maxDepth, stream);
resampleStream.lineEnd = lineEnd;
lineEnd();
}
return resampleStream;
};
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/index.js
var projection_transformRadians = transform_transformer({
point: function(x, y) {
this.stream.point(x * radians, y * radians);
}
});
function projection_transformRotate(rotate) {
return transform_transformer({
point: function(x, y) {
var r = rotate(x, y);
return this.stream.point(r[0], r[1]);
}
});
}
function projection_scaleTranslate(k, dx, dy) {
function transform(x, y) {
return [dx + k * x, dy - k * y];
}
transform.invert = function(x, y) {
return [(x - dx) / k, (dy - y) / k];
};
return transform;
}
function projection_scaleTranslateRotate(k, dx, dy, alpha) {
var cosAlpha = src_math_cos(alpha),
sinAlpha = src_math_sin(alpha),
a = cosAlpha * k,
b = sinAlpha * k,
ai = cosAlpha / k,
bi = sinAlpha / k,
ci = (sinAlpha * dy - cosAlpha * dx) / k,
fi = (sinAlpha * dx + cosAlpha * dy) / k;
function transform(x, y) {
return [a * x - b * y + dx, dy - b * x - a * y];
}
transform.invert = function(x, y) {
return [ai * x - bi * y + ci, fi - bi * x - ai * y];
};
return transform;
}
function projection_projection(project) {
return projection_projectionMutator(function() { return project; })();
}
function projection_projectionMutator(projectAt) {
var project,
k = 150, // scale
x = 480, y = 250, // translate
lambda = 0, phi = 0, // center
deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, // pre-rotate
alpha = 0, // post-rotate
theta = null, preclip = clip_antimeridian, // pre-clip angle
x0 = null, y0, x1, y1, postclip = d3_geo_src_identity, // post-clip extent
delta2 = 0.5, // precision
projectResample,
projectTransform,
projectRotateTransform,
cache,
cacheStream;
function projection(point) {
return projectRotateTransform(point[0] * radians, point[1] * radians);
}
function invert(point) {
point = projectRotateTransform.invert(point[0], point[1]);
return point && [point[0] * math_degrees, point[1] * math_degrees];
}
projection.stream = function(stream) {
return cache && cacheStream === stream ? cache : cache = projection_transformRadians(projection_transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));
};
projection.preclip = function(_) {
return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;
};
projection.postclip = function(_) {
return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
};
projection.clipAngle = function(_) {
return arguments.length ? (preclip = +_ ? clip_circle(theta = _ * radians) : (theta = null, clip_antimeridian), reset()) : theta * math_degrees;
};
projection.clipExtent = function(_) {
return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, d3_geo_src_identity) : rectangle_clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
};
projection.scale = function(_) {
return arguments.length ? (k = +_, recenter()) : k;
};
projection.translate = function(_) {
return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];
};
projection.center = function(_) {
return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * math_degrees, phi * math_degrees];
};
projection.rotate = function(_) {
return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * math_degrees, deltaPhi * math_degrees, deltaGamma * math_degrees];
};
projection.angle = function(_) {
return arguments.length ? (alpha = _ % 360 * radians, recenter()) : alpha * math_degrees;
};
projection.precision = function(_) {
return arguments.length ? (projectResample = projection_resample(projectTransform, delta2 = _ * _), reset()) : src_math_sqrt(delta2);
};
projection.fitExtent = function(extent, object) {
return fit_fitExtent(projection, extent, object);
};
projection.fitSize = function(size, object) {
return fit_fitSize(projection, size, object);
};
projection.fitWidth = function(width, object) {
return fit_fitWidth(projection, width, object);
};
projection.fitHeight = function(height, object) {
return fit_fitHeight(projection, height, object);
};
function recenter() {
var center = projection_scaleTranslateRotate(k, 0, 0, alpha).apply(null, project(lambda, phi)),
transform = (alpha ? projection_scaleTranslateRotate : projection_scaleTranslate)(k, x - center[0], y - center[1], alpha);
rotate = rotation_rotateRadians(deltaLambda, deltaPhi, deltaGamma);
projectTransform = compose(project, transform);
projectRotateTransform = compose(rotate, projectTransform);
projectResample = projection_resample(projectTransform, delta2);
return reset();
}
function reset() {
cache = cacheStream = null;
return projection;
}
return function() {
project = projectAt.apply(this, arguments);
projection.invert = project.invert && invert;
return recenter();
};
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/conic.js
function conic_conicProjection(projectAt) {
var phi0 = 0,
phi1 = math_pi / 3,
m = projection_projectionMutator(projectAt),
p = m(phi0, phi1);
p.parallels = function(_) {
return arguments.length ? m(phi0 = _[0] * radians, phi1 = _[1] * radians) : [phi0 * math_degrees, phi1 * math_degrees];
};
return p;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/cylindricalEqualArea.js
function cylindricalEqualArea_cylindricalEqualAreaRaw(phi0) {
var cosPhi0 = src_math_cos(phi0);
function forward(lambda, phi) {
return [lambda * cosPhi0, src_math_sin(phi) / cosPhi0];
}
forward.invert = function(x, y) {
return [x / cosPhi0, math_asin(y * cosPhi0)];
};
return forward;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/conicEqualArea.js
function conicEqualArea_conicEqualAreaRaw(y0, y1) {
var sy0 = src_math_sin(y0), n = (sy0 + src_math_sin(y1)) / 2;
// Are the parallels symmetrical around the Equator?
if (math_abs(n) < src_math_epsilon) return cylindricalEqualArea_cylindricalEqualAreaRaw(y0);
var c = 1 + sy0 * (2 * n - sy0), r0 = src_math_sqrt(c) / n;
function project(x, y) {
var r = src_math_sqrt(c - 2 * n * src_math_sin(y)) / n;
return [r * src_math_sin(x *= n), r0 - r * src_math_cos(x)];
}
project.invert = function(x, y) {
var r0y = r0 - y;
return [math_atan2(x, math_abs(r0y)) / n * math_sign(r0y), math_asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];
};
return project;
}
/* harmony default export */ var conicEqualArea = (function() {
return conic_conicProjection(conicEqualArea_conicEqualAreaRaw)
.scale(155.424)
.center([0, 33.6442]);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/albers.js
/* harmony default export */ var albers = (function() {
return conicEqualArea()
.parallels([29.5, 45.5])
.scale(1070)
.translate([480, 250])
.rotate([96, 0])
.center([-0.6, 38.7]);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/albersUsa.js
// The projections must have mutually exclusive clip regions on the sphere,
// as this will avoid emitting interleaving lines and polygons.
function albersUsa_multiplex(streams) {
var n = streams.length;
return {
point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); },
sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); },
lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); },
lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); },
polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); },
polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); }
};
}
// A composite projection for the United States, configured by default for
// 960×500. The projection also works quite well at 960×600 if you change the
// scale to 1285 and adjust the translate accordingly. The set of standard
// parallels for each region comes from USGS, which is published here:
// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers
/* harmony default export */ var projection_albersUsa = (function() {
var cache,
cacheStream,
lower48 = albers(), lower48Point,
alaska = conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338
hawaii = conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007
point, pointStream = {point: function(x, y) { point = [x, y]; }};
function albersUsa(coordinates) {
var x = coordinates[0], y = coordinates[1];
return point = null,
(lower48Point.point(x, y), point)
|| (alaskaPoint.point(x, y), point)
|| (hawaiiPoint.point(x, y), point);
}
albersUsa.invert = function(coordinates) {
var k = lower48.scale(),
t = lower48.translate(),
x = (coordinates[0] - t[0]) / k,
y = (coordinates[1] - t[1]) / k;
return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska
: y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii
: lower48).invert(coordinates);
};
albersUsa.stream = function(stream) {
return cache && cacheStream === stream ? cache : cache = albersUsa_multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);
};
albersUsa.precision = function(_) {
if (!arguments.length) return lower48.precision();
lower48.precision(_), alaska.precision(_), hawaii.precision(_);
return reset();
};
albersUsa.scale = function(_) {
if (!arguments.length) return lower48.scale();
lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
return albersUsa.translate(lower48.translate());
};
albersUsa.translate = function(_) {
if (!arguments.length) return lower48.translate();
var k = lower48.scale(), x = +_[0], y = +_[1];
lower48Point = lower48
.translate(_)
.clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])
.stream(pointStream);
alaskaPoint = alaska
.translate([x - 0.307 * k, y + 0.201 * k])
.clipExtent([[x - 0.425 * k + src_math_epsilon, y + 0.120 * k + src_math_epsilon], [x - 0.214 * k - src_math_epsilon, y + 0.234 * k - src_math_epsilon]])
.stream(pointStream);
hawaiiPoint = hawaii
.translate([x - 0.205 * k, y + 0.212 * k])
.clipExtent([[x - 0.214 * k + src_math_epsilon, y + 0.166 * k + src_math_epsilon], [x - 0.115 * k - src_math_epsilon, y + 0.234 * k - src_math_epsilon]])
.stream(pointStream);
return reset();
};
albersUsa.fitExtent = function(extent, object) {
return fit_fitExtent(albersUsa, extent, object);
};
albersUsa.fitSize = function(size, object) {
return fit_fitSize(albersUsa, size, object);
};
albersUsa.fitWidth = function(width, object) {
return fit_fitWidth(albersUsa, width, object);
};
albersUsa.fitHeight = function(height, object) {
return fit_fitHeight(albersUsa, height, object);
};
function reset() {
cache = cacheStream = null;
return albersUsa;
}
return albersUsa.scale(1070);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/azimuthal.js
function azimuthal_azimuthalRaw(scale) {
return function(x, y) {
var cx = src_math_cos(x),
cy = src_math_cos(y),
k = scale(cx * cy);
return [
k * cy * src_math_sin(x),
k * src_math_sin(y)
];
}
}
function azimuthal_azimuthalInvert(angle) {
return function(x, y) {
var z = src_math_sqrt(x * x + y * y),
c = angle(z),
sc = src_math_sin(c),
cc = src_math_cos(c);
return [
math_atan2(x * sc, z * cc),
math_asin(z && y * sc / z)
];
}
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/azimuthalEqualArea.js
var azimuthalEqualArea_azimuthalEqualAreaRaw = azimuthal_azimuthalRaw(function(cxcy) {
return src_math_sqrt(2 / (1 + cxcy));
});
azimuthalEqualArea_azimuthalEqualAreaRaw.invert = azimuthal_azimuthalInvert(function(z) {
return 2 * math_asin(z / 2);
});
/* harmony default export */ var azimuthalEqualArea = (function() {
return projection_projection(azimuthalEqualArea_azimuthalEqualAreaRaw)
.scale(124.75)
.clipAngle(180 - 1e-3);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/azimuthalEquidistant.js
var azimuthalEquidistant_azimuthalEquidistantRaw = azimuthal_azimuthalRaw(function(c) {
return (c = math_acos(c)) && c / src_math_sin(c);
});
azimuthalEquidistant_azimuthalEquidistantRaw.invert = azimuthal_azimuthalInvert(function(z) {
return z;
});
/* harmony default export */ var azimuthalEquidistant = (function() {
return projection_projection(azimuthalEquidistant_azimuthalEquidistantRaw)
.scale(79.4188)
.clipAngle(180 - 1e-3);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/mercator.js
function mercator_mercatorRaw(lambda, phi) {
return [lambda, math_log(tan((math_halfPi + phi) / 2))];
}
mercator_mercatorRaw.invert = function(x, y) {
return [x, 2 * atan(math_exp(y)) - math_halfPi];
};
/* harmony default export */ var mercator = (function() {
return mercator_mercatorProjection(mercator_mercatorRaw)
.scale(961 / src_math_tau);
});
function mercator_mercatorProjection(project) {
var m = projection_projection(project),
center = m.center,
scale = m.scale,
translate = m.translate,
clipExtent = m.clipExtent,
x0 = null, y0, x1, y1; // clip extent
m.scale = function(_) {
return arguments.length ? (scale(_), reclip()) : scale();
};
m.translate = function(_) {
return arguments.length ? (translate(_), reclip()) : translate();
};
m.center = function(_) {
return arguments.length ? (center(_), reclip()) : center();
};
m.clipExtent = function(_) {
return arguments.length ? ((_ == null ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1])), reclip()) : x0 == null ? null : [[x0, y0], [x1, y1]];
};
function reclip() {
var k = math_pi * scale(),
t = m(src_rotation(m.rotate()).invert([0, 0]));
return clipExtent(x0 == null
? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === mercator_mercatorRaw
? [[Math.max(t[0] - k, x0), y0], [Math.min(t[0] + k, x1), y1]]
: [[x0, Math.max(t[1] - k, y0)], [x1, Math.min(t[1] + k, y1)]]);
}
return reclip();
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/conicConformal.js
function conicConformal_tany(y) {
return tan((math_halfPi + y) / 2);
}
function conicConformal_conicConformalRaw(y0, y1) {
var cy0 = src_math_cos(y0),
n = y0 === y1 ? src_math_sin(y0) : math_log(cy0 / src_math_cos(y1)) / math_log(conicConformal_tany(y1) / conicConformal_tany(y0)),
f = cy0 * math_pow(conicConformal_tany(y0), n) / n;
if (!n) return mercator_mercatorRaw;
function project(x, y) {
if (f > 0) { if (y < -math_halfPi + src_math_epsilon) y = -math_halfPi + src_math_epsilon; }
else { if (y > math_halfPi - src_math_epsilon) y = math_halfPi - src_math_epsilon; }
var r = f / math_pow(conicConformal_tany(y), n);
return [r * src_math_sin(n * x), f - r * src_math_cos(n * x)];
}
project.invert = function(x, y) {
var fy = f - y, r = math_sign(n) * src_math_sqrt(x * x + fy * fy);
return [math_atan2(x, math_abs(fy)) / n * math_sign(fy), 2 * atan(math_pow(f / r, 1 / n)) - math_halfPi];
};
return project;
}
/* harmony default export */ var conicConformal = (function() {
return conic_conicProjection(conicConformal_conicConformalRaw)
.scale(109.5)
.parallels([30, 30]);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/equirectangular.js
function equirectangular_equirectangularRaw(lambda, phi) {
return [lambda, phi];
}
equirectangular_equirectangularRaw.invert = equirectangular_equirectangularRaw;
/* harmony default export */ var equirectangular = (function() {
return projection_projection(equirectangular_equirectangularRaw)
.scale(152.63);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/conicEquidistant.js
function conicEquidistant_conicEquidistantRaw(y0, y1) {
var cy0 = src_math_cos(y0),
n = y0 === y1 ? src_math_sin(y0) : (cy0 - src_math_cos(y1)) / (y1 - y0),
g = cy0 / n + y0;
if (math_abs(n) < src_math_epsilon) return equirectangular_equirectangularRaw;
function project(x, y) {
var gy = g - y, nx = n * x;
return [gy * src_math_sin(nx), g - gy * src_math_cos(nx)];
}
project.invert = function(x, y) {
var gy = g - y;
return [math_atan2(x, math_abs(gy)) / n * math_sign(gy), g - math_sign(n) * src_math_sqrt(x * x + gy * gy)];
};
return project;
}
/* harmony default export */ var conicEquidistant = (function() {
return conic_conicProjection(conicEquidistant_conicEquidistantRaw)
.scale(131.154)
.center([0, 13.9389]);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/equalEarth.js
var equalEarth_A1 = 1.340264,
equalEarth_A2 = -0.081106,
equalEarth_A3 = 0.000893,
equalEarth_A4 = 0.003796,
equalEarth_M = src_math_sqrt(3) / 2,
equalEarth_iterations = 12;
function equalEarth_equalEarthRaw(lambda, phi) {
var l = math_asin(equalEarth_M * src_math_sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;
return [
lambda * src_math_cos(l) / (equalEarth_M * (equalEarth_A1 + 3 * equalEarth_A2 * l2 + l6 * (7 * equalEarth_A3 + 9 * equalEarth_A4 * l2))),
l * (equalEarth_A1 + equalEarth_A2 * l2 + l6 * (equalEarth_A3 + equalEarth_A4 * l2))
];
}
equalEarth_equalEarthRaw.invert = function(x, y) {
var l = y, l2 = l * l, l6 = l2 * l2 * l2;
for (var i = 0, delta, fy, fpy; i < equalEarth_iterations; ++i) {
fy = l * (equalEarth_A1 + equalEarth_A2 * l2 + l6 * (equalEarth_A3 + equalEarth_A4 * l2)) - y;
fpy = equalEarth_A1 + 3 * equalEarth_A2 * l2 + l6 * (7 * equalEarth_A3 + 9 * equalEarth_A4 * l2);
l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;
if (math_abs(delta) < math_epsilon2) break;
}
return [
equalEarth_M * x * (equalEarth_A1 + 3 * equalEarth_A2 * l2 + l6 * (7 * equalEarth_A3 + 9 * equalEarth_A4 * l2)) / src_math_cos(l),
math_asin(src_math_sin(l) / equalEarth_M)
];
};
/* harmony default export */ var equalEarth = (function() {
return projection_projection(equalEarth_equalEarthRaw)
.scale(177.158);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/gnomonic.js
function gnomonic_gnomonicRaw(x, y) {
var cy = src_math_cos(y), k = src_math_cos(x) * cy;
return [cy * src_math_sin(x) / k, src_math_sin(y) / k];
}
gnomonic_gnomonicRaw.invert = azimuthal_azimuthalInvert(atan);
/* harmony default export */ var gnomonic = (function() {
return projection_projection(gnomonic_gnomonicRaw)
.scale(144.049)
.clipAngle(60);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/identity.js
function identity_scaleTranslate(kx, ky, tx, ty) {
return kx === 1 && ky === 1 && tx === 0 && ty === 0 ? d3_geo_src_identity : transform_transformer({
point: function(x, y) {
this.stream.point(x * kx + tx, y * ky + ty);
}
});
}
/* harmony default export */ var projection_identity = (function() {
var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, transform = d3_geo_src_identity, // scale, translate and reflect
x0 = null, y0, x1, y1, // clip extent
postclip = d3_geo_src_identity,
cache,
cacheStream,
projection;
function reset() {
cache = cacheStream = null;
return projection;
}
return projection = {
stream: function(stream) {
return cache && cacheStream === stream ? cache : cache = transform(postclip(cacheStream = stream));
},
postclip: function(_) {
return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
},
clipExtent: function(_) {
return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, d3_geo_src_identity) : rectangle_clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];
},
scale: function(_) {
return arguments.length ? (transform = identity_scaleTranslate((k = +_) * sx, k * sy, tx, ty), reset()) : k;
},
translate: function(_) {
return arguments.length ? (transform = identity_scaleTranslate(k * sx, k * sy, tx = +_[0], ty = +_[1]), reset()) : [tx, ty];
},
reflectX: function(_) {
return arguments.length ? (transform = identity_scaleTranslate(k * (sx = _ ? -1 : 1), k * sy, tx, ty), reset()) : sx < 0;
},
reflectY: function(_) {
return arguments.length ? (transform = identity_scaleTranslate(k * sx, k * (sy = _ ? -1 : 1), tx, ty), reset()) : sy < 0;
},
fitExtent: function(extent, object) {
return fit_fitExtent(projection, extent, object);
},
fitSize: function(size, object) {
return fit_fitSize(projection, size, object);
},
fitWidth: function(width, object) {
return fit_fitWidth(projection, width, object);
},
fitHeight: function(height, object) {
return fit_fitHeight(projection, height, object);
}
};
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/naturalEarth1.js
function naturalEarth1_naturalEarth1Raw(lambda, phi) {
var phi2 = phi * phi, phi4 = phi2 * phi2;
return [
lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),
phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))
];
}
naturalEarth1_naturalEarth1Raw.invert = function(x, y) {
var phi = y, i = 25, delta;
do {
var phi2 = phi * phi, phi4 = phi2 * phi2;
phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /
(1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));
} while (math_abs(delta) > src_math_epsilon && --i > 0);
return [
x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),
phi
];
};
/* harmony default export */ var naturalEarth1 = (function() {
return projection_projection(naturalEarth1_naturalEarth1Raw)
.scale(175.295);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/orthographic.js
function orthographic_orthographicRaw(x, y) {
return [src_math_cos(y) * src_math_sin(x), src_math_sin(y)];
}
orthographic_orthographicRaw.invert = azimuthal_azimuthalInvert(math_asin);
/* harmony default export */ var orthographic = (function() {
return projection_projection(orthographic_orthographicRaw)
.scale(249.5)
.clipAngle(90 + src_math_epsilon);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/stereographic.js
function stereographic_stereographicRaw(x, y) {
var cy = src_math_cos(y), k = 1 + src_math_cos(x) * cy;
return [cy * src_math_sin(x) / k, src_math_sin(y) / k];
}
stereographic_stereographicRaw.invert = azimuthal_azimuthalInvert(function(z) {
return 2 * atan(z);
});
/* harmony default export */ var stereographic = (function() {
return projection_projection(stereographic_stereographicRaw)
.scale(250)
.clipAngle(142);
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/projection/transverseMercator.js
function transverseMercator_transverseMercatorRaw(lambda, phi) {
return [math_log(tan((math_halfPi + phi) / 2)), -lambda];
}
transverseMercator_transverseMercatorRaw.invert = function(x, y) {
return [-y, 2 * atan(math_exp(x)) - math_halfPi];
};
/* harmony default export */ var transverseMercator = (function() {
var m = mercator_mercatorProjection(transverseMercator_transverseMercatorRaw),
center = m.center,
rotate = m.rotate;
m.center = function(_) {
return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);
};
m.rotate = function(_) {
return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);
};
return rotate([0, 0, 90])
.scale(159.155);
});
// CONCATENATED MODULE: ./node_modules/d3-geo-projection/src/math.js
var src_math_abs = Math.abs;
var math_atan = Math.atan;
var src_math_atan2 = Math.atan2;
var math_ceil = Math.ceil;
var d3_geo_projection_src_math_cos = Math.cos;
var src_math_exp = Math.exp;
var src_math_floor = Math.floor;
var src_math_log = Math.log;
var src_math_max = Math.max;
var src_math_min = Math.min;
var src_math_pow = Math.pow;
var math_round = Math.round;
var src_math_sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };
var d3_geo_projection_src_math_sin = Math.sin;
var math_tan = Math.tan;
var d3_geo_projection_src_math_epsilon = 1e-6;
var src_math_epsilon2 = 1e-12;
var src_math_pi = Math.PI;
var src_math_halfPi = src_math_pi / 2;
var math_quarterPi = src_math_pi / 4;
var sqrt1_2 = Math.SQRT1_2;
var sqrt2 = d3_geo_projection_src_math_sqrt(2);
var sqrtPi = d3_geo_projection_src_math_sqrt(src_math_pi);
var d3_geo_projection_src_math_tau = src_math_pi * 2;
var src_math_degrees = 180 / src_math_pi;
var math_radians = src_math_pi / 180;
function sinci(x) {
return x ? x / Math.sin(x) : 1;
}
function src_math_asin(x) {
return x > 1 ? src_math_halfPi : x < -1 ? -src_math_halfPi : Math.asin(x);
}
function src_math_acos(x) {
return x > 1 ? 0 : x < -1 ? src_math_pi : Math.acos(x);
}
function d3_geo_projection_src_math_sqrt(x) {
return x > 0 ? Math.sqrt(x) : 0;
}
function math_tanh(x) {
x = src_math_exp(2 * x);
return (x - 1) / (x + 1);
}
function math_sinh(x) {
return (src_math_exp(x) - src_math_exp(-x)) / 2;
}
function math_cosh(x) {
return (src_math_exp(x) + src_math_exp(-x)) / 2;
}
function arsinh(x) {
return src_math_log(x + d3_geo_projection_src_math_sqrt(x * x + 1));
}
function arcosh(x) {
return src_math_log(x + d3_geo_projection_src_math_sqrt(x * x - 1));
}
// CONCATENATED MODULE: ./node_modules/d3-geo-projection/src/mollweide.js
function mollweide_mollweideBromleyTheta(cp, phi) {
var cpsinPhi = cp * d3_geo_projection_src_math_sin(phi), i = 30, delta;
do phi -= delta = (phi + d3_geo_projection_src_math_sin(phi) - cpsinPhi) / (1 + d3_geo_projection_src_math_cos(phi));
while (src_math_abs(delta) > d3_geo_projection_src_math_epsilon && --i > 0);
return phi / 2;
}
function mollweide_mollweideBromleyRaw(cx, cy, cp) {
function forward(lambda, phi) {
return [cx * lambda * d3_geo_projection_src_math_cos(phi = mollweide_mollweideBromleyTheta(cp, phi)), cy * d3_geo_projection_src_math_sin(phi)];
}
forward.invert = function(x, y) {
return y = src_math_asin(y / cy), [x / (cx * d3_geo_projection_src_math_cos(y)), src_math_asin((2 * y + d3_geo_projection_src_math_sin(2 * y)) / cp)];
};
return forward;
}
var mollweide_mollweideRaw = mollweide_mollweideBromleyRaw(sqrt2 / src_math_halfPi, sqrt2, src_math_pi);
/* harmony default export */ var mollweide = (function() {
return projection_projection(mollweide_mollweideRaw)
.scale(169.529);
});
// CONCATENATED MODULE: ./node_modules/vega-projection/src/projections.js
var projections_defaultPath = d3_geo_src_path();
var projections_projectionProperties = [
// standard properties in d3-geo
'clipAngle',
'clipExtent',
'scale',
'translate',
'center',
'rotate',
'parallels',
'precision',
'reflectX',
'reflectY',
// extended properties in d3-geo-projections
'coefficient',
'distance',
'fraction',
'lobes',
'parallel',
'radius',
'ratio',
'spacing',
'tilt'
];
/**
* Augment projections with their type and a copy method.
*/
function projections_create(type, constructor) {
return function projection() {
var p = constructor();
p.type = type;
p.path = d3_geo_src_path().projection(p);
p.copy = p.copy || function() {
var c = projection();
projections_projectionProperties.forEach(function(prop) {
if (p[prop]) c[prop](p[prop]());
});
c.path.pointRadius(p.path.pointRadius());
return c;
};
return p;
};
}
function projections_projection(type, proj) {
if (!type || typeof type !== 'string') {
throw new Error('Projection type must be a name string.');
}
type = type.toLowerCase();
if (arguments.length > 1) {
projections_projections[type] = projections_create(type, proj);
return this;
} else {
return projections_projections[type] || null;
}
}
function projections_getProjectionPath(proj) {
return (proj && proj.path) || projections_defaultPath;
}
var projections_projections = {
// base d3-geo projection types
albers: albers,
albersusa: projection_albersUsa,
azimuthalequalarea: azimuthalEqualArea,
azimuthalequidistant: azimuthalEquidistant,
conicconformal: conicConformal,
conicequalarea: conicEqualArea,
conicequidistant: conicEquidistant,
equalEarth: equalEarth,
equirectangular: equirectangular,
gnomonic: gnomonic,
identity: projection_identity,
mercator: mercator,
mollweide: mollweide,
naturalEarth1: naturalEarth1,
orthographic: orthographic,
stereographic: stereographic,
transversemercator: transverseMercator
};
for (var projections_key in projections_projections) {
projections_projection(projections_key, projections_projections[projections_key]);
}
// CONCATENATED MODULE: ./node_modules/vega-projection/index.js
// CONCATENATED MODULE: ./node_modules/vega-geo/src/GeoPath.js
/**
* Map GeoJSON data to an SVG path string.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(number, number): *} params.projection - The cartographic
* projection to apply.
* @param {function(object): *} [params.field] - The field with GeoJSON data,
* or null if the tuple itself is a GeoJSON feature.
* @param {string} [params.as='path'] - The output field in which to store
* the generated path data (default 'path').
*/
function GeoPath_GeoPath(params) {
Transform_Transform.call(this, null, params);
}
GeoPath_GeoPath.Definition = {
"type": "GeoPath",
"metadata": {"modifies": true},
"params": [
{ "name": "projection", "type": "projection" },
{ "name": "field", "type": "field" },
{ "name": "pointRadius", "type": "number", "expr": true },
{ "name": "as", "type": "string", "default": "path" }
]
};
var GeoPath_prototype = Object(vega_util["y" /* inherits */])(GeoPath_GeoPath, Transform_Transform);
GeoPath_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.ALL),
path = this.value,
field = _.field || vega_util["x" /* identity */],
as = _.as || 'path',
flag = out.SOURCE;
function set(t) { t[as] = path(field(t)); }
if (!path || _.modified()) {
// parameters updated, reset and reflow
this.value = path = projections_getProjectionPath(_.projection);
out.materialize().reflow();
} else {
flag = field === vega_util["x" /* identity */] || pulse.modified(field.fields)
? out.ADD_MOD
: out.ADD;
}
var prev = GeoPath_initPath(path, _.pointRadius);
out.visit(flag, set);
path.pointRadius(prev);
return out.modifies(as);
};
function GeoPath_initPath(path, pointRadius) {
var prev = path.pointRadius();
path.context(null);
if (pointRadius != null) {
path.pointRadius(pointRadius);
}
return prev;
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/GeoPoint.js
/**
* Geo-code a longitude/latitude point to an x/y coordinate.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(number, number): *} params.projection - The cartographic
* projection to apply.
* @param {Array<function(object): *>} params.fields - A two-element array of
* field accessors for the longitude and latitude values.
* @param {Array<string>} [params.as] - A two-element array of field names
* under which to store the result. Defaults to ['x','y'].
*/
function GeoPoint_GeoPoint(params) {
Transform_Transform.call(this, null, params);
}
GeoPoint_GeoPoint.Definition = {
"type": "GeoPoint",
"metadata": {"modifies": true},
"params": [
{ "name": "projection", "type": "projection", "required": true },
{ "name": "fields", "type": "field", "array": true, "required": true, "length": 2 },
{ "name": "as", "type": "string", "array": true, "length": 2, "default": ["x", "y"] }
]
};
var GeoPoint_prototype = Object(vega_util["y" /* inherits */])(GeoPoint_GeoPoint, Transform_Transform);
GeoPoint_prototype.transform = function(_, pulse) {
var proj = _.projection,
lon = _.fields[0],
lat = _.fields[1],
as = _.as || ['x', 'y'],
x = as[0],
y = as[1],
mod;
function set(t) {
var xy = proj([lon(t), lat(t)]);
if (xy) {
t[x] = xy[0];
t[y] = xy[1];
} else {
t[x] = undefined;
t[y] = undefined;
}
}
if (_.modified()) {
// parameters updated, reflow
pulse = pulse.materialize().reflow(true).visit(pulse.SOURCE, set);
} else {
mod = pulse.modified(lon.fields) || pulse.modified(lat.fields);
pulse.visit(mod ? pulse.ADD_MOD : pulse.ADD, set);
}
return pulse.modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-geo/src/GeoShape.js
/**
* Annotate items with a geopath shape generator.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(number, number): *} params.projection - The cartographic
* projection to apply.
* @param {function(object): *} [params.field] - The field with GeoJSON data,
* or null if the tuple itself is a GeoJSON feature.
* @param {string} [params.as='shape'] - The output field in which to store
* the generated path data (default 'shape').
*/
function GeoShape_GeoShape(params) {
Transform_Transform.call(this, null, params);
}
GeoShape_GeoShape.Definition = {
"type": "GeoShape",
"metadata": {"modifies": true, "nomod": true},
"params": [
{ "name": "projection", "type": "projection" },
{ "name": "field", "type": "field", "default": "datum" },
{ "name": "pointRadius", "type": "number", "expr": true },
{ "name": "as", "type": "string", "default": "shape" }
]
};
var GeoShape_prototype = Object(vega_util["y" /* inherits */])(GeoShape_GeoShape, Transform_Transform);
GeoShape_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.ALL),
shape = this.value,
as = _.as || 'shape',
flag = out.ADD;
if (!shape || _.modified()) {
// parameters updated, reset and reflow
this.value = shape = GeoShape_shapeGenerator(
projections_getProjectionPath(_.projection),
_.field || Object(vega_util["t" /* field */])('datum'),
_.pointRadius
);
out.materialize().reflow();
flag = out.SOURCE;
}
out.visit(flag, function(t) { t[as] = shape; });
return out.modifies(as);
};
function GeoShape_shapeGenerator(path, field, pointRadius) {
var shape = pointRadius == null
? function(_) { return path(field(_)); }
: function(_) {
var prev = path.pointRadius(),
value = path.pointRadius(pointRadius)(field(_));
path.pointRadius(prev);
return value;
};
shape.context = function(_) {
path.context(_);
return shape;
};
return shape;
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/graticule.js
function graticule_graticuleX(y0, y1, dy) {
var y = d3_array_src_range(y0, y1 - src_math_epsilon, dy).concat(y1);
return function(x) { return y.map(function(y) { return [x, y]; }); };
}
function graticule_graticuleY(x0, x1, dx) {
var x = d3_array_src_range(x0, x1 - src_math_epsilon, dx).concat(x1);
return function(y) { return x.map(function(x) { return [x, y]; }); };
}
function graticule_graticule() {
var x1, x0, X1, X0,
y1, y0, Y1, Y0,
dx = 10, dy = dx, DX = 90, DY = 360,
x, y, X, Y,
precision = 2.5;
function graticule() {
return {type: "MultiLineString", coordinates: lines()};
}
function lines() {
return d3_array_src_range(ceil(X0 / DX) * DX, X1, DX).map(X)
.concat(d3_array_src_range(ceil(Y0 / DY) * DY, Y1, DY).map(Y))
.concat(d3_array_src_range(ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return math_abs(x % DX) > src_math_epsilon; }).map(x))
.concat(d3_array_src_range(ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return math_abs(y % DY) > src_math_epsilon; }).map(y));
}
graticule.lines = function() {
return lines().map(function(coordinates) { return {type: "LineString", coordinates: coordinates}; });
};
graticule.outline = function() {
return {
type: "Polygon",
coordinates: [
X(X0).concat(
Y(Y1).slice(1),
X(X1).reverse().slice(1),
Y(Y0).reverse().slice(1))
]
};
};
graticule.extent = function(_) {
if (!arguments.length) return graticule.extentMinor();
return graticule.extentMajor(_).extentMinor(_);
};
graticule.extentMajor = function(_) {
if (!arguments.length) return [[X0, Y0], [X1, Y1]];
X0 = +_[0][0], X1 = +_[1][0];
Y0 = +_[0][1], Y1 = +_[1][1];
if (X0 > X1) _ = X0, X0 = X1, X1 = _;
if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
return graticule.precision(precision);
};
graticule.extentMinor = function(_) {
if (!arguments.length) return [[x0, y0], [x1, y1]];
x0 = +_[0][0], x1 = +_[1][0];
y0 = +_[0][1], y1 = +_[1][1];
if (x0 > x1) _ = x0, x0 = x1, x1 = _;
if (y0 > y1) _ = y0, y0 = y1, y1 = _;
return graticule.precision(precision);
};
graticule.step = function(_) {
if (!arguments.length) return graticule.stepMinor();
return graticule.stepMajor(_).stepMinor(_);
};
graticule.stepMajor = function(_) {
if (!arguments.length) return [DX, DY];
DX = +_[0], DY = +_[1];
return graticule;
};
graticule.stepMinor = function(_) {
if (!arguments.length) return [dx, dy];
dx = +_[0], dy = +_[1];
return graticule;
};
graticule.precision = function(_) {
if (!arguments.length) return precision;
precision = +_;
x = graticule_graticuleX(y0, y1, 90);
y = graticule_graticuleY(x0, x1, precision);
X = graticule_graticuleX(Y0, Y1, 90);
Y = graticule_graticuleY(X0, X1, precision);
return graticule;
};
return graticule
.extentMajor([[-180, -90 + src_math_epsilon], [180, 90 - src_math_epsilon]])
.extentMinor([[-180, -80 - src_math_epsilon], [180, 80 + src_math_epsilon]]);
}
function graticule_graticule10() {
return graticule_graticule()();
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/Graticule.js
/**
* GeoJSON feature generator for creating graticules.
* @constructor
*/
function Graticule_Graticule(params) {
Transform_Transform.call(this, [], params);
this.generator = graticule_graticule();
}
Graticule_Graticule.Definition = {
"type": "Graticule",
"metadata": {"changes": true, "generates": true},
"params": [
{ "name": "extent", "type": "array", "array": true, "length": 2,
"content": {"type": "number", "array": true, "length": 2} },
{ "name": "extentMajor", "type": "array", "array": true, "length": 2,
"content": {"type": "number", "array": true, "length": 2} },
{ "name": "extentMinor", "type": "array", "array": true, "length": 2,
"content": {"type": "number", "array": true, "length": 2} },
{ "name": "step", "type": "number", "array": true, "length": 2 },
{ "name": "stepMajor", "type": "number", "array": true, "length": 2, "default": [90, 360] },
{ "name": "stepMinor", "type": "number", "array": true, "length": 2, "default": [10, 10] },
{ "name": "precision", "type": "number", "default": 2.5 }
]
};
var Graticule_prototype = Object(vega_util["y" /* inherits */])(Graticule_Graticule, Transform_Transform);
Graticule_prototype.transform = function(_, pulse) {
var src = this.value,
gen = this.generator, t;
if (!src.length || _.modified()) {
for (var prop in _) {
if (Object(vega_util["D" /* isFunction */])(gen[prop])) {
gen[prop](_[prop]);
}
}
}
t = gen();
if (src.length) {
pulse.mod.push(replace(src[0], t));
} else {
pulse.add.push(Tuple_ingest(t));
}
src[0] = t;
return pulse;
};
// CONCATENATED MODULE: ./node_modules/vega-geo/src/Heatmap.js
/**
* Render a heatmap image for input raster grid data.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} [params.field] - The field with raster grid
* data. If unspecified, the tuple itself is interpreted as a raster grid.
* @param {string} [params.color] - A constant color value or function for
* individual pixel color. If a function, it will be invoked with an input
* object that includes $x, $y, $value, and $max fields for the grid.
* @param {number} [params.opacity] - A constant opacity value or function for
* individual pixel opacity. If a function, it will be invoked with an input
* object that includes $x, $y, $value, and $max fields for the grid.
* @param {string} [params.resolve] - The method for resolving maximum values
* across multiple input grids. If 'independent' (the default), maximum
* calculation will be performed separately for each grid. If 'shared',
* a single global maximum will be used for all input grids.
* @param {string} [params.as='image'] - The output field in which to store
* the generated bitmap canvas images (default 'image').
*/
function Heatmap_Heatmap(params) {
Transform_Transform.call(this, null, params);
}
Heatmap_Heatmap.Definition = {
"type": "heatmap",
"metadata": {"modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "color", "type": "string", "expr": true},
{ "name": "opacity", "type": "number", "expr": true},
{ "name": "resolve", "type": "enum", "values": ["shared", "independent"], "default": "independent" },
{ "name": "as", "type": "string", "default": "image" }
]
};
var Heatmap_prototype = Object(vega_util["y" /* inherits */])(Heatmap_Heatmap, Transform_Transform);
Heatmap_prototype.transform = function(_, pulse) {
if (!pulse.changed() && !_.modified()) {
return pulse.StopPropagation;
}
var source = pulse.materialize(pulse.SOURCE).source,
shared = _.resolve === 'shared',
field = _.field || vega_util["x" /* identity */],
opacity = Heatmap_opacity_(_.opacity, _),
color = Heatmap_color_(_.color, _),
as = _.as || 'image',
obj = {
$x: 0, $y: 0, $value: 0,
$max: shared ? max_max(source.map(t => max_max(field(t).values))) : 0
};
source.forEach(t => {
const v = field(t);
// build proxy data object
const o = Object(vega_util["o" /* extend */])({}, t, obj);
// set maximum value if not globally shared
if (!shared) o.$max = max_max(v.values || []);
// generate canvas image
// optimize color/opacity if not pixel-dependent
t[as] = Heatmap_toCanvas(v, o,
color.dep ? color : Object(vega_util["l" /* constant */])(color(o)),
opacity.dep ? opacity : Object(vega_util["l" /* constant */])(opacity(o))
);
});
return pulse.reflow(true).modifies(as);
};
// get image color function
function Heatmap_color_(color, _) {
let f;
if (Object(vega_util["D" /* isFunction */])(color)) {
f = obj => color_rgb(color(obj, _));
f.dep = Heatmap_dependency(color);
} else {
// default to mid-grey
f = Object(vega_util["l" /* constant */])(color_rgb(color || '#888'));
}
return f;
}
// get image opacity function
function Heatmap_opacity_(opacity, _) {
let f;
if (Object(vega_util["D" /* isFunction */])(opacity)) {
f = obj => opacity(obj, _);
f.dep = Heatmap_dependency(opacity);
} else if (opacity) {
f = Object(vega_util["l" /* constant */])(opacity);
} else {
// default to [0, max] opacity gradient
f = obj => (obj.$value / obj.$max) || 0;
f.dep = true;
}
return f;
}
// check if function depends on individual pixel data
function Heatmap_dependency(f) {
if (!Object(vega_util["D" /* isFunction */])(f)) return false;
const set = Object(vega_util["Da" /* toSet */])(Object(vega_util["g" /* accessorFields */])(f));
return set.$x || set.$y || set.$value || set.$max;
}
// render raster grid to canvas
function Heatmap_toCanvas(grid, obj, color, opacity) {
const n = grid.width,
m = grid.height,
x1 = grid.x1 || 0,
y1 = grid.y1 || 0,
x2 = grid.x2 || n,
y2 = grid.y2 || m,
val = grid.values,
value = val ? i => val[i] : vega_util["Ka" /* zero */],
can = domCanvas(x2 - x1, y2 - y1),
ctx = can.getContext('2d'),
img = ctx.getImageData(0, 0, x2 - x1, y2 - y1),
pix = img.data;
for (let j=y1, k=0; j<y2; ++j) {
obj.$y = j - y1;
for (let i=x1, r=j*n; i<x2; ++i, k+=4) {
obj.$x = i - x1;
obj.$value = value(i + r);
const v = color(obj);
pix[k+0] = v.r;
pix[k+1] = v.g;
pix[k+2] = v.b;
pix[k+3] = ~~(255 * opacity(obj));
}
}
ctx.putImageData(img, 0, 0);
return can;
}
// CONCATENATED MODULE: ./node_modules/vega-geo/src/Projection.js
/**
* Maintains a cartographic projection.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function Projection_Projection(params) {
Transform_Transform.call(this, null, params);
this.modified(true); // always treat as modified
}
var Projection_prototype = Object(vega_util["y" /* inherits */])(Projection_Projection, Transform_Transform);
Projection_prototype.transform = function(_, pulse) {
var proj = this.value;
if (!proj || _.modified('type')) {
this.value = (proj = Projection_create(_.type));
projections_projectionProperties.forEach(function(prop) {
if (_[prop] != null) Projection_set(proj, prop, _[prop]);
});
} else {
projections_projectionProperties.forEach(function(prop) {
if (_.modified(prop)) Projection_set(proj, prop, _[prop]);
});
}
if (_.pointRadius != null) proj.path.pointRadius(_.pointRadius);
if (_.fit) Projection_fit(proj, _);
return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
};
function Projection_fit(proj, _) {
var data = Projection_collectGeoJSON(_.fit);
_.extent ? proj.fitExtent(_.extent, data)
: _.size ? proj.fitSize(_.size, data) : 0;
}
function Projection_create(type) {
var constructor = projections_projection((type || 'mercator').toLowerCase());
if (!constructor) Object(vega_util["n" /* error */])('Unrecognized projection type: ' + type);
return constructor();
}
function Projection_set(proj, key, value) {
if (Object(vega_util["D" /* isFunction */])(proj[key])) proj[key](value);
}
function Projection_collectGeoJSON(data) {
data = Object(vega_util["i" /* array */])(data);
return data.length === 1 ? data[0]
: {
type: FeatureCollection,
features: data.reduce((a, f) => a.concat(Projection_featurize(f)), [])
};
}
function Projection_featurize(f) {
return f.type === FeatureCollection
? f.features
: Object(vega_util["i" /* array */])(f).filter(d => d != null).map(
d => d.type === Feature ? d : {type: Feature, geometry: d}
);
}
// CONCATENATED MODULE: ./node_modules/vega-geo/index.js
// CONCATENATED MODULE: ./node_modules/d3-force/src/center.js
/* harmony default export */ var src_center = (function(x, y) {
var nodes;
if (x == null) x = 0;
if (y == null) y = 0;
function force() {
var i,
n = nodes.length,
node,
sx = 0,
sy = 0;
for (i = 0; i < n; ++i) {
node = nodes[i], sx += node.x, sy += node.y;
}
for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) {
node = nodes[i], node.x -= sx, node.y -= sy;
}
}
force.initialize = function(_) {
nodes = _;
};
force.x = function(_) {
return arguments.length ? (x = +_, force) : x;
};
force.y = function(_) {
return arguments.length ? (y = +_, force) : y;
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/add.js
/* harmony default export */ var src_add = (function(d) {
var x = +this._x.call(null, d),
y = +this._y.call(null, d);
return add_add(this.cover(x, y), x, y, d);
});
function add_add(tree, x, y, d) {
if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points
var parent,
node = tree._root,
leaf = {data: d},
x0 = tree._x0,
y0 = tree._y0,
x1 = tree._x1,
y1 = tree._y1,
xm,
ym,
xp,
yp,
right,
bottom,
i,
j;
// If the tree is empty, initialize the root as a leaf.
if (!node) return tree._root = leaf, tree;
// Find the existing leaf for the new point, or add it.
while (node.length) {
if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
}
// Is the new point is exactly coincident with the existing point?
xp = +tree._x.call(null, node.data);
yp = +tree._y.call(null, node.data);
if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
// Otherwise, split the leaf node until the old and new point are separated.
do {
parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);
if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
} while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));
return parent[j] = node, parent[i] = leaf, tree;
}
function addAll(data) {
var d, i, n = data.length,
x,
y,
xz = new Array(n),
yz = new Array(n),
x0 = Infinity,
y0 = Infinity,
x1 = -Infinity,
y1 = -Infinity;
// Compute the points and their extent.
for (i = 0; i < n; ++i) {
if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
xz[i] = x;
yz[i] = y;
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
// If there were no (valid) points, abort.
if (x0 > x1 || y0 > y1) return this;
// Expand the tree to cover the new points.
this.cover(x0, y0).cover(x1, y1);
// Add the new points.
for (i = 0; i < n; ++i) {
add_add(this, xz[i], yz[i], data[i]);
}
return this;
}
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/cover.js
/* harmony default export */ var cover = (function(x, y) {
if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points
var x0 = this._x0,
y0 = this._y0,
x1 = this._x1,
y1 = this._y1;
// If the quadtree has no extent, initialize them.
// Integer extent are necessary so that if we later double the extent,
// the existing quadrant boundaries dont change due to floating point error!
if (isNaN(x0)) {
x1 = (x0 = Math.floor(x)) + 1;
y1 = (y0 = Math.floor(y)) + 1;
}
// Otherwise, double repeatedly to cover.
else {
var z = x1 - x0,
node = this._root,
parent,
i;
while (x0 > x || x >= x1 || y0 > y || y >= y1) {
i = (y < y0) << 1 | (x < x0);
parent = new Array(4), parent[i] = node, node = parent, z *= 2;
switch (i) {
case 0: x1 = x0 + z, y1 = y0 + z; break;
case 1: x0 = x1 - z, y1 = y0 + z; break;
case 2: x1 = x0 + z, y0 = y1 - z; break;
case 3: x0 = x1 - z, y0 = y1 - z; break;
}
}
if (this._root && this._root.length) this._root = node;
}
this._x0 = x0;
this._y0 = y0;
this._x1 = x1;
this._y1 = y1;
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/data.js
/* harmony default export */ var src_data = (function() {
var data = [];
this.visit(function(node) {
if (!node.length) do data.push(node.data); while (node = node.next)
});
return data;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/extent.js
/* harmony default export */ var d3_quadtree_src_extent = (function(_) {
return arguments.length
? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])
: isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/quad.js
/* harmony default export */ var src_quad = (function(node, x0, y0, x1, y1) {
this.node = node;
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/find.js
/* harmony default export */ var src_find = (function(x, y, radius) {
var data,
x0 = this._x0,
y0 = this._y0,
x1,
y1,
x2,
y2,
x3 = this._x1,
y3 = this._y1,
quads = [],
node = this._root,
q,
i;
if (node) quads.push(new src_quad(node, x0, y0, x3, y3));
if (radius == null) radius = Infinity;
else {
x0 = x - radius, y0 = y - radius;
x3 = x + radius, y3 = y + radius;
radius *= radius;
}
while (q = quads.pop()) {
// Stop searching if this quadrant cant contain a closer node.
if (!(node = q.node)
|| (x1 = q.x0) > x3
|| (y1 = q.y0) > y3
|| (x2 = q.x1) < x0
|| (y2 = q.y1) < y0) continue;
// Bisect the current quadrant.
if (node.length) {
var xm = (x1 + x2) / 2,
ym = (y1 + y2) / 2;
quads.push(
new src_quad(node[3], xm, ym, x2, y2),
new src_quad(node[2], x1, ym, xm, y2),
new src_quad(node[1], xm, y1, x2, ym),
new src_quad(node[0], x1, y1, xm, ym)
);
// Visit the closest quadrant first.
if (i = (y >= ym) << 1 | (x >= xm)) {
q = quads[quads.length - 1];
quads[quads.length - 1] = quads[quads.length - 1 - i];
quads[quads.length - 1 - i] = q;
}
}
// Visit this point. (Visiting coincident points isnt necessary!)
else {
var dx = x - +this._x.call(null, node.data),
dy = y - +this._y.call(null, node.data),
d2 = dx * dx + dy * dy;
if (d2 < radius) {
var d = Math.sqrt(radius = d2);
x0 = x - d, y0 = y - d;
x3 = x + d, y3 = y + d;
data = node.data;
}
}
}
return data;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/remove.js
/* harmony default export */ var src_remove = (function(d) {
if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points
var parent,
node = this._root,
retainer,
previous,
next,
x0 = this._x0,
y0 = this._y0,
x1 = this._x1,
y1 = this._y1,
x,
y,
xm,
ym,
right,
bottom,
i,
j;
// If the tree is empty, initialize the root as a leaf.
if (!node) return this;
// Find the leaf node for the point.
// While descending, also retain the deepest parent with a non-removed sibling.
if (node.length) while (true) {
if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;
if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;
if (!(parent = node, node = node[i = bottom << 1 | right])) return this;
if (!node.length) break;
if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;
}
// Find the point to remove.
while (node.data !== d) if (!(previous = node, node = node.next)) return this;
if (next = node.next) delete node.next;
// If there are multiple coincident points, remove just the point.
if (previous) return (next ? previous.next = next : delete previous.next), this;
// If this is the root point, remove it.
if (!parent) return this._root = next, this;
// Remove this leaf.
next ? parent[i] = next : delete parent[i];
// If the parent now contains exactly one leaf, collapse superfluous parents.
if ((node = parent[0] || parent[1] || parent[2] || parent[3])
&& node === (parent[3] || parent[2] || parent[1] || parent[0])
&& !node.length) {
if (retainer) retainer[j] = node;
else this._root = node;
}
return this;
});
function removeAll(data) {
for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
return this;
}
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/root.js
/* harmony default export */ var src_root = (function() {
return this._root;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/size.js
/* harmony default export */ var src_size = (function() {
var size = 0;
this.visit(function(node) {
if (!node.length) do ++size; while (node = node.next)
});
return size;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/visit.js
/* harmony default export */ var src_visit = (function(callback) {
var quads = [], q, node = this._root, child, x0, y0, x1, y1;
if (node) quads.push(new src_quad(node, this._x0, this._y0, this._x1, this._y1));
while (q = quads.pop()) {
if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
if (child = node[3]) quads.push(new src_quad(child, xm, ym, x1, y1));
if (child = node[2]) quads.push(new src_quad(child, x0, ym, xm, y1));
if (child = node[1]) quads.push(new src_quad(child, xm, y0, x1, ym));
if (child = node[0]) quads.push(new src_quad(child, x0, y0, xm, ym));
}
}
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/visitAfter.js
/* harmony default export */ var visitAfter = (function(callback) {
var quads = [], next = [], q;
if (this._root) quads.push(new src_quad(this._root, this._x0, this._y0, this._x1, this._y1));
while (q = quads.pop()) {
var node = q.node;
if (node.length) {
var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
if (child = node[0]) quads.push(new src_quad(child, x0, y0, xm, ym));
if (child = node[1]) quads.push(new src_quad(child, xm, y0, x1, ym));
if (child = node[2]) quads.push(new src_quad(child, x0, ym, xm, y1));
if (child = node[3]) quads.push(new src_quad(child, xm, ym, x1, y1));
}
next.push(q);
}
while (q = next.pop()) {
callback(q.node, q.x0, q.y0, q.x1, q.y1);
}
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/x.js
function defaultX(d) {
return d[0];
}
/* harmony default export */ var src_x = (function(_) {
return arguments.length ? (this._x = _, this) : this._x;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/y.js
function defaultY(d) {
return d[1];
}
/* harmony default export */ var src_y = (function(_) {
return arguments.length ? (this._y = _, this) : this._y;
});
// CONCATENATED MODULE: ./node_modules/d3-quadtree/src/quadtree.js
function quadtree_quadtree(nodes, x, y) {
var tree = new quadtree_Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
return nodes == null ? tree : tree.addAll(nodes);
}
function quadtree_Quadtree(x, y, x0, y0, x1, y1) {
this._x = x;
this._y = y;
this._x0 = x0;
this._y0 = y0;
this._x1 = x1;
this._y1 = y1;
this._root = undefined;
}
function quadtree_leaf_copy(leaf) {
var copy = {data: leaf.data}, next = copy;
while (leaf = leaf.next) next = next.next = {data: leaf.data};
return copy;
}
var quadtree_treeProto = quadtree_quadtree.prototype = quadtree_Quadtree.prototype;
quadtree_treeProto.copy = function() {
var copy = new quadtree_Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),
node = this._root,
nodes,
child;
if (!node) return copy;
if (!node.length) return copy._root = quadtree_leaf_copy(node), copy;
nodes = [{source: node, target: copy._root = new Array(4)}];
while (node = nodes.pop()) {
for (var i = 0; i < 4; ++i) {
if (child = node.source[i]) {
if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});
else node.target[i] = quadtree_leaf_copy(child);
}
}
}
return copy;
};
quadtree_treeProto.add = src_add;
quadtree_treeProto.addAll = addAll;
quadtree_treeProto.cover = cover;
quadtree_treeProto.data = src_data;
quadtree_treeProto.extent = d3_quadtree_src_extent;
quadtree_treeProto.find = src_find;
quadtree_treeProto.remove = src_remove;
quadtree_treeProto.removeAll = removeAll;
quadtree_treeProto.root = src_root;
quadtree_treeProto.size = src_size;
quadtree_treeProto.visit = src_visit;
quadtree_treeProto.visitAfter = visitAfter;
quadtree_treeProto.x = src_x;
quadtree_treeProto.y = src_y;
// CONCATENATED MODULE: ./node_modules/d3-force/src/constant.js
/* harmony default export */ var d3_force_src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/jiggle.js
/* harmony default export */ var jiggle = (function() {
return (Math.random() - 0.5) * 1e-6;
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/collide.js
function collide_x(d) {
return d.x + d.vx;
}
function collide_y(d) {
return d.y + d.vy;
}
/* harmony default export */ var collide = (function(radius) {
var nodes,
radii,
strength = 1,
iterations = 1;
if (typeof radius !== "function") radius = d3_force_src_constant(radius == null ? 1 : +radius);
function force() {
var i, n = nodes.length,
tree,
node,
xi,
yi,
ri,
ri2;
for (var k = 0; k < iterations; ++k) {
tree = quadtree_quadtree(nodes, collide_x, collide_y).visitAfter(prepare);
for (i = 0; i < n; ++i) {
node = nodes[i];
ri = radii[node.index], ri2 = ri * ri;
xi = node.x + node.vx;
yi = node.y + node.vy;
tree.visit(apply);
}
}
function apply(quad, x0, y0, x1, y1) {
var data = quad.data, rj = quad.r, r = ri + rj;
if (data) {
if (data.index > node.index) {
var x = xi - data.x - data.vx,
y = yi - data.y - data.vy,
l = x * x + y * y;
if (l < r * r) {
if (x === 0) x = jiggle(), l += x * x;
if (y === 0) y = jiggle(), l += y * y;
l = (r - (l = Math.sqrt(l))) / l * strength;
node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));
node.vy += (y *= l) * r;
data.vx -= x * (r = 1 - r);
data.vy -= y * r;
}
}
return;
}
return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
}
}
function prepare(quad) {
if (quad.data) return quad.r = radii[quad.data.index];
for (var i = quad.r = 0; i < 4; ++i) {
if (quad[i] && quad[i].r > quad.r) {
quad.r = quad[i].r;
}
}
}
function initialize() {
if (!nodes) return;
var i, n = nodes.length, node;
radii = new Array(n);
for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);
}
force.initialize = function(_) {
nodes = _;
initialize();
};
force.iterations = function(_) {
return arguments.length ? (iterations = +_, force) : iterations;
};
force.strength = function(_) {
return arguments.length ? (strength = +_, force) : strength;
};
force.radius = function(_) {
return arguments.length ? (radius = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : radius;
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/link.js
function link_index(d) {
return d.index;
}
function link_find(nodeById, nodeId) {
var node = nodeById.get(nodeId);
if (!node) throw new Error("missing: " + nodeId);
return node;
}
/* harmony default export */ var src_link = (function(links) {
var id = link_index,
strength = defaultStrength,
strengths,
distance = d3_force_src_constant(30),
distances,
nodes,
count,
bias,
iterations = 1;
if (links == null) links = [];
function defaultStrength(link) {
return 1 / Math.min(count[link.source.index], count[link.target.index]);
}
function force(alpha) {
for (var k = 0, n = links.length; k < iterations; ++k) {
for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
link = links[i], source = link.source, target = link.target;
x = target.x + target.vx - source.x - source.vx || jiggle();
y = target.y + target.vy - source.y - source.vy || jiggle();
l = Math.sqrt(x * x + y * y);
l = (l - distances[i]) / l * alpha * strengths[i];
x *= l, y *= l;
target.vx -= x * (b = bias[i]);
target.vy -= y * b;
source.vx += x * (b = 1 - b);
source.vy += y * b;
}
}
}
function initialize() {
if (!nodes) return;
var i,
n = nodes.length,
m = links.length,
nodeById = new Map(nodes.map((d, i) => [id(d, i, nodes), d])),
link;
for (i = 0, count = new Array(n); i < m; ++i) {
link = links[i], link.index = i;
if (typeof link.source !== "object") link.source = link_find(nodeById, link.source);
if (typeof link.target !== "object") link.target = link_find(nodeById, link.target);
count[link.source.index] = (count[link.source.index] || 0) + 1;
count[link.target.index] = (count[link.target.index] || 0) + 1;
}
for (i = 0, bias = new Array(m); i < m; ++i) {
link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
}
strengths = new Array(m), initializeStrength();
distances = new Array(m), initializeDistance();
}
function initializeStrength() {
if (!nodes) return;
for (var i = 0, n = links.length; i < n; ++i) {
strengths[i] = +strength(links[i], i, links);
}
}
function initializeDistance() {
if (!nodes) return;
for (var i = 0, n = links.length; i < n; ++i) {
distances[i] = +distance(links[i], i, links);
}
}
force.initialize = function(_) {
nodes = _;
initialize();
};
force.links = function(_) {
return arguments.length ? (links = _, initialize(), force) : links;
};
force.id = function(_) {
return arguments.length ? (id = _, force) : id;
};
force.iterations = function(_) {
return arguments.length ? (iterations = +_, force) : iterations;
};
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : d3_force_src_constant(+_), initializeStrength(), force) : strength;
};
force.distance = function(_) {
return arguments.length ? (distance = typeof _ === "function" ? _ : d3_force_src_constant(+_), initializeDistance(), force) : distance;
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-dispatch/src/dispatch.js
var dispatch_noop = {value: function() {}};
function dispatch_dispatch() {
for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
if (!(t = arguments[i] + "") || (t in _) || /[\s.]/.test(t)) throw new Error("illegal type: " + t);
_[t] = [];
}
return new Dispatch(_);
}
function Dispatch(_) {
this._ = _;
}
function dispatch_parseTypenames(typenames, types) {
return typenames.trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
return {type: t, name: name};
});
}
Dispatch.prototype = dispatch_dispatch.prototype = {
constructor: Dispatch,
on: function(typename, callback) {
var _ = this._,
T = dispatch_parseTypenames(typename + "", _),
t,
i = -1,
n = T.length;
// If no callback was specified, return the callback of the given type and name.
if (arguments.length < 2) {
while (++i < n) if ((t = (typename = T[i]).type) && (t = dispatch_get(_[t], typename.name))) return t;
return;
}
// If a type was specified, set the callback for the given type and name.
// Otherwise, if a null callback was specified, remove callbacks of the given name.
if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
while (++i < n) {
if (t = (typename = T[i]).type) _[t] = dispatch_set(_[t], typename.name, callback);
else if (callback == null) for (t in _) _[t] = dispatch_set(_[t], typename.name, null);
}
return this;
},
copy: function() {
var copy = {}, _ = this._;
for (var t in _) copy[t] = _[t].slice();
return new Dispatch(copy);
},
call: function(type, that) {
if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
},
apply: function(type, that, args) {
if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
}
};
function dispatch_get(type, name) {
for (var i = 0, n = type.length, c; i < n; ++i) {
if ((c = type[i]).name === name) {
return c.value;
}
}
}
function dispatch_set(type, name, callback) {
for (var i = 0, n = type.length; i < n; ++i) {
if (type[i].name === name) {
type[i] = dispatch_noop, type = type.slice(0, i).concat(type.slice(i + 1));
break;
}
}
if (callback != null) type.push({name: name, value: callback});
return type;
}
/* harmony default export */ var src_dispatch = (dispatch_dispatch);
// CONCATENATED MODULE: ./node_modules/d3-timer/src/timer.js
var timer_frame = 0, // is an animation frame pending?
timeout = 0, // is a timeout pending?
timer_interval = 0, // are any timers active?
pokeDelay = 1000, // how frequently we check for clock skew
taskHead,
taskTail,
clockLast = 0,
clockNow = 0,
clockSkew = 0,
clock = typeof performance === "object" && performance.now ? performance : Date,
setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };
function now() {
return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}
function clearNow() {
clockNow = 0;
}
function timer_Timer() {
this._call =
this._time =
this._next = null;
}
timer_Timer.prototype = timer.prototype = {
constructor: timer_Timer,
restart: function(callback, delay, time) {
if (typeof callback !== "function") throw new TypeError("callback is not a function");
time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);
if (!this._next && taskTail !== this) {
if (taskTail) taskTail._next = this;
else taskHead = this;
taskTail = this;
}
this._call = callback;
this._time = time;
sleep();
},
stop: function() {
if (this._call) {
this._call = null;
this._time = Infinity;
sleep();
}
}
};
function timer(callback, delay, time) {
var t = new timer_Timer;
t.restart(callback, delay, time);
return t;
}
function timerFlush() {
now(); // Get the current time, if not already set.
++timer_frame; // Pretend weve set an alarm, if we havent already.
var t = taskHead, e;
while (t) {
if ((e = clockNow - t._time) >= 0) t._call.call(null, e);
t = t._next;
}
--timer_frame;
}
function wake() {
clockNow = (clockLast = clock.now()) + clockSkew;
timer_frame = timeout = 0;
try {
timerFlush();
} finally {
timer_frame = 0;
nap();
clockNow = 0;
}
}
function poke() {
var now = clock.now(), delay = now - clockLast;
if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
}
function nap() {
var t0, t1 = taskHead, t2, time = Infinity;
while (t1) {
if (t1._call) {
if (time > t1._time) time = t1._time;
t0 = t1, t1 = t1._next;
} else {
t2 = t1._next, t1._next = null;
t1 = t0 ? t0._next = t2 : taskHead = t2;
}
}
taskTail = t0;
sleep(time);
}
function sleep(time) {
if (timer_frame) return; // Soonest alarm already set, or will be.
if (timeout) timeout = clearTimeout(timeout);
var delay = time - clockNow; // Strictly less than if we recomputed clockNow.
if (delay > 24) {
if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);
if (timer_interval) timer_interval = clearInterval(timer_interval);
} else {
if (!timer_interval) clockLast = clock.now(), timer_interval = setInterval(poke, pokeDelay);
timer_frame = 1, setFrame(wake);
}
}
// CONCATENATED MODULE: ./node_modules/d3-force/src/simulation.js
function simulation_x(d) {
return d.x;
}
function simulation_y(d) {
return d.y;
}
var simulation_initialRadius = 10,
simulation_initialAngle = Math.PI * (3 - Math.sqrt(5));
/* harmony default export */ var src_simulation = (function(nodes) {
var simulation,
alpha = 1,
alphaMin = 0.001,
alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),
alphaTarget = 0,
velocityDecay = 0.6,
forces = new Map(),
stepper = timer(step),
event = src_dispatch("tick", "end");
if (nodes == null) nodes = [];
function step() {
tick();
event.call("tick", simulation);
if (alpha < alphaMin) {
stepper.stop();
event.call("end", simulation);
}
}
function tick(iterations) {
var i, n = nodes.length, node;
if (iterations === undefined) iterations = 1;
for (var k = 0; k < iterations; ++k) {
alpha += (alphaTarget - alpha) * alphaDecay;
forces.forEach(function(force) {
force(alpha);
});
for (i = 0; i < n; ++i) {
node = nodes[i];
if (node.fx == null) node.x += node.vx *= velocityDecay;
else node.x = node.fx, node.vx = 0;
if (node.fy == null) node.y += node.vy *= velocityDecay;
else node.y = node.fy, node.vy = 0;
}
}
return simulation;
}
function initializeNodes() {
for (var i = 0, n = nodes.length, node; i < n; ++i) {
node = nodes[i], node.index = i;
if (node.fx != null) node.x = node.fx;
if (node.fy != null) node.y = node.fy;
if (isNaN(node.x) || isNaN(node.y)) {
var radius = simulation_initialRadius * Math.sqrt(i), angle = i * simulation_initialAngle;
node.x = radius * Math.cos(angle);
node.y = radius * Math.sin(angle);
}
if (isNaN(node.vx) || isNaN(node.vy)) {
node.vx = node.vy = 0;
}
}
}
function initializeForce(force) {
if (force.initialize) force.initialize(nodes);
return force;
}
initializeNodes();
return simulation = {
tick: tick,
restart: function() {
return stepper.restart(step), simulation;
},
stop: function() {
return stepper.stop(), simulation;
},
nodes: function(_) {
return arguments.length ? (nodes = _, initializeNodes(), forces.forEach(initializeForce), simulation) : nodes;
},
alpha: function(_) {
return arguments.length ? (alpha = +_, simulation) : alpha;
},
alphaMin: function(_) {
return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
},
alphaDecay: function(_) {
return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
},
alphaTarget: function(_) {
return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
},
velocityDecay: function(_) {
return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
},
force: function(name, _) {
return arguments.length > 1 ? ((_ == null ? forces.delete(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);
},
find: function(x, y, radius) {
var i = 0,
n = nodes.length,
dx,
dy,
d2,
node,
closest;
if (radius == null) radius = Infinity;
else radius *= radius;
for (i = 0; i < n; ++i) {
node = nodes[i];
dx = x - node.x;
dy = y - node.y;
d2 = dx * dx + dy * dy;
if (d2 < radius) closest = node, radius = d2;
}
return closest;
},
on: function(name, _) {
return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
}
};
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/manyBody.js
/* harmony default export */ var manyBody = (function() {
var nodes,
node,
alpha,
strength = d3_force_src_constant(-30),
strengths,
distanceMin2 = 1,
distanceMax2 = Infinity,
theta2 = 0.81;
function force(_) {
var i, n = nodes.length, tree = quadtree_quadtree(nodes, simulation_x, simulation_y).visitAfter(accumulate);
for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);
}
function initialize() {
if (!nodes) return;
var i, n = nodes.length, node;
strengths = new Array(n);
for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);
}
function accumulate(quad) {
var strength = 0, q, c, weight = 0, x, y, i;
// For internal nodes, accumulate forces from child quadrants.
if (quad.length) {
for (x = y = i = 0; i < 4; ++i) {
if ((q = quad[i]) && (c = Math.abs(q.value))) {
strength += q.value, weight += c, x += c * q.x, y += c * q.y;
}
}
quad.x = x / weight;
quad.y = y / weight;
}
// For leaf nodes, accumulate forces from coincident quadrants.
else {
q = quad;
q.x = q.data.x;
q.y = q.data.y;
do strength += strengths[q.data.index];
while (q = q.next);
}
quad.value = strength;
}
function apply(quad, x1, _, x2) {
if (!quad.value) return true;
var x = quad.x - node.x,
y = quad.y - node.y,
w = x2 - x1,
l = x * x + y * y;
// Apply the Barnes-Hut approximation if possible.
// Limit forces for very close nodes; randomize direction if coincident.
if (w * w / theta2 < l) {
if (l < distanceMax2) {
if (x === 0) x = jiggle(), l += x * x;
if (y === 0) y = jiggle(), l += y * y;
if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
node.vx += x * quad.value * alpha / l;
node.vy += y * quad.value * alpha / l;
}
return true;
}
// Otherwise, process points directly.
else if (quad.length || l >= distanceMax2) return;
// Limit forces for very close nodes; randomize direction if coincident.
if (quad.data !== node || quad.next) {
if (x === 0) x = jiggle(), l += x * x;
if (y === 0) y = jiggle(), l += y * y;
if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);
}
do if (quad.data !== node) {
w = strengths[quad.data.index] * alpha / l;
node.vx += x * w;
node.vy += y * w;
} while (quad = quad.next);
}
force.initialize = function(_) {
nodes = _;
initialize();
};
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : strength;
};
force.distanceMin = function(_) {
return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
};
force.distanceMax = function(_) {
return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
};
force.theta = function(_) {
return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/radial.js
/* harmony default export */ var radial = (function(radius, x, y) {
var nodes,
strength = d3_force_src_constant(0.1),
strengths,
radiuses;
if (typeof radius !== "function") radius = d3_force_src_constant(+radius);
if (x == null) x = 0;
if (y == null) y = 0;
function force(alpha) {
for (var i = 0, n = nodes.length; i < n; ++i) {
var node = nodes[i],
dx = node.x - x || 1e-6,
dy = node.y - y || 1e-6,
r = Math.sqrt(dx * dx + dy * dy),
k = (radiuses[i] - r) * strengths[i] * alpha / r;
node.vx += dx * k;
node.vy += dy * k;
}
}
function initialize() {
if (!nodes) return;
var i, n = nodes.length;
strengths = new Array(n);
radiuses = new Array(n);
for (i = 0; i < n; ++i) {
radiuses[i] = +radius(nodes[i], i, nodes);
strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
}
}
force.initialize = function(_) {
nodes = _, initialize();
};
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : strength;
};
force.radius = function(_) {
return arguments.length ? (radius = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : radius;
};
force.x = function(_) {
return arguments.length ? (x = +_, force) : x;
};
force.y = function(_) {
return arguments.length ? (y = +_, force) : y;
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/x.js
/* harmony default export */ var d3_force_src_x = (function(x) {
var strength = d3_force_src_constant(0.1),
nodes,
strengths,
xz;
if (typeof x !== "function") x = d3_force_src_constant(x == null ? 0 : +x);
function force(alpha) {
for (var i = 0, n = nodes.length, node; i < n; ++i) {
node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
}
}
function initialize() {
if (!nodes) return;
var i, n = nodes.length;
strengths = new Array(n);
xz = new Array(n);
for (i = 0; i < n; ++i) {
strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
}
}
force.initialize = function(_) {
nodes = _;
initialize();
};
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : strength;
};
force.x = function(_) {
return arguments.length ? (x = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : x;
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/y.js
/* harmony default export */ var d3_force_src_y = (function(y) {
var strength = d3_force_src_constant(0.1),
nodes,
strengths,
yz;
if (typeof y !== "function") y = d3_force_src_constant(y == null ? 0 : +y);
function force(alpha) {
for (var i = 0, n = nodes.length, node; i < n; ++i) {
node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
}
}
function initialize() {
if (!nodes) return;
var i, n = nodes.length;
strengths = new Array(n);
yz = new Array(n);
for (i = 0; i < n; ++i) {
strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
}
}
force.initialize = function(_) {
nodes = _;
initialize();
};
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : strength;
};
force.y = function(_) {
return arguments.length ? (y = typeof _ === "function" ? _ : d3_force_src_constant(+_), initialize(), force) : y;
};
return force;
});
// CONCATENATED MODULE: ./node_modules/d3-force/src/index.js
// CONCATENATED MODULE: ./node_modules/vega-force/src/Force.js
var Force_ForceMap = {
center: src_center,
collide: collide,
nbody: manyBody,
link: src_link,
x: d3_force_src_x,
y: d3_force_src_y
};
var Force_Forces = 'forces',
Force_ForceParams = [
'alpha', 'alphaMin', 'alphaTarget',
'velocityDecay', 'forces'
],
Force_ForceConfig = ['static', 'iterations'],
Force_ForceOutput = ['x', 'y', 'vx', 'vy'];
/**
* Force simulation layout.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<object>} params.forces - The forces to apply.
*/
function Force_Force(params) {
Transform_Transform.call(this, null, params);
}
Force_Force.Definition = {
"type": "Force",
"metadata": {"modifies": true},
"params": [
{ "name": "static", "type": "boolean", "default": false },
{ "name": "restart", "type": "boolean", "default": false },
{ "name": "iterations", "type": "number", "default": 300 },
{ "name": "alpha", "type": "number", "default": 1 },
{ "name": "alphaMin", "type": "number", "default": 0.001 },
{ "name": "alphaTarget", "type": "number", "default": 0 },
{ "name": "velocityDecay", "type": "number", "default": 0.4 },
{ "name": "forces", "type": "param", "array": true,
"params": [
{
"key": {"force": "center"},
"params": [
{ "name": "x", "type": "number", "default": 0 },
{ "name": "y", "type": "number", "default": 0 }
]
},
{
"key": {"force": "collide"},
"params": [
{ "name": "radius", "type": "number", "expr": true },
{ "name": "strength", "type": "number", "default": 0.7 },
{ "name": "iterations", "type": "number", "default": 1 }
]
},
{
"key": {"force": "nbody"},
"params": [
{ "name": "strength", "type": "number", "default": -30 },
{ "name": "theta", "type": "number", "default": 0.9 },
{ "name": "distanceMin", "type": "number", "default": 1 },
{ "name": "distanceMax", "type": "number" }
]
},
{
"key": {"force": "link"},
"params": [
{ "name": "links", "type": "data" },
{ "name": "id", "type": "field" },
{ "name": "distance", "type": "number", "default": 30, "expr": true },
{ "name": "strength", "type": "number", "expr": true },
{ "name": "iterations", "type": "number", "default": 1 }
]
},
{
"key": {"force": "x"},
"params": [
{ "name": "strength", "type": "number", "default": 0.1 },
{ "name": "x", "type": "field" }
]
},
{
"key": {"force": "y"},
"params": [
{ "name": "strength", "type": "number", "default": 0.1 },
{ "name": "y", "type": "field" }
]
}
] },
{
"name": "as", "type": "string", "array": true, "modify": false,
"default": Force_ForceOutput
}
]
};
var Force_prototype = Object(vega_util["y" /* inherits */])(Force_Force, Transform_Transform);
Force_prototype.transform = function(_, pulse) {
var sim = this.value,
change = pulse.changed(pulse.ADD_REM),
params = _.modified(Force_ForceParams),
iters = _.iterations || 300;
// configure simulation
if (!sim) {
this.value = sim = Force_simulation(pulse.source, _);
sim.on('tick', Force_rerun(pulse.dataflow, this));
if (!_.static) {
change = true;
sim.tick(); // ensure we run on init
}
pulse.modifies('index');
} else {
if (change) {
pulse.modifies('index');
sim.nodes(pulse.source);
}
if (params || pulse.changed(pulse.MOD)) {
Force_setup(sim, _, 0, pulse);
}
}
// run simulation
if (params || change || _.modified(Force_ForceConfig)
|| (pulse.changed() && _.restart))
{
sim.alpha(Math.max(sim.alpha(), _.alpha || 1))
.alphaDecay(1 - Math.pow(sim.alphaMin(), 1 / iters));
if (_.static) {
for (sim.stop(); --iters >= 0;) sim.tick();
} else {
if (sim.stopped()) sim.restart();
if (!change) return pulse.StopPropagation; // defer to sim ticks
}
}
return this.finish(_, pulse);
};
Force_prototype.finish = function(_, pulse) {
var dataflow = pulse.dataflow;
// inspect dependencies, touch link source data
for (var args=this._argops, j=0, m=args.length, arg; j<m; ++j) {
arg = args[j];
if (arg.name !== Force_Forces || arg.op._argval.force !== 'link') {
continue;
}
for (var ops=arg.op._argops, i=0, n=ops.length, op; i<n; ++i) {
if (ops[i].name === 'links' && (op = ops[i].op.source)) {
dataflow.pulse(op, dataflow.changeset().reflow());
break;
}
}
}
// reflow all nodes
return pulse.reflow(_.modified()).modifies(Force_ForceOutput);
};
function Force_rerun(df, op) {
return function() { df.touch(op).run(); }
}
function Force_simulation(nodes, _) {
var sim = src_simulation(nodes),
stopped = false,
stop = sim.stop,
restart = sim.restart;
sim.stopped = function() {
return stopped;
};
sim.restart = function() {
stopped = false;
return restart();
};
sim.stop = function() {
stopped = true;
return stop();
};
return Force_setup(sim, _, true).on('end', function() { stopped = true; });
}
function Force_setup(sim, _, init, pulse) {
var f = Object(vega_util["i" /* array */])(_.forces), i, n, p, name;
for (i=0, n=Force_ForceParams.length; i<n; ++i) {
p = Force_ForceParams[i];
if (p !== Force_Forces && _.modified(p)) sim[p](_[p]);
}
for (i=0, n=f.length; i<n; ++i) {
name = Force_Forces + i;
p = init || _.modified(Force_Forces, i) ? Force_getForce(f[i])
: pulse && Force_modified(f[i], pulse) ? sim.force(name)
: null;
if (p) sim.force(name, p);
}
for (n=(sim.numForces || 0); i<n; ++i) {
sim.force(Force_Forces + i, null); // remove
}
sim.numForces = f.length;
return sim;
}
function Force_modified(f, pulse) {
var k, v;
for (k in f) {
if (Object(vega_util["D" /* isFunction */])(v = f[k]) && pulse.modified(Object(vega_util["g" /* accessorFields */])(v)))
return 1;
}
return 0;
}
function Force_getForce(_) {
var f, p;
if (!Object(vega_util["v" /* hasOwnProperty */])(Force_ForceMap, _.force)) {
Object(vega_util["n" /* error */])('Unrecognized force: ' + _.force);
}
f = Force_ForceMap[_.force]();
for (p in _) {
if (Object(vega_util["D" /* isFunction */])(f[p])) Force_setForceParam(f[p], _[p], _);
}
return f;
}
function Force_setForceParam(f, v, _) {
f(Object(vega_util["D" /* isFunction */])(v) ? function(d) { return v(d, _); } : v);
}
// CONCATENATED MODULE: ./node_modules/vega-force/index.js
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/lookup.js
// Build lookup table mapping tuple keys to tree node instances
/* harmony default export */ var src_lookup = (function(tree, key, filter) {
var map = {};
tree.each(function(node) {
var t = node.data;
if (filter(t)) map[key(t)] = node;
});
tree.lookup = map;
return tree;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/count.js
function count_count(node) {
var sum = 0,
children = node.children,
i = children && children.length;
if (!i) sum = 1;
else while (--i >= 0) sum += children[i].value;
node.value = sum;
}
/* harmony default export */ var hierarchy_count = (function() {
return this.eachAfter(count_count);
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/each.js
/* harmony default export */ var hierarchy_each = (function(callback) {
var node = this, current, next = [node], children, i, n;
do {
current = next.reverse(), next = [];
while (node = current.pop()) {
callback(node), children = node.children;
if (children) for (i = 0, n = children.length; i < n; ++i) {
next.push(children[i]);
}
}
} while (next.length);
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
/* harmony default export */ var eachBefore = (function(callback) {
var node = this, nodes = [node], children, i;
while (node = nodes.pop()) {
callback(node), children = node.children;
if (children) for (i = children.length - 1; i >= 0; --i) {
nodes.push(children[i]);
}
}
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
/* harmony default export */ var eachAfter = (function(callback) {
var node = this, nodes = [node], next = [], children, i, n;
while (node = nodes.pop()) {
next.push(node), children = node.children;
if (children) for (i = 0, n = children.length; i < n; ++i) {
nodes.push(children[i]);
}
}
while (node = next.pop()) {
callback(node);
}
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/sum.js
/* harmony default export */ var hierarchy_sum = (function(value) {
return this.eachAfter(function(node) {
var sum = +value(node.data) || 0,
children = node.children,
i = children && children.length;
while (--i >= 0) sum += children[i].value;
node.value = sum;
});
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/sort.js
/* harmony default export */ var hierarchy_sort = (function(compare) {
return this.eachBefore(function(node) {
if (node.children) {
node.children.sort(compare);
}
});
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/path.js
/* harmony default export */ var hierarchy_path = (function(end) {
var start = this,
ancestor = leastCommonAncestor(start, end),
nodes = [start];
while (start !== ancestor) {
start = start.parent;
nodes.push(start);
}
var k = nodes.length;
while (end !== ancestor) {
nodes.splice(k, 0, end);
end = end.parent;
}
return nodes;
});
function leastCommonAncestor(a, b) {
if (a === b) return a;
var aNodes = a.ancestors(),
bNodes = b.ancestors(),
c = null;
a = aNodes.pop();
b = bNodes.pop();
while (a === b) {
c = a;
a = aNodes.pop();
b = bNodes.pop();
}
return c;
}
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/ancestors.js
/* harmony default export */ var ancestors = (function() {
var node = this, nodes = [node];
while (node = node.parent) {
nodes.push(node);
}
return nodes;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/descendants.js
/* harmony default export */ var descendants = (function() {
var nodes = [];
this.each(function(node) {
nodes.push(node);
});
return nodes;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/leaves.js
/* harmony default export */ var leaves = (function() {
var leaves = [];
this.eachBefore(function(node) {
if (!node.children) {
leaves.push(node);
}
});
return leaves;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/links.js
/* harmony default export */ var hierarchy_links = (function() {
var root = this, links = [];
root.each(function(node) {
if (node !== root) { // Dont include the roots parent, if any.
links.push({source: node.parent, target: node});
}
});
return links;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/hierarchy/index.js
function hierarchy_hierarchy(data, children) {
var root = new hierarchy_Node(data),
valued = +data.value && (root.value = data.value),
node,
nodes = [root],
child,
childs,
i,
n;
if (children == null) children = hierarchy_defaultChildren;
while (node = nodes.pop()) {
if (valued) node.value = +node.data.value;
if ((childs = children(node.data)) && (n = childs.length)) {
node.children = new Array(n);
for (i = n - 1; i >= 0; --i) {
nodes.push(child = node.children[i] = new hierarchy_Node(childs[i]));
child.parent = node;
child.depth = node.depth + 1;
}
}
}
return root.eachBefore(hierarchy_computeHeight);
}
function hierarchy_node_copy() {
return hierarchy_hierarchy(this).eachBefore(hierarchy_copyData);
}
function hierarchy_defaultChildren(d) {
return d.children;
}
function hierarchy_copyData(node) {
node.data = node.data.data;
}
function hierarchy_computeHeight(node) {
var height = 0;
do node.height = height;
while ((node = node.parent) && (node.height < ++height));
}
function hierarchy_Node(data) {
this.data = data;
this.depth =
this.height = 0;
this.parent = null;
}
hierarchy_Node.prototype = hierarchy_hierarchy.prototype = {
constructor: hierarchy_Node,
count: hierarchy_count,
each: hierarchy_each,
eachAfter: eachAfter,
eachBefore: eachBefore,
sum: hierarchy_sum,
sort: hierarchy_sort,
path: hierarchy_path,
ancestors: ancestors,
descendants: descendants,
leaves: leaves,
links: hierarchy_links,
copy: hierarchy_node_copy
};
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/Nest.js
/**
* Nest tuples into a tree structure, grouped by key values.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *>} params.keys - The key fields to nest by, in order.
* @param {boolean} [params.generate=false] - A boolean flag indicating if
* non-leaf nodes generated by this transform should be included in the
* output. The default (false) includes only the input data (leaf nodes)
* in the data stream.
*/
function Nest_Nest(params) {
Transform_Transform.call(this, null, params);
}
Nest_Nest.Definition = {
"type": "Nest",
"metadata": {"treesource": true, "changes": true},
"params": [
{ "name": "keys", "type": "field", "array": true },
{ "name": "generate", "type": "boolean" }
]
};
var Nest_prototype = Object(vega_util["y" /* inherits */])(Nest_Nest, Transform_Transform);
function Nest_children(n) {
return n.values;
}
Nest_prototype.transform = function(_, pulse) {
if (!pulse.source) {
Object(vega_util["n" /* error */])('Nest transform requires an upstream data source.');
}
var gen = _.generate,
mod = _.modified(),
out = pulse.clone(),
tree = this.value;
if (!tree || mod || pulse.changed()) {
// collect nodes to remove
if (tree) {
tree.each(node => {
if (node.children && isTuple(node.data)) {
out.rem.push(node.data);
}
});
}
// generate new tree structure
this.value = tree = hierarchy_hierarchy({
values: Object(vega_util["i" /* array */])(_.keys)
.reduce((n, k) => { n.key(k); return n; }, Nest_nest())
.entries(out.source)
}, Nest_children);
// collect nodes to add
if (gen) {
tree.each(node => {
if (node.children) {
node = Tuple_ingest(node.data);
out.add.push(node);
out.source.push(node);
}
});
}
// build lookup table
src_lookup(tree, tupleid, tupleid);
}
out.source.root = tree;
return out;
};
function Nest_nest() {
var keys = [],
nest;
function apply(array, depth) {
if (depth >= keys.length) {
return array;
}
var i = -1,
n = array.length,
key = keys[depth++],
keyValue,
value,
valuesByKey = {},
values,
result = {};
while (++i < n) {
keyValue = key(value = array[i]) + '';
if (values = valuesByKey[keyValue]) {
values.push(value);
} else {
valuesByKey[keyValue] = [value];
}
}
for (keyValue in valuesByKey) {
result[keyValue] = apply(valuesByKey[keyValue], depth);
}
return result;
}
function entries(map, depth) {
if (++depth > keys.length) return map;
var array = [], k;
for (k in map) {
array.push({key: k, values: entries(map[k], depth)});
}
return array;
}
return nest = {
entries: array => entries(apply(array, 0), 0),
key: d => { keys.push(d); return nest; }
};
}
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/HierarchyLayout.js
/**
* Abstract class for tree layout.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function HierarchyLayout_HierarchyLayout(params) {
Transform_Transform.call(this, null, params);
}
var HierarchyLayout_prototype = Object(vega_util["y" /* inherits */])(HierarchyLayout_HierarchyLayout, Transform_Transform);
HierarchyLayout_prototype.transform = function(_, pulse) {
if (!pulse.source || !pulse.source.root) {
Object(vega_util["n" /* error */])(this.constructor.name
+ ' transform requires a backing tree data source.');
}
var layout = this.layout(_.method),
fields = this.fields,
root = pulse.source.root,
as = _.as || fields;
if (_.field) root.sum(_.field); else root.count();
if (_.sort) root.sort(stableCompare(_.sort, d => d.data));
HierarchyLayout_setParams(layout, this.params, _);
if (layout.separation) {
layout.separation(_.separation !== false ? HierarchyLayout_defaultSeparation : vega_util["O" /* one */]);
}
try {
this.value = layout(root);
} catch (err) {
Object(vega_util["n" /* error */])(err);
}
root.each(function(node) { HierarchyLayout_setFields(node, fields, as); });
return pulse.reflow(_.modified()).modifies(as).modifies('leaf');
};
function HierarchyLayout_setParams(layout, params, _) {
for (var p, i=0, n=params.length; i<n; ++i) {
p = params[i];
if (p in _) layout[p](_[p]);
}
}
function HierarchyLayout_setFields(node, fields, as) {
var t = node.data;
for (var i=0, n=fields.length-1; i<n; ++i) {
t[as[i]] = node[fields[i]];
}
t[as[n]] = node.children ? node.children.length : 0;
}
function HierarchyLayout_defaultSeparation(a, b) {
return a.parent === b.parent ? 1 : 2;
}
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/array.js
var src_array_slice = Array.prototype.slice;
function array_shuffle(array) {
var m = array.length,
t,
i;
while (m) {
i = Math.random() * m-- | 0;
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/pack/enclose.js
/* harmony default export */ var enclose = (function(circles) {
var i = 0, n = (circles = array_shuffle(src_array_slice.call(circles))).length, B = [], p, e;
while (i < n) {
p = circles[i];
if (e && enclose_enclosesWeak(e, p)) ++i;
else e = enclose_encloseBasis(B = enclose_extendBasis(B, p)), i = 0;
}
return e;
});
function enclose_extendBasis(B, p) {
var i, j;
if (enclose_enclosesWeakAll(p, B)) return [p];
// If we get here then B must have at least one element.
for (i = 0; i < B.length; ++i) {
if (enclose_enclosesNot(p, B[i])
&& enclose_enclosesWeakAll(enclose_encloseBasis2(B[i], p), B)) {
return [B[i], p];
}
}
// If we get here then B must have at least two elements.
for (i = 0; i < B.length - 1; ++i) {
for (j = i + 1; j < B.length; ++j) {
if (enclose_enclosesNot(enclose_encloseBasis2(B[i], B[j]), p)
&& enclose_enclosesNot(enclose_encloseBasis2(B[i], p), B[j])
&& enclose_enclosesNot(enclose_encloseBasis2(B[j], p), B[i])
&& enclose_enclosesWeakAll(enclose_encloseBasis3(B[i], B[j], p), B)) {
return [B[i], B[j], p];
}
}
}
// If we get here then something is very wrong.
throw new Error;
}
function enclose_enclosesNot(a, b) {
var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;
return dr < 0 || dr * dr < dx * dx + dy * dy;
}
function enclose_enclosesWeak(a, b) {
var dr = a.r - b.r + 1e-6, dx = b.x - a.x, dy = b.y - a.y;
return dr > 0 && dr * dr > dx * dx + dy * dy;
}
function enclose_enclosesWeakAll(a, B) {
for (var i = 0; i < B.length; ++i) {
if (!enclose_enclosesWeak(a, B[i])) {
return false;
}
}
return true;
}
function enclose_encloseBasis(B) {
switch (B.length) {
case 1: return enclose_encloseBasis1(B[0]);
case 2: return enclose_encloseBasis2(B[0], B[1]);
case 3: return enclose_encloseBasis3(B[0], B[1], B[2]);
}
}
function enclose_encloseBasis1(a) {
return {
x: a.x,
y: a.y,
r: a.r
};
}
function enclose_encloseBasis2(a, b) {
var x1 = a.x, y1 = a.y, r1 = a.r,
x2 = b.x, y2 = b.y, r2 = b.r,
x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
l = Math.sqrt(x21 * x21 + y21 * y21);
return {
x: (x1 + x2 + x21 / l * r21) / 2,
y: (y1 + y2 + y21 / l * r21) / 2,
r: (l + r1 + r2) / 2
};
}
function enclose_encloseBasis3(a, b, c) {
var x1 = a.x, y1 = a.y, r1 = a.r,
x2 = b.x, y2 = b.y, r2 = b.r,
x3 = c.x, y3 = c.y, r3 = c.r,
a2 = x1 - x2,
a3 = x1 - x3,
b2 = y1 - y2,
b3 = y1 - y3,
c2 = r2 - r1,
c3 = r3 - r1,
d1 = x1 * x1 + y1 * y1 - r1 * r1,
d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,
d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,
ab = a3 * b2 - a2 * b3,
xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,
xb = (b3 * c2 - b2 * c3) / ab,
ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,
yb = (a2 * c3 - a3 * c2) / ab,
A = xb * xb + yb * yb - 1,
B = 2 * (r1 + xa * xb + ya * yb),
C = xa * xa + ya * ya - r1 * r1,
r = -(A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B);
return {
x: x1 + xa + xb * r,
y: y1 + ya + yb * r,
r: r
};
}
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/pack/siblings.js
function siblings_place(b, a, c) {
var dx = b.x - a.x, x, a2,
dy = b.y - a.y, y, b2,
d2 = dx * dx + dy * dy;
if (d2) {
a2 = a.r + c.r, a2 *= a2;
b2 = b.r + c.r, b2 *= b2;
if (a2 > b2) {
x = (d2 + b2 - a2) / (2 * d2);
y = Math.sqrt(Math.max(0, b2 / d2 - x * x));
c.x = b.x - x * dx - y * dy;
c.y = b.y - x * dy + y * dx;
} else {
x = (d2 + a2 - b2) / (2 * d2);
y = Math.sqrt(Math.max(0, a2 / d2 - x * x));
c.x = a.x + x * dx - y * dy;
c.y = a.y + x * dy + y * dx;
}
} else {
c.x = a.x + c.r;
c.y = a.y;
}
}
function siblings_intersects(a, b) {
var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y;
return dr > 0 && dr * dr > dx * dx + dy * dy;
}
function siblings_score(node) {
var a = node._,
b = node.next._,
ab = a.r + b.r,
dx = (a.x * b.r + b.x * a.r) / ab,
dy = (a.y * b.r + b.y * a.r) / ab;
return dx * dx + dy * dy;
}
function siblings_Node(circle) {
this._ = circle;
this.next = null;
this.previous = null;
}
function siblings_packEnclose(circles) {
if (!(n = circles.length)) return 0;
var a, b, c, n, aa, ca, i, j, k, sj, sk;
// Place the first circle.
a = circles[0], a.x = 0, a.y = 0;
if (!(n > 1)) return a.r;
// Place the second circle.
b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;
if (!(n > 2)) return a.r + b.r;
// Place the third circle.
siblings_place(b, a, c = circles[2]);
// Initialize the front-chain using the first three circles a, b and c.
a = new siblings_Node(a), b = new siblings_Node(b), c = new siblings_Node(c);
a.next = c.previous = b;
b.next = a.previous = c;
c.next = b.previous = a;
// Attempt to place each remaining circle…
pack: for (i = 3; i < n; ++i) {
siblings_place(a._, b._, c = circles[i]), c = new siblings_Node(c);
// Find the closest intersecting circle on the front-chain, if any.
// “Closeness” is determined by linear distance along the front-chain.
// “Ahead” or “behind” is likewise determined by linear distance.
j = b.next, k = a.previous, sj = b._.r, sk = a._.r;
do {
if (sj <= sk) {
if (siblings_intersects(j._, c._)) {
b = j, a.next = b, b.previous = a, --i;
continue pack;
}
sj += j._.r, j = j.next;
} else {
if (siblings_intersects(k._, c._)) {
a = k, a.next = b, b.previous = a, --i;
continue pack;
}
sk += k._.r, k = k.previous;
}
} while (j !== k.next);
// Success! Insert the new circle c between a and b.
c.previous = a, c.next = b, a.next = b.previous = b = c;
// Compute the new closest circle pair to the centroid.
aa = siblings_score(a);
while ((c = c.next) !== b) {
if ((ca = siblings_score(c)) < aa) {
a = c, aa = ca;
}
}
b = a.next;
}
// Compute the enclosing circle of the front chain.
a = [b._], c = b; while ((c = c.next) !== b) a.push(c._); c = enclose(a);
// Translate the circles to put the enclosing circle around the origin.
for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y;
return c.r;
}
/* harmony default export */ var siblings = (function(circles) {
siblings_packEnclose(circles);
return circles;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/accessors.js
function optional(f) {
return f == null ? null : required(f);
}
function required(f) {
if (typeof f !== "function") throw new Error;
return f;
}
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/constant.js
function constantZero() {
return 0;
}
/* harmony default export */ var d3_hierarchy_src_constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/pack/index.js
function pack_defaultRadius(d) {
return Math.sqrt(d.value);
}
/* harmony default export */ var src_pack = (function() {
var radius = null,
dx = 1,
dy = 1,
padding = constantZero;
function pack(root) {
root.x = dx / 2, root.y = dy / 2;
if (radius) {
root.eachBefore(pack_radiusLeaf(radius))
.eachAfter(pack_packChildren(padding, 0.5))
.eachBefore(pack_translateChild(1));
} else {
root.eachBefore(pack_radiusLeaf(pack_defaultRadius))
.eachAfter(pack_packChildren(constantZero, 1))
.eachAfter(pack_packChildren(padding, root.r / Math.min(dx, dy)))
.eachBefore(pack_translateChild(Math.min(dx, dy) / (2 * root.r)));
}
return root;
}
pack.radius = function(x) {
return arguments.length ? (radius = optional(x), pack) : radius;
};
pack.size = function(x) {
return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy];
};
pack.padding = function(x) {
return arguments.length ? (padding = typeof x === "function" ? x : d3_hierarchy_src_constant(+x), pack) : padding;
};
return pack;
});
function pack_radiusLeaf(radius) {
return function(node) {
if (!node.children) {
node.r = Math.max(0, +radius(node) || 0);
}
};
}
function pack_packChildren(padding, k) {
return function(node) {
if (children = node.children) {
var children,
i,
n = children.length,
r = padding(node) * k || 0,
e;
if (r) for (i = 0; i < n; ++i) children[i].r += r;
e = siblings_packEnclose(children);
if (r) for (i = 0; i < n; ++i) children[i].r -= r;
node.r = e + r;
}
};
}
function pack_translateChild(k) {
return function(node) {
var parent = node.parent;
node.r *= k;
if (parent) {
node.x = parent.x + k * node.x;
node.y = parent.y + k * node.y;
}
};
}
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/Pack.js
var Pack_Output = ['x', 'y', 'r', 'depth', 'children'];
/**
* Packed circle tree layout.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to size nodes.
*/
function Pack_Pack(params) {
HierarchyLayout_HierarchyLayout.call(this, params);
}
Pack_Pack.Definition = {
"type": "Pack",
"metadata": {"tree": true, "modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "sort", "type": "compare" },
{ "name": "padding", "type": "number", "default": 0 },
{ "name": "radius", "type": "field", "default": null },
{ "name": "size", "type": "number", "array": true, "length": 2 },
{ "name": "as", "type": "string", "array": true, "length": Pack_Output.length, "default": Pack_Output }
]
};
var Pack_prototype = Object(vega_util["y" /* inherits */])(Pack_Pack, HierarchyLayout_HierarchyLayout);
Pack_prototype.layout = src_pack;
Pack_prototype.params = ['radius', 'size', 'padding'];
Pack_prototype.fields = Pack_Output;
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/round.js
/* harmony default export */ var treemap_round = (function(node) {
node.x0 = Math.round(node.x0);
node.y0 = Math.round(node.y0);
node.x1 = Math.round(node.x1);
node.y1 = Math.round(node.y1);
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/dice.js
/* harmony default export */ var dice = (function(parent, x0, y0, x1, y1) {
var nodes = parent.children,
node,
i = -1,
n = nodes.length,
k = parent.value && (x1 - x0) / parent.value;
while (++i < n) {
node = nodes[i], node.y0 = y0, node.y1 = y1;
node.x0 = x0, node.x1 = x0 += node.value * k;
}
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/partition.js
/* harmony default export */ var src_partition = (function() {
var dx = 1,
dy = 1,
padding = 0,
round = false;
function partition(root) {
var n = root.height + 1;
root.x0 =
root.y0 = padding;
root.x1 = dx;
root.y1 = dy / n;
root.eachBefore(positionNode(dy, n));
if (round) root.eachBefore(treemap_round);
return root;
}
function positionNode(dy, n) {
return function(node) {
if (node.children) {
dice(node, node.x0, dy * (node.depth + 1) / n, node.x1, dy * (node.depth + 2) / n);
}
var x0 = node.x0,
y0 = node.y0,
x1 = node.x1 - padding,
y1 = node.y1 - padding;
if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
node.x0 = x0;
node.y0 = y0;
node.x1 = x1;
node.y1 = y1;
};
}
partition.round = function(x) {
return arguments.length ? (round = !!x, partition) : round;
};
partition.size = function(x) {
return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy];
};
partition.padding = function(x) {
return arguments.length ? (padding = +x, partition) : padding;
};
return partition;
});
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/Partition.js
var Partition_Output = ['x0', 'y0', 'x1', 'y1', 'depth', 'children'];
/**
* Partition tree layout.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to size nodes.
*/
function Partition_Partition(params) {
HierarchyLayout_HierarchyLayout.call(this, params);
}
Partition_Partition.Definition = {
"type": "Partition",
"metadata": {"tree": true, "modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "sort", "type": "compare" },
{ "name": "padding", "type": "number", "default": 0 },
{ "name": "round", "type": "boolean", "default": false },
{ "name": "size", "type": "number", "array": true, "length": 2 },
{ "name": "as", "type": "string", "array": true, "length": Partition_Output.length, "default": Partition_Output }
]
};
var Partition_prototype = Object(vega_util["y" /* inherits */])(Partition_Partition, HierarchyLayout_HierarchyLayout);
Partition_prototype.layout = src_partition;
Partition_prototype.params = ['size', 'round', 'padding'];
Partition_prototype.fields = Partition_Output;
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/stratify.js
var stratify_keyPrefix = "$", // Protect against keys like “__proto__”.
stratify_preroot = {depth: -1},
stratify_ambiguous = {};
function stratify_defaultId(d) {
return d.id;
}
function stratify_defaultParentId(d) {
return d.parentId;
}
/* harmony default export */ var src_stratify = (function() {
var id = stratify_defaultId,
parentId = stratify_defaultParentId;
function stratify(data) {
var d,
i,
n = data.length,
root,
parent,
node,
nodes = new Array(n),
nodeId,
nodeKey,
nodeByKey = {};
for (i = 0; i < n; ++i) {
d = data[i], node = nodes[i] = new hierarchy_Node(d);
if ((nodeId = id(d, i, data)) != null && (nodeId += "")) {
nodeKey = stratify_keyPrefix + (node.id = nodeId);
nodeByKey[nodeKey] = nodeKey in nodeByKey ? stratify_ambiguous : node;
}
}
for (i = 0; i < n; ++i) {
node = nodes[i], nodeId = parentId(data[i], i, data);
if (nodeId == null || !(nodeId += "")) {
if (root) throw new Error("multiple roots");
root = node;
} else {
parent = nodeByKey[stratify_keyPrefix + nodeId];
if (!parent) throw new Error("missing: " + nodeId);
if (parent === stratify_ambiguous) throw new Error("ambiguous: " + nodeId);
if (parent.children) parent.children.push(node);
else parent.children = [node];
node.parent = parent;
}
}
if (!root) throw new Error("no root");
root.parent = stratify_preroot;
root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(hierarchy_computeHeight);
root.parent = null;
if (n > 0) throw new Error("cycle");
return root;
}
stratify.id = function(x) {
return arguments.length ? (id = required(x), stratify) : id;
};
stratify.parentId = function(x) {
return arguments.length ? (parentId = required(x), stratify) : parentId;
};
return stratify;
});
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/Stratify.js
/**
* Stratify a collection of tuples into a tree structure based on
* id and parent id fields.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.key - Unique key field for each tuple.
* @param {function(object): *} params.parentKey - Field with key for parent tuple.
*/
function Stratify_Stratify(params) {
Transform_Transform.call(this, null, params);
}
Stratify_Stratify.Definition = {
"type": "Stratify",
"metadata": {"treesource": true},
"params": [
{ "name": "key", "type": "field", "required": true },
{ "name": "parentKey", "type": "field", "required": true }
]
};
var Stratify_prototype = Object(vega_util["y" /* inherits */])(Stratify_Stratify, Transform_Transform);
Stratify_prototype.transform = function(_, pulse) {
if (!pulse.source) {
Object(vega_util["n" /* error */])('Stratify transform requires an upstream data source.');
}
var tree = this.value,
mod = _.modified(),
out = pulse.fork(pulse.ALL).materialize(pulse.SOURCE),
run = !this.value
|| mod
|| pulse.changed(pulse.ADD_REM)
|| pulse.modified(_.key.fields)
|| pulse.modified(_.parentKey.fields);
// prevent upstream source pollution
out.source = out.source.slice();
if (run) {
if (out.source.length) {
tree = src_lookup(
src_stratify().id(_.key).parentId(_.parentKey)(out.source)
, _.key, vega_util["Ga" /* truthy */]);
} else {
tree = src_lookup(src_stratify()([{}]), _.key, _.key);
}
}
out.source.root = this.value = tree;
return out;
};
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/tree.js
function tree_defaultSeparation(a, b) {
return a.parent === b.parent ? 1 : 2;
}
// function radialSeparation(a, b) {
// return (a.parent === b.parent ? 1 : 2) / a.depth;
// }
// This function is used to traverse the left contour of a subtree (or
// subforest). It returns the successor of v on this contour. This successor is
// either given by the leftmost child of v or by the thread of v. The function
// returns null if and only if v is on the highest level of its subtree.
function tree_nextLeft(v) {
var children = v.children;
return children ? children[0] : v.t;
}
// This function works analogously to nextLeft.
function tree_nextRight(v) {
var children = v.children;
return children ? children[children.length - 1] : v.t;
}
// Shifts the current subtree rooted at w+. This is done by increasing
// prelim(w+) and mod(w+) by shift.
function tree_moveSubtree(wm, wp, shift) {
var change = shift / (wp.i - wm.i);
wp.c -= change;
wp.s += shift;
wm.c += change;
wp.z += shift;
wp.m += shift;
}
// All other shifts, applied to the smaller subtrees between w- and w+, are
// performed by this function. To prepare the shifts, we have to adjust
// change(w+), shift(w+), and change(w-).
function tree_executeShifts(v) {
var shift = 0,
change = 0,
children = v.children,
i = children.length,
w;
while (--i >= 0) {
w = children[i];
w.z += shift;
w.m += shift;
shift += w.s + (change += w.c);
}
}
// If vi-s ancestor is a sibling of v, returns vi-s ancestor. Otherwise,
// returns the specified (default) ancestor.
function tree_nextAncestor(vim, v, ancestor) {
return vim.a.parent === v.parent ? vim.a : ancestor;
}
function tree_TreeNode(node, i) {
this._ = node;
this.parent = null;
this.children = null;
this.A = null; // default ancestor
this.a = this; // ancestor
this.z = 0; // prelim
this.m = 0; // mod
this.c = 0; // change
this.s = 0; // shift
this.t = null; // thread
this.i = i; // number
}
tree_TreeNode.prototype = Object.create(hierarchy_Node.prototype);
function tree_treeRoot(root) {
var tree = new tree_TreeNode(root, 0),
node,
nodes = [tree],
child,
children,
i,
n;
while (node = nodes.pop()) {
if (children = node._.children) {
node.children = new Array(n = children.length);
for (i = n - 1; i >= 0; --i) {
nodes.push(child = node.children[i] = new tree_TreeNode(children[i], i));
child.parent = node;
}
}
}
(tree.parent = new tree_TreeNode(null, 0)).children = [tree];
return tree;
}
// Node-link tree diagram using the Reingold-Tilford "tidy" algorithm
/* harmony default export */ var src_tree = (function() {
var separation = tree_defaultSeparation,
dx = 1,
dy = 1,
nodeSize = null;
function tree(root) {
var t = tree_treeRoot(root);
// Compute the layout using Buchheim et al.s algorithm.
t.eachAfter(firstWalk), t.parent.m = -t.z;
t.eachBefore(secondWalk);
// If a fixed node size is specified, scale x and y.
if (nodeSize) root.eachBefore(sizeNode);
// If a fixed tree size is specified, scale x and y based on the extent.
// Compute the left-most, right-most, and depth-most nodes for extents.
else {
var left = root,
right = root,
bottom = root;
root.eachBefore(function(node) {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
if (node.depth > bottom.depth) bottom = node;
});
var s = left === right ? 1 : separation(left, right) / 2,
tx = s - left.x,
kx = dx / (right.x + s + tx),
ky = dy / (bottom.depth || 1);
root.eachBefore(function(node) {
node.x = (node.x + tx) * kx;
node.y = node.depth * ky;
});
}
return root;
}
// Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
// applied recursively to the children of v, as well as the function
// APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
// node v is placed to the midpoint of its outermost children.
function firstWalk(v) {
var children = v.children,
siblings = v.parent.children,
w = v.i ? siblings[v.i - 1] : null;
if (children) {
tree_executeShifts(v);
var midpoint = (children[0].z + children[children.length - 1].z) / 2;
if (w) {
v.z = w.z + separation(v._, w._);
v.m = v.z - midpoint;
} else {
v.z = midpoint;
}
} else if (w) {
v.z = w.z + separation(v._, w._);
}
v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
}
// Computes all real x-coordinates by summing up the modifiers recursively.
function secondWalk(v) {
v._.x = v.z + v.parent.m;
v.m += v.parent.m;
}
// The core of the algorithm. Here, a new subtree is combined with the
// previous subtrees. Threads are used to traverse the inside and outside
// contours of the left and right subtree up to the highest common level. The
// vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
// superscript o means outside and i means inside, the subscript - means left
// subtree and + means right subtree. For summing up the modifiers along the
// contour, we use respective variables si+, si-, so-, and so+. Whenever two
// nodes of the inside contours conflict, we compute the left one of the
// greatest uncommon ancestors using the function ANCESTOR and call MOVE
// SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
// Finally, we add a new thread (if necessary).
function apportion(v, w, ancestor) {
if (w) {
var vip = v,
vop = v,
vim = w,
vom = vip.parent.children[0],
sip = vip.m,
sop = vop.m,
sim = vim.m,
som = vom.m,
shift;
while (vim = tree_nextRight(vim), vip = tree_nextLeft(vip), vim && vip) {
vom = tree_nextLeft(vom);
vop = tree_nextRight(vop);
vop.a = v;
shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
if (shift > 0) {
tree_moveSubtree(tree_nextAncestor(vim, v, ancestor), v, shift);
sip += shift;
sop += shift;
}
sim += vim.m;
sip += vip.m;
som += vom.m;
sop += vop.m;
}
if (vim && !tree_nextRight(vop)) {
vop.t = vim;
vop.m += sim - sop;
}
if (vip && !tree_nextLeft(vom)) {
vom.t = vip;
vom.m += sip - som;
ancestor = v;
}
}
return ancestor;
}
function sizeNode(node) {
node.x *= dx;
node.y = node.depth * dy;
}
tree.separation = function(x) {
return arguments.length ? (separation = x, tree) : separation;
};
tree.size = function(x) {
return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);
};
tree.nodeSize = function(x) {
return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);
};
return tree;
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/cluster.js
function cluster_defaultSeparation(a, b) {
return a.parent === b.parent ? 1 : 2;
}
function meanX(children) {
return children.reduce(meanXReduce, 0) / children.length;
}
function meanXReduce(x, c) {
return x + c.x;
}
function maxY(children) {
return 1 + children.reduce(maxYReduce, 0);
}
function maxYReduce(y, c) {
return Math.max(y, c.y);
}
function leafLeft(node) {
var children;
while (children = node.children) node = children[0];
return node;
}
function leafRight(node) {
var children;
while (children = node.children) node = children[children.length - 1];
return node;
}
/* harmony default export */ var cluster = (function() {
var separation = cluster_defaultSeparation,
dx = 1,
dy = 1,
nodeSize = false;
function cluster(root) {
var previousNode,
x = 0;
// First walk, computing the initial x & y values.
root.eachAfter(function(node) {
var children = node.children;
if (children) {
node.x = meanX(children);
node.y = maxY(children);
} else {
node.x = previousNode ? x += separation(node, previousNode) : 0;
node.y = 0;
previousNode = node;
}
});
var left = leafLeft(root),
right = leafRight(root),
x0 = left.x - separation(left, right) / 2,
x1 = right.x + separation(right, left) / 2;
// Second walk, normalizing x & y to the desired size.
return root.eachAfter(nodeSize ? function(node) {
node.x = (node.x - root.x) * dx;
node.y = (root.y - node.y) * dy;
} : function(node) {
node.x = (node.x - x0) / (x1 - x0) * dx;
node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;
});
}
cluster.separation = function(x) {
return arguments.length ? (separation = x, cluster) : separation;
};
cluster.size = function(x) {
return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? null : [dx, dy]);
};
cluster.nodeSize = function(x) {
return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? [dx, dy] : null);
};
return cluster;
});
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/Tree.js
var Tree_Layouts = {
tidy: src_tree,
cluster: cluster
};
var Tree_Output = ['x', 'y', 'depth', 'children'];
/**
* Tree layout. Depending on the method parameter, performs either
* Reingold-Tilford 'tidy' layout or dendrogram 'cluster' layout.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function Tree_Tree(params) {
HierarchyLayout_HierarchyLayout.call(this, params);
}
Tree_Tree.Definition = {
"type": "Tree",
"metadata": {"tree": true, "modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "sort", "type": "compare" },
{ "name": "method", "type": "enum", "default": "tidy", "values": ["tidy", "cluster"] },
{ "name": "size", "type": "number", "array": true, "length": 2 },
{ "name": "nodeSize", "type": "number", "array": true, "length": 2 },
{ "name": "separation", "type": "boolean", "default": true },
{ "name": "as", "type": "string", "array": true, "length": Tree_Output.length, "default": Tree_Output }
]
};
var Tree_prototype = Object(vega_util["y" /* inherits */])(Tree_Tree, HierarchyLayout_HierarchyLayout);
/**
* Tree layout generator. Supports both 'tidy' and 'cluster' layouts.
*/
Tree_prototype.layout = function(method) {
var m = method || 'tidy';
if (Object(vega_util["v" /* hasOwnProperty */])(Tree_Layouts, m)) return Tree_Layouts[m]();
else Object(vega_util["n" /* error */])('Unrecognized Tree layout method: ' + m);
};
Tree_prototype.params = ['size', 'nodeSize'];
Tree_prototype.fields = Tree_Output;
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/TreeLinks.js
/**
* Generate tuples representing links between tree nodes.
* The resulting tuples will contain 'source' and 'target' fields,
* which point to parent and child node tuples, respectively.
* @constructor
* @param {object} params - The parameters for this operator.
*/
function TreeLinks_TreeLinks(params) {
Transform_Transform.call(this, [], params);
}
TreeLinks_TreeLinks.Definition = {
"type": "TreeLinks",
"metadata": {"tree": true, "generates": true, "changes": true},
"params": []
};
var TreeLinks_prototype = Object(vega_util["y" /* inherits */])(TreeLinks_TreeLinks, Transform_Transform);
TreeLinks_prototype.transform = function(_, pulse) {
var links = this.value,
tree = pulse.source && pulse.source.root,
out = pulse.fork(pulse.NO_SOURCE),
lut = {};
if (!tree) Object(vega_util["n" /* error */])('TreeLinks transform requires a tree data source.');
if (pulse.changed(pulse.ADD_REM)) {
// remove previous links
out.rem = links;
// build lookup table of valid tuples
pulse.visit(pulse.SOURCE, function(t) { lut[tupleid(t)] = 1; });
// generate links for all edges incident on valid tuples
tree.each(function(node) {
var t = node.data,
p = node.parent && node.parent.data;
if (p && lut[tupleid(t)] && lut[tupleid(p)]) {
out.add.push(Tuple_ingest({source: p, target: t}));
}
});
this.value = out.add;
}
else if (pulse.changed(pulse.MOD)) {
// build lookup table of modified tuples
pulse.visit(pulse.MOD, function(t) { lut[tupleid(t)] = 1; });
// gather links incident on modified tuples
links.forEach(function(link) {
if (lut[tupleid(link.source)] || lut[tupleid(link.target)]) {
out.mod.push(link);
}
});
}
return out;
};
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/binary.js
/* harmony default export */ var binary = (function(parent, x0, y0, x1, y1) {
var nodes = parent.children,
i, n = nodes.length,
sum, sums = new Array(n + 1);
for (sums[0] = sum = i = 0; i < n; ++i) {
sums[i + 1] = sum += nodes[i].value;
}
partition(0, n, parent.value, x0, y0, x1, y1);
function partition(i, j, value, x0, y0, x1, y1) {
if (i >= j - 1) {
var node = nodes[i];
node.x0 = x0, node.y0 = y0;
node.x1 = x1, node.y1 = y1;
return;
}
var valueOffset = sums[i],
valueTarget = (value / 2) + valueOffset,
k = i + 1,
hi = j - 1;
while (k < hi) {
var mid = k + hi >>> 1;
if (sums[mid] < valueTarget) k = mid + 1;
else hi = mid;
}
if ((valueTarget - sums[k - 1]) < (sums[k] - valueTarget) && i + 1 < k) --k;
var valueLeft = sums[k] - valueOffset,
valueRight = value - valueLeft;
if ((x1 - x0) > (y1 - y0)) {
var xk = (x0 * valueRight + x1 * valueLeft) / value;
partition(i, k, valueLeft, x0, y0, xk, y1);
partition(k, j, valueRight, xk, y0, x1, y1);
} else {
var yk = (y0 * valueRight + y1 * valueLeft) / value;
partition(i, k, valueLeft, x0, y0, x1, yk);
partition(k, j, valueRight, x0, yk, x1, y1);
}
}
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/slice.js
/* harmony default export */ var treemap_slice = (function(parent, x0, y0, x1, y1) {
var nodes = parent.children,
node,
i = -1,
n = nodes.length,
k = parent.value && (y1 - y0) / parent.value;
while (++i < n) {
node = nodes[i], node.x0 = x0, node.x1 = x1;
node.y0 = y0, node.y1 = y0 += node.value * k;
}
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/sliceDice.js
/* harmony default export */ var sliceDice = (function(parent, x0, y0, x1, y1) {
(parent.depth & 1 ? treemap_slice : dice)(parent, x0, y0, x1, y1);
});
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/squarify.js
var squarify_phi = (1 + Math.sqrt(5)) / 2;
function squarify_squarifyRatio(ratio, parent, x0, y0, x1, y1) {
var rows = [],
nodes = parent.children,
row,
nodeValue,
i0 = 0,
i1 = 0,
n = nodes.length,
dx, dy,
value = parent.value,
sumValue,
minValue,
maxValue,
newRatio,
minRatio,
alpha,
beta;
while (i0 < n) {
dx = x1 - x0, dy = y1 - y0;
// Find the next non-empty node.
do sumValue = nodes[i1++].value; while (!sumValue && i1 < n);
minValue = maxValue = sumValue;
alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
beta = sumValue * sumValue * alpha;
minRatio = Math.max(maxValue / beta, beta / minValue);
// Keep adding nodes while the aspect ratio maintains or improves.
for (; i1 < n; ++i1) {
sumValue += nodeValue = nodes[i1].value;
if (nodeValue < minValue) minValue = nodeValue;
if (nodeValue > maxValue) maxValue = nodeValue;
beta = sumValue * sumValue * alpha;
newRatio = Math.max(maxValue / beta, beta / minValue);
if (newRatio > minRatio) { sumValue -= nodeValue; break; }
minRatio = newRatio;
}
// Position and record the row orientation.
rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});
if (row.dice) dice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
else treemap_slice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
value -= sumValue, i0 = i1;
}
return rows;
}
/* harmony default export */ var squarify = ((function custom(ratio) {
function squarify(parent, x0, y0, x1, y1) {
squarify_squarifyRatio(ratio, parent, x0, y0, x1, y1);
}
squarify.ratio = function(x) {
return custom((x = +x) > 1 ? x : 1);
};
return squarify;
})(squarify_phi));
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/resquarify.js
/* harmony default export */ var treemap_resquarify = ((function custom(ratio) {
function resquarify(parent, x0, y0, x1, y1) {
if ((rows = parent._squarify) && (rows.ratio === ratio)) {
var rows,
row,
nodes,
i,
j = -1,
n,
m = rows.length,
value = parent.value;
while (++j < m) {
row = rows[j], nodes = row.children;
for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value;
if (row.dice) dice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value);
else treemap_slice(row, x0, y0, x0 += (x1 - x0) * row.value / value, y1);
value -= row.value;
}
} else {
parent._squarify = rows = squarify_squarifyRatio(ratio, parent, x0, y0, x1, y1);
rows.ratio = ratio;
}
}
resquarify.ratio = function(x) {
return custom((x = +x) > 1 ? x : 1);
};
return resquarify;
})(squarify_phi));
// CONCATENATED MODULE: ./node_modules/d3-hierarchy/src/treemap/index.js
/* harmony default export */ var src_treemap = (function() {
var tile = squarify,
round = false,
dx = 1,
dy = 1,
paddingStack = [0],
paddingInner = constantZero,
paddingTop = constantZero,
paddingRight = constantZero,
paddingBottom = constantZero,
paddingLeft = constantZero;
function treemap(root) {
root.x0 =
root.y0 = 0;
root.x1 = dx;
root.y1 = dy;
root.eachBefore(positionNode);
paddingStack = [0];
if (round) root.eachBefore(treemap_round);
return root;
}
function positionNode(node) {
var p = paddingStack[node.depth],
x0 = node.x0 + p,
y0 = node.y0 + p,
x1 = node.x1 - p,
y1 = node.y1 - p;
if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
node.x0 = x0;
node.y0 = y0;
node.x1 = x1;
node.y1 = y1;
if (node.children) {
p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
x0 += paddingLeft(node) - p;
y0 += paddingTop(node) - p;
x1 -= paddingRight(node) - p;
y1 -= paddingBottom(node) - p;
if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
tile(node, x0, y0, x1, y1);
}
}
treemap.round = function(x) {
return arguments.length ? (round = !!x, treemap) : round;
};
treemap.size = function(x) {
return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
};
treemap.tile = function(x) {
return arguments.length ? (tile = required(x), treemap) : tile;
};
treemap.padding = function(x) {
return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
};
treemap.paddingInner = function(x) {
return arguments.length ? (paddingInner = typeof x === "function" ? x : d3_hierarchy_src_constant(+x), treemap) : paddingInner;
};
treemap.paddingOuter = function(x) {
return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
};
treemap.paddingTop = function(x) {
return arguments.length ? (paddingTop = typeof x === "function" ? x : d3_hierarchy_src_constant(+x), treemap) : paddingTop;
};
treemap.paddingRight = function(x) {
return arguments.length ? (paddingRight = typeof x === "function" ? x : d3_hierarchy_src_constant(+x), treemap) : paddingRight;
};
treemap.paddingBottom = function(x) {
return arguments.length ? (paddingBottom = typeof x === "function" ? x : d3_hierarchy_src_constant(+x), treemap) : paddingBottom;
};
treemap.paddingLeft = function(x) {
return arguments.length ? (paddingLeft = typeof x === "function" ? x : d3_hierarchy_src_constant(+x), treemap) : paddingLeft;
};
return treemap;
});
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/src/Treemap.js
var Treemap_Tiles = {
binary: binary,
dice: dice,
slice: treemap_slice,
slicedice: sliceDice,
squarify: squarify,
resquarify: treemap_resquarify
};
var Treemap_Output = ['x0', 'y0', 'x1', 'y1', 'depth', 'children'];
/**
* Treemap layout.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.field - The value field to size nodes.
*/
function Treemap_Treemap(params) {
HierarchyLayout_HierarchyLayout.call(this, params);
}
Treemap_Treemap.Definition = {
"type": "Treemap",
"metadata": {"tree": true, "modifies": true},
"params": [
{ "name": "field", "type": "field" },
{ "name": "sort", "type": "compare" },
{ "name": "method", "type": "enum", "default": "squarify",
"values": ["squarify", "resquarify", "binary", "dice", "slice", "slicedice"] },
{ "name": "padding", "type": "number", "default": 0 },
{ "name": "paddingInner", "type": "number", "default": 0 },
{ "name": "paddingOuter", "type": "number", "default": 0 },
{ "name": "paddingTop", "type": "number", "default": 0 },
{ "name": "paddingRight", "type": "number", "default": 0 },
{ "name": "paddingBottom", "type": "number", "default": 0 },
{ "name": "paddingLeft", "type": "number", "default": 0 },
{ "name": "ratio", "type": "number", "default": 1.618033988749895 },
{ "name": "round", "type": "boolean", "default": false },
{ "name": "size", "type": "number", "array": true, "length": 2 },
{ "name": "as", "type": "string", "array": true, "length": Treemap_Output.length, "default": Treemap_Output }
]
};
var Treemap_prototype = Object(vega_util["y" /* inherits */])(Treemap_Treemap, HierarchyLayout_HierarchyLayout);
/**
* Treemap layout generator. Adds 'method' and 'ratio' parameters
* to configure the underlying tile method.
*/
Treemap_prototype.layout = function() {
var x = src_treemap();
x.ratio = function(_) {
var t = x.tile();
if (t.ratio) x.tile(t.ratio(_));
};
x.method = function(_) {
if (Object(vega_util["v" /* hasOwnProperty */])(Treemap_Tiles, _)) x.tile(Treemap_Tiles[_]);
else Object(vega_util["n" /* error */])('Unrecognized Treemap layout method: ' + _);
};
return x;
};
Treemap_prototype.params = [
'method', 'ratio', 'size', 'round',
'padding', 'paddingInner', 'paddingOuter',
'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'
];
Treemap_prototype.fields = Treemap_Output;
// CONCATENATED MODULE: ./node_modules/vega-hierarchy/index.js
// CONCATENATED MODULE: ./node_modules/vega-regression/src/partition.js
/* harmony default export */ var vega_regression_src_partition = (function(data, groupby) {
var groups = [],
get = function(f) { return f(t); },
map, i, n, t, k, g;
// partition data points into stack groups
if (groupby == null) {
groups.push(data);
} else {
for (map={}, i=0, n=data.length; i<n; ++i) {
t = data[i];
k = groupby.map(get);
g = map[k];
if (!g) {
map[k] = (g = []);
g.dims = k;
groups.push(g);
}
g.push(t);
}
}
return groups;
});
// CONCATENATED MODULE: ./node_modules/vega-regression/src/Loess.js
/**
* Compute locally-weighted regression fits for one or more data groups.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.x - An accessor for the predictor data field.
* @param {function(object): *} params.y - An accessor for the predicted data field.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
* @param {number} [params.bandwidth=0.3] - The loess bandwidth.
*/
function Loess_Loess(params) {
Transform_Transform.call(this, null, params);
}
Loess_Loess.Definition = {
"type": "Loess",
"metadata": {"generates": true},
"params": [
{ "name": "x", "type": "field", "required": true },
{ "name": "y", "type": "field", "required": true },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "bandwidth", "type": "number", "default": 0.3 },
{ "name": "as", "type": "string", "array": true }
]
};
var Loess_prototype = Object(vega_util["y" /* inherits */])(Loess_Loess, Transform_Transform);
Loess_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
if (!this.value || pulse.changed() || _.modified()) {
const source = pulse.materialize(pulse.SOURCE).source,
groups = vega_regression_src_partition(source, _.groupby),
names = (_.groupby || []).map(vega_util["h" /* accessorName */]),
m = names.length,
as = _.as || [Object(vega_util["h" /* accessorName */])(_.x), Object(vega_util["h" /* accessorName */])(_.y)],
values = [];
groups.forEach(g => {
regression_loess(g, _.x, _.y, _.bandwidth || 0.3).forEach(p => {
const t = {};
for (let i=0; i<m; ++i) {
t[names[i]] = g.dims[i];
}
t[as[0]] = p[0];
t[as[1]] = p[1];
values.push(Tuple_ingest(t));
});
});
if (this.value) out.rem = this.value;
this.value = out.add = out.source = values;
}
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-regression/src/Regression.js
const Regression_Methods = {
linear: regression_linear,
log: regression_log,
exp: regression_exp,
pow: regression_pow,
quad: regression_quad,
poly: poly
};
function Regression_degreesOfFreedom(method, order) {
return method === 'poly' ? order : method === 'quad' ? 2 : 1;
}
/**
* Compute regression fits for one or more data groups.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {function(object): *} params.x - An accessor for the predictor data field.
* @param {function(object): *} params.y - An accessor for the predicted data field.
* @param {string} [params.method='linear'] - The regression method to apply.
* @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby.
* @param {Array<number>} [params.extent] - The domain extent over which to plot the regression line.
* @param {number} [params.order=3] - The polynomial order. Only applies to the 'poly' method.
*/
function Regression_Regression(params) {
Transform_Transform.call(this, null, params);
}
Regression_Regression.Definition = {
"type": "Regression",
"metadata": {"generates": true},
"params": [
{ "name": "x", "type": "field", "required": true },
{ "name": "y", "type": "field", "required": true },
{ "name": "groupby", "type": "field", "array": true },
{ "name": "method", "type": "string", "default": "linear", "values": Object.keys(Regression_Methods) },
{ "name": "order", "type": "number", "default": 3 },
{ "name": "extent", "type": "number", "array": true, "length": 2 },
{ "name": "params", "type": "boolean", "default": false },
{ "name": "as", "type": "string", "array": true }
]
};
var Regression_prototype = Object(vega_util["y" /* inherits */])(Regression_Regression, Transform_Transform);
Regression_prototype.transform = function(_, pulse) {
var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS);
if (!this.value || pulse.changed() || _.modified()) {
const source = pulse.materialize(pulse.SOURCE).source,
groups = vega_regression_src_partition(source, _.groupby),
names = (_.groupby || []).map(vega_util["h" /* accessorName */]),
method = _.method || 'linear',
order = _.order || 3,
dof = Regression_degreesOfFreedom(method, order),
as = _.as || [Object(vega_util["h" /* accessorName */])(_.x), Object(vega_util["h" /* accessorName */])(_.y)],
fit = Regression_Methods[method],
values = [];
let domain = _.extent;
if (!Object(vega_util["v" /* hasOwnProperty */])(Regression_Methods, method)) {
Object(vega_util["n" /* error */])('Invalid regression method: ' + method);
}
if (domain != null) {
if (method === 'log' && domain[0] <= 0) {
pulse.dataflow.warn('Ignoring extent with values <= 0 for log regression.');
domain = null;
}
}
groups.forEach(g => {
const n = g.length;
if (n <= dof) {
pulse.dataflow.warn('Skipping regression with more parameters than data points.');
return;
}
const model = fit(g, _.x, _.y, order);
if (_.params) {
// if parameter vectors requested return those
values.push(Tuple_ingest({
keys: g.dims,
coef: model.coef,
rSquared: model.rSquared
}));
return;
}
const dom = domain || Object(vega_util["p" /* extent */])(g, _.x),
add = p => {
const t = {};
for (let i=0; i<names.length; ++i) {
t[names[i]] = g.dims[i];
}
t[as[0]] = p[0];
t[as[1]] = p[1];
values.push(Tuple_ingest(t));
};
if (method === 'linear') {
// for linear regression we only need the end points
dom.forEach(x => add([x, model.predict(x)]));
} else {
// otherwise return trend line sample points
sampleCurve(model.predict, dom, 25, 200).forEach(add);
}
});
if (this.value) out.rem = this.value;
this.value = out.add = out.source = values;
}
return out;
};
// CONCATENATED MODULE: ./node_modules/vega-regression/index.js
// CONCATENATED MODULE: ./node_modules/delaunator/index.js
const delaunator_EPSILON = Math.pow(2, -52);
const EDGE_STACK = new Uint32Array(512);
class Delaunator {
static from(points, getX = defaultGetX, getY = defaultGetY) {
const n = points.length;
const coords = new Float64Array(n * 2);
for (let i = 0; i < n; i++) {
const p = points[i];
coords[2 * i] = getX(p);
coords[2 * i + 1] = getY(p);
}
return new Delaunator(coords);
}
constructor(coords) {
const n = coords.length >> 1;
if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');
this.coords = coords;
// arrays that will store the triangulation graph
const maxTriangles = Math.max(2 * n - 5, 0);
this._triangles = new Uint32Array(maxTriangles * 3);
this._halfedges = new Int32Array(maxTriangles * 3);
// temporary arrays for tracking the edges of the advancing convex hull
this._hashSize = Math.ceil(Math.sqrt(n));
this._hullPrev = new Uint32Array(n); // edge to prev edge
this._hullNext = new Uint32Array(n); // edge to next edge
this._hullTri = new Uint32Array(n); // edge to adjacent triangle
this._hullHash = new Int32Array(this._hashSize).fill(-1); // angular edge hash
// temporary arrays for sorting points
this._ids = new Uint32Array(n);
this._dists = new Float64Array(n);
this.update();
}
update() {
const {coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash} = this;
const n = coords.length >> 1;
// populate an array of point indices; calculate input data bbox
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (let i = 0; i < n; i++) {
const x = coords[2 * i];
const y = coords[2 * i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
this._ids[i] = i;
}
const cx = (minX + maxX) / 2;
const cy = (minY + maxY) / 2;
let minDist = Infinity;
let i0, i1, i2;
// pick a seed point close to the center
for (let i = 0; i < n; i++) {
const d = delaunator_dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
if (d < minDist) {
i0 = i;
minDist = d;
}
}
const i0x = coords[2 * i0];
const i0y = coords[2 * i0 + 1];
minDist = Infinity;
// find the point closest to the seed
for (let i = 0; i < n; i++) {
if (i === i0) continue;
const d = delaunator_dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
if (d < minDist && d > 0) {
i1 = i;
minDist = d;
}
}
let i1x = coords[2 * i1];
let i1y = coords[2 * i1 + 1];
let minRadius = Infinity;
// find the third point which forms the smallest circumcircle with the first two
for (let i = 0; i < n; i++) {
if (i === i0 || i === i1) continue;
const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
if (r < minRadius) {
i2 = i;
minRadius = r;
}
}
let i2x = coords[2 * i2];
let i2y = coords[2 * i2 + 1];
if (minRadius === Infinity) {
// order collinear points by dx (or dy if all x are identical)
// and return the list as a hull
for (let i = 0; i < n; i++) {
this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);
}
quicksort(this._ids, this._dists, 0, n - 1);
const hull = new Uint32Array(n);
let j = 0;
for (let i = 0, d0 = -Infinity; i < n; i++) {
const id = this._ids[i];
if (this._dists[id] > d0) {
hull[j++] = id;
d0 = this._dists[id];
}
}
this.hull = hull.subarray(0, j);
this.triangles = new Uint32Array(0);
this.halfedges = new Uint32Array(0);
return;
}
// swap the order of the seed points for counter-clockwise orientation
if (delaunator_orient(i0x, i0y, i1x, i1y, i2x, i2y)) {
const i = i1;
const x = i1x;
const y = i1y;
i1 = i2;
i1x = i2x;
i1y = i2y;
i2 = i;
i2x = x;
i2y = y;
}
const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
this._cx = center.x;
this._cy = center.y;
for (let i = 0; i < n; i++) {
this._dists[i] = delaunator_dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);
}
// sort the points by distance from the seed triangle circumcenter
quicksort(this._ids, this._dists, 0, n - 1);
// set up the seed triangle as the starting hull
this._hullStart = i0;
let hullSize = 3;
hullNext[i0] = hullPrev[i2] = i1;
hullNext[i1] = hullPrev[i0] = i2;
hullNext[i2] = hullPrev[i1] = i0;
hullTri[i0] = 0;
hullTri[i1] = 1;
hullTri[i2] = 2;
hullHash.fill(-1);
hullHash[this._hashKey(i0x, i0y)] = i0;
hullHash[this._hashKey(i1x, i1y)] = i1;
hullHash[this._hashKey(i2x, i2y)] = i2;
this.trianglesLen = 0;
this._addTriangle(i0, i1, i2, -1, -1, -1);
for (let k = 0, xp, yp; k < this._ids.length; k++) {
const i = this._ids[k];
const x = coords[2 * i];
const y = coords[2 * i + 1];
// skip near-duplicate points
if (k > 0 && Math.abs(x - xp) <= delaunator_EPSILON && Math.abs(y - yp) <= delaunator_EPSILON) continue;
xp = x;
yp = y;
// skip seed triangle points
if (i === i0 || i === i1 || i === i2) continue;
// find a visible edge on the convex hull using edge hash
let start = 0;
for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {
start = hullHash[(key + j) % this._hashSize];
if (start !== -1 && start !== hullNext[start]) break;
}
start = hullPrev[start];
let e = start, q;
while (q = hullNext[e], !delaunator_orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1])) {
e = q;
if (e === start) {
e = -1;
break;
}
}
if (e === -1) continue; // likely a near-duplicate point; skip it
// add the first triangle from the point
let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);
// recursively flip triangles from the point until they satisfy the Delaunay condition
hullTri[i] = this._legalize(t + 2);
hullTri[e] = t; // keep track of boundary triangles on the hull
hullSize++;
// walk forward through the hull, adding more triangles and flipping recursively
let n = hullNext[e];
while (q = hullNext[n], delaunator_orient(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1])) {
t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);
hullTri[i] = this._legalize(t + 2);
hullNext[n] = n; // mark as removed
hullSize--;
n = q;
}
// walk backward from the other side, adding more triangles and flipping
if (e === start) {
while (q = hullPrev[e], delaunator_orient(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1])) {
t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
this._legalize(t + 2);
hullTri[q] = t;
hullNext[e] = e; // mark as removed
hullSize--;
e = q;
}
}
// update the hull indices
this._hullStart = hullPrev[i] = e;
hullNext[e] = hullPrev[n] = i;
hullNext[i] = n;
// save the two new edges in the hash table
hullHash[this._hashKey(x, y)] = i;
hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
}
this.hull = new Uint32Array(hullSize);
for (let i = 0, e = this._hullStart; i < hullSize; i++) {
this.hull[i] = e;
e = hullNext[e];
}
// trim typed triangle mesh arrays
this.triangles = this._triangles.subarray(0, this.trianglesLen);
this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
}
_hashKey(x, y) {
return Math.floor(pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;
}
_legalize(a) {
const {_triangles: triangles, _halfedges: halfedges, coords} = this;
let i = 0;
let ar = 0;
// recursion eliminated with a fixed-size stack
while (true) {
const b = halfedges[a];
/* if the pair of triangles doesn't satisfy the Delaunay condition
* (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
* then do the same check/flip recursively for the new pair of triangles
*
* pl pl
* /||\ / \
* al/ || \bl al/ \a
* / || \ / \
* / a||b \ flip /___ar___\
* p0\ || /p1 => p0\---bl---/p1
* \ || / \ /
* ar\ || /br b\ /br
* \||/ \ /
* pr pr
*/
const a0 = a - a % 3;
ar = a0 + (a + 2) % 3;
if (b === -1) { // convex hull edge
if (i === 0) break;
a = EDGE_STACK[--i];
continue;
}
const b0 = b - b % 3;
const al = a0 + (a + 1) % 3;
const bl = b0 + (b + 2) % 3;
const p0 = triangles[ar];
const pr = triangles[a];
const pl = triangles[al];
const p1 = triangles[bl];
const illegal = inCircle(
coords[2 * p0], coords[2 * p0 + 1],
coords[2 * pr], coords[2 * pr + 1],
coords[2 * pl], coords[2 * pl + 1],
coords[2 * p1], coords[2 * p1 + 1]);
if (illegal) {
triangles[a] = p1;
triangles[b] = p0;
const hbl = halfedges[bl];
// edge swapped on the other side of the hull (rare); fix the halfedge reference
if (hbl === -1) {
let e = this._hullStart;
do {
if (this._hullTri[e] === bl) {
this._hullTri[e] = a;
break;
}
e = this._hullPrev[e];
} while (e !== this._hullStart);
}
this._link(a, hbl);
this._link(b, halfedges[ar]);
this._link(ar, bl);
const br = b0 + (b + 1) % 3;
// don't worry about hitting the cap: it can only happen on extremely degenerate input
if (i < EDGE_STACK.length) {
EDGE_STACK[i++] = br;
}
} else {
if (i === 0) break;
a = EDGE_STACK[--i];
}
}
return ar;
}
_link(a, b) {
this._halfedges[a] = b;
if (b !== -1) this._halfedges[b] = a;
}
// add a new triangle given vertex indices and adjacent half-edge ids
_addTriangle(i0, i1, i2, a, b, c) {
const t = this.trianglesLen;
this._triangles[t] = i0;
this._triangles[t + 1] = i1;
this._triangles[t + 2] = i2;
this._link(t, a);
this._link(t + 1, b);
this._link(t + 2, c);
this.trianglesLen += 3;
return t;
}
}
// monotonically increases with real angle, but doesn't need expensive trigonometry
function pseudoAngle(dx, dy) {
const p = dx / (Math.abs(dx) + Math.abs(dy));
return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]
}
function delaunator_dist(ax, ay, bx, by) {
const dx = ax - bx;
const dy = ay - by;
return dx * dx + dy * dy;
}
// return 2d orientation sign if we're confident in it through J. Shewchuk's error bound check
function orientIfSure(px, py, rx, ry, qx, qy) {
const l = (ry - py) * (qx - px);
const r = (rx - px) * (qy - py);
return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0;
}
// a more robust orientation test that's stable in a given triangle (to fix robustness issues)
function delaunator_orient(rx, ry, qx, qy, px, py) {
const sign = orientIfSure(px, py, rx, ry, qx, qy) ||
orientIfSure(rx, ry, qx, qy, px, py) ||
orientIfSure(qx, qy, px, py, rx, ry);
return sign < 0;
}
function inCircle(ax, ay, bx, by, cx, cy, px, py) {
const dx = ax - px;
const dy = ay - py;
const ex = bx - px;
const ey = by - py;
const fx = cx - px;
const fy = cy - py;
const ap = dx * dx + dy * dy;
const bp = ex * ex + ey * ey;
const cp = fx * fx + fy * fy;
return dx * (ey * cp - bp * fy) -
dy * (ex * cp - bp * fx) +
ap * (ex * fy - ey * fx) < 0;
}
function circumradius(ax, ay, bx, by, cx, cy) {
const dx = bx - ax;
const dy = by - ay;
const ex = cx - ax;
const ey = cy - ay;
const bl = dx * dx + dy * dy;
const cl = ex * ex + ey * ey;
const d = 0.5 / (dx * ey - dy * ex);
const x = (ey * bl - dy * cl) * d;
const y = (dx * cl - ex * bl) * d;
return x * x + y * y;
}
function circumcenter(ax, ay, bx, by, cx, cy) {
const dx = bx - ax;
const dy = by - ay;
const ex = cx - ax;
const ey = cy - ay;
const bl = dx * dx + dy * dy;
const cl = ex * ex + ey * ey;
const d = 0.5 / (dx * ey - dy * ex);
const x = ax + (ey * bl - dy * cl) * d;
const y = ay + (dx * cl - ex * bl) * d;
return {x, y};
}
function quicksort(ids, dists, left, right) {
if (right - left <= 20) {
for (let i = left + 1; i <= right; i++) {
const temp = ids[i];
const tempDist = dists[temp];
let j = i - 1;
while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];
ids[j + 1] = temp;
}
} else {
const median = (left + right) >> 1;
let i = left + 1;
let j = right;
delaunator_swap(ids, median, i);
if (dists[ids[left]] > dists[ids[right]]) delaunator_swap(ids, left, right);
if (dists[ids[i]] > dists[ids[right]]) delaunator_swap(ids, i, right);
if (dists[ids[left]] > dists[ids[i]]) delaunator_swap(ids, left, i);
const temp = ids[i];
const tempDist = dists[temp];
while (true) {
do i++; while (dists[ids[i]] < tempDist);
do j--; while (dists[ids[j]] > tempDist);
if (j < i) break;
delaunator_swap(ids, i, j);
}
ids[left + 1] = ids[j];
ids[j] = temp;
if (right - i + 1 >= j - left) {
quicksort(ids, dists, i, right);
quicksort(ids, dists, left, j - 1);
} else {
quicksort(ids, dists, left, j - 1);
quicksort(ids, dists, i, right);
}
}
}
function delaunator_swap(arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function defaultGetX(p) {
return p[0];
}
function defaultGetY(p) {
return p[1];
}
// CONCATENATED MODULE: ./node_modules/d3-delaunay/src/path.js
const src_path_epsilon = 1e-6;
class path_Path {
constructor() {
this._x0 = this._y0 = // start of current subpath
this._x1 = this._y1 = null; // end of current subpath
this._ = "";
}
moveTo(x, y) {
this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;
}
closePath() {
if (this._x1 !== null) {
this._x1 = this._x0, this._y1 = this._y0;
this._ += "Z";
}
}
lineTo(x, y) {
this._ += `L${this._x1 = +x},${this._y1 = +y}`;
}
arc(x, y, r) {
x = +x, y = +y, r = +r;
const x0 = x + r;
const y0 = y;
if (r < 0) throw new Error("negative radius");
if (this._x1 === null) this._ += `M${x0},${y0}`;
else if (Math.abs(this._x1 - x0) > src_path_epsilon || Math.abs(this._y1 - y0) > src_path_epsilon) this._ += "L" + x0 + "," + y0;
if (!r) return;
this._ += `A${r},${r},0,1,1,${x - r},${y}A${r},${r},0,1,1,${this._x1 = x0},${this._y1 = y0}`;
}
rect(x, y, w, h) {
this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${+w}v${+h}h${-w}Z`;
}
value() {
return this._ || null;
}
}
// CONCATENATED MODULE: ./node_modules/d3-delaunay/src/polygon.js
class Polygon {
constructor() {
this._ = [];
}
moveTo(x, y) {
this._.push([x, y]);
}
closePath() {
this._.push(this._[0].slice());
}
lineTo(x, y) {
this._.push([x, y]);
}
value() {
return this._.length ? this._ : null;
}
}
// CONCATENATED MODULE: ./node_modules/d3-delaunay/src/voronoi.js
class voronoi_Voronoi {
constructor(delaunay, [xmin, ymin, xmax, ymax] = [0, 0, 960, 500]) {
if (!((xmax = +xmax) >= (xmin = +xmin)) || !((ymax = +ymax) >= (ymin = +ymin))) throw new Error("invalid bounds");
this.delaunay = delaunay;
this._circumcenters = new Float64Array(delaunay.points.length * 2);
this.vectors = new Float64Array(delaunay.points.length * 2);
this.xmax = xmax, this.xmin = xmin;
this.ymax = ymax, this.ymin = ymin;
this._init();
}
update() {
this.delaunay.update();
this._init();
return this;
}
_init() {
const {delaunay: {points, hull, triangles}, vectors} = this;
// Compute circumcenters.
const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);
for (let i = 0, j = 0, n = triangles.length, x, y; i < n; i += 3, j += 2) {
const t1 = triangles[i] * 2;
const t2 = triangles[i + 1] * 2;
const t3 = triangles[i + 2] * 2;
const x1 = points[t1];
const y1 = points[t1 + 1];
const x2 = points[t2];
const y2 = points[t2 + 1];
const x3 = points[t3];
const y3 = points[t3 + 1];
const dx = x2 - x1;
const dy = y2 - y1;
const ex = x3 - x1;
const ey = y3 - y1;
const bl = dx * dx + dy * dy;
const cl = ex * ex + ey * ey;
const ab = (dx * ey - dy * ex) * 2;
if (!ab) {
// degenerate case (collinear diagram)
x = (x1 + x3) / 2 - 1e8 * ey;
y = (y1 + y3) / 2 + 1e8 * ex;
}
else if (Math.abs(ab) < 1e-8) {
// almost equal points (degenerate triangle)
x = (x1 + x3) / 2;
y = (y1 + y3) / 2;
} else {
const d = 1 / ab;
x = x1 + (ey * bl - dy * cl) * d;
y = y1 + (dx * cl - ex * bl) * d;
}
circumcenters[j] = x;
circumcenters[j + 1] = y;
}
// Compute exterior cell rays.
let h = hull[hull.length - 1];
let p0, p1 = h * 4;
let x0, x1 = points[2 * h];
let y0, y1 = points[2 * h + 1];
vectors.fill(0);
for (let i = 0; i < hull.length; ++i) {
h = hull[i];
p0 = p1, x0 = x1, y0 = y1;
p1 = h * 4, x1 = points[2 * h], y1 = points[2 * h + 1];
vectors[p0 + 2] = vectors[p1] = y0 - y1;
vectors[p0 + 3] = vectors[p1 + 1] = x1 - x0;
}
}
render(context) {
const buffer = context == null ? context = new path_Path : undefined;
const {delaunay: {halfedges, inedges, hull}, circumcenters, vectors} = this;
if (hull.length <= 1) return null;
for (let i = 0, n = halfedges.length; i < n; ++i) {
const j = halfedges[i];
if (j < i) continue;
const ti = Math.floor(i / 3) * 2;
const tj = Math.floor(j / 3) * 2;
const xi = circumcenters[ti];
const yi = circumcenters[ti + 1];
const xj = circumcenters[tj];
const yj = circumcenters[tj + 1];
this._renderSegment(xi, yi, xj, yj, context);
}
let h0, h1 = hull[hull.length - 1];
for (let i = 0; i < hull.length; ++i) {
h0 = h1, h1 = hull[i];
const t = Math.floor(inedges[h1] / 3) * 2;
const x = circumcenters[t];
const y = circumcenters[t + 1];
const v = h0 * 4;
const p = this._project(x, y, vectors[v + 2], vectors[v + 3]);
if (p) this._renderSegment(x, y, p[0], p[1], context);
}
return buffer && buffer.value();
}
renderBounds(context) {
const buffer = context == null ? context = new path_Path : undefined;
context.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin);
return buffer && buffer.value();
}
renderCell(i, context) {
const buffer = context == null ? context = new path_Path : undefined;
const points = this._clip(i);
if (points === null) return;
context.moveTo(points[0], points[1]);
let n = points.length;
while (points[0] === points[n-2] && points[1] === points[n-1] && n > 1) n -= 2;
for (let i = 2; i < n; i += 2) {
if (points[i] !== points[i-2] || points[i+1] !== points[i-1])
context.lineTo(points[i], points[i + 1]);
}
context.closePath();
return buffer && buffer.value();
}
*cellPolygons() {
const {delaunay: {points}} = this;
for (let i = 0, n = points.length / 2; i < n; ++i) {
const cell = this.cellPolygon(i);
if (cell) yield cell;
}
}
cellPolygon(i) {
const polygon = new Polygon;
this.renderCell(i, polygon);
return polygon.value();
}
_renderSegment(x0, y0, x1, y1, context) {
let S;
const c0 = this._regioncode(x0, y0);
const c1 = this._regioncode(x1, y1);
if (c0 === 0 && c1 === 0) {
context.moveTo(x0, y0);
context.lineTo(x1, y1);
} else if (S = this._clipSegment(x0, y0, x1, y1, c0, c1)) {
context.moveTo(S[0], S[1]);
context.lineTo(S[2], S[3]);
}
}
contains(i, x, y) {
if ((x = +x, x !== x) || (y = +y, y !== y)) return false;
return this.delaunay._step(i, x, y) === i;
}
*neighbors(i) {
const ci = this._clip(i);
if (ci) for (const j of this.delaunay.neighbors(i)) {
const cj = this._clip(j);
// find the common edge
if (cj) loop: for (let ai = 0, li = ci.length; ai < li; ai += 2) {
for (let aj = 0, lj = cj.length; aj < lj; aj += 2) {
if (ci[ai] == cj[aj]
&& ci[ai + 1] == cj[aj + 1]
&& ci[(ai + 2) % li] == cj[(aj + lj - 2) % lj]
&& ci[(ai + 3) % li] == cj[(aj + lj - 1) % lj]
) {
yield j;
break loop;
}
}
}
}
}
_cell(i) {
const {circumcenters, delaunay: {inedges, halfedges, triangles}} = this;
const e0 = inedges[i];
if (e0 === -1) return null; // coincident point
const points = [];
let e = e0;
do {
const t = Math.floor(e / 3);
points.push(circumcenters[t * 2], circumcenters[t * 2 + 1]);
e = e % 3 === 2 ? e - 2 : e + 1;
if (triangles[e] !== i) break; // bad triangulation
e = halfedges[e];
} while (e !== e0 && e !== -1);
return points;
}
_clip(i) {
// degenerate case (1 valid point: return the box)
if (i === 0 && this.delaunay.hull.length === 1) {
return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
}
const points = this._cell(i);
if (points === null) return null;
const {vectors: V} = this;
const v = i * 4;
return V[v] || V[v + 1]
? this._clipInfinite(i, points, V[v], V[v + 1], V[v + 2], V[v + 3])
: this._clipFinite(i, points);
}
_clipFinite(i, points) {
const n = points.length;
let P = null;
let x0, y0, x1 = points[n - 2], y1 = points[n - 1];
let c0, c1 = this._regioncode(x1, y1);
let e0, e1;
for (let j = 0; j < n; j += 2) {
x0 = x1, y0 = y1, x1 = points[j], y1 = points[j + 1];
c0 = c1, c1 = this._regioncode(x1, y1);
if (c0 === 0 && c1 === 0) {
e0 = e1, e1 = 0;
if (P) P.push(x1, y1);
else P = [x1, y1];
} else {
let S, sx0, sy0, sx1, sy1;
if (c0 === 0) {
if ((S = this._clipSegment(x0, y0, x1, y1, c0, c1)) === null) continue;
[sx0, sy0, sx1, sy1] = S;
} else {
if ((S = this._clipSegment(x1, y1, x0, y0, c1, c0)) === null) continue;
[sx1, sy1, sx0, sy0] = S;
e0 = e1, e1 = this._edgecode(sx0, sy0);
if (e0 && e1) this._edge(i, e0, e1, P, P.length);
if (P) P.push(sx0, sy0);
else P = [sx0, sy0];
}
e0 = e1, e1 = this._edgecode(sx1, sy1);
if (e0 && e1) this._edge(i, e0, e1, P, P.length);
if (P) P.push(sx1, sy1);
else P = [sx1, sy1];
}
}
if (P) {
e0 = e1, e1 = this._edgecode(P[0], P[1]);
if (e0 && e1) this._edge(i, e0, e1, P, P.length);
} else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
}
return P;
}
_clipSegment(x0, y0, x1, y1, c0, c1) {
while (true) {
if (c0 === 0 && c1 === 0) return [x0, y0, x1, y1];
if (c0 & c1) return null;
let x, y, c = c0 || c1;
if (c & 0b1000) x = x0 + (x1 - x0) * (this.ymax - y0) / (y1 - y0), y = this.ymax;
else if (c & 0b0100) x = x0 + (x1 - x0) * (this.ymin - y0) / (y1 - y0), y = this.ymin;
else if (c & 0b0010) y = y0 + (y1 - y0) * (this.xmax - x0) / (x1 - x0), x = this.xmax;
else y = y0 + (y1 - y0) * (this.xmin - x0) / (x1 - x0), x = this.xmin;
if (c0) x0 = x, y0 = y, c0 = this._regioncode(x0, y0);
else x1 = x, y1 = y, c1 = this._regioncode(x1, y1);
}
}
_clipInfinite(i, points, vx0, vy0, vxn, vyn) {
let P = Array.from(points), p;
if (p = this._project(P[0], P[1], vx0, vy0)) P.unshift(p[0], p[1]);
if (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p[0], p[1]);
if (P = this._clipFinite(i, P)) {
for (let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2) {
c0 = c1, c1 = this._edgecode(P[j], P[j + 1]);
if (c0 && c1) j = this._edge(i, c0, c1, P, j), n = P.length;
}
} else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
P = [this.xmin, this.ymin, this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax];
}
return P;
}
_edge(i, e0, e1, P, j) {
while (e0 !== e1) {
let x, y;
switch (e0) {
case 0b0101: e0 = 0b0100; continue; // top-left
case 0b0100: e0 = 0b0110, x = this.xmax, y = this.ymin; break; // top
case 0b0110: e0 = 0b0010; continue; // top-right
case 0b0010: e0 = 0b1010, x = this.xmax, y = this.ymax; break; // right
case 0b1010: e0 = 0b1000; continue; // bottom-right
case 0b1000: e0 = 0b1001, x = this.xmin, y = this.ymax; break; // bottom
case 0b1001: e0 = 0b0001; continue; // bottom-left
case 0b0001: e0 = 0b0101, x = this.xmin, y = this.ymin; break; // left
}
if ((P[j] !== x || P[j + 1] !== y) && this.contains(i, x, y)) {
P.splice(j, 0, x, y), j += 2;
}
}
if (P.length > 4) {
for (let i = 0; i < P.length; i+= 2) {
const j = (i + 2) % P.length, k = (i + 4) % P.length;
if (P[i] === P[j] && P[j] === P[k]
|| P[i + 1] === P[j + 1] && P[j + 1] === P[k + 1])
P.splice(j, 2), i -= 2;
}
}
return j;
}
_project(x0, y0, vx, vy) {
let t = Infinity, c, x, y;
if (vy < 0) { // top
if (y0 <= this.ymin) return null;
if ((c = (this.ymin - y0) / vy) < t) y = this.ymin, x = x0 + (t = c) * vx;
} else if (vy > 0) { // bottom
if (y0 >= this.ymax) return null;
if ((c = (this.ymax - y0) / vy) < t) y = this.ymax, x = x0 + (t = c) * vx;
}
if (vx > 0) { // right
if (x0 >= this.xmax) return null;
if ((c = (this.xmax - x0) / vx) < t) x = this.xmax, y = y0 + (t = c) * vy;
} else if (vx < 0) { // left
if (x0 <= this.xmin) return null;
if ((c = (this.xmin - x0) / vx) < t) x = this.xmin, y = y0 + (t = c) * vy;
}
return [x, y];
}
_edgecode(x, y) {
return (x === this.xmin ? 0b0001
: x === this.xmax ? 0b0010 : 0b0000)
| (y === this.ymin ? 0b0100
: y === this.ymax ? 0b1000 : 0b0000);
}
_regioncode(x, y) {
return (x < this.xmin ? 0b0001
: x > this.xmax ? 0b0010 : 0b0000)
| (y < this.ymin ? 0b0100
: y > this.ymax ? 0b1000 : 0b0000);
}
}
// CONCATENATED MODULE: ./node_modules/d3-delaunay/src/delaunay.js
const delaunay_tau = 2 * Math.PI;
function delaunay_pointX(p) {
return p[0];
}
function delaunay_pointY(p) {
return p[1];
}
// A triangulation is collinear if all its triangles have a non-null area
function delaunay_collinear(d) {
const {triangles, coords} = d;
for (let i = 0; i < triangles.length; i += 3) {
const a = 2 * triangles[i],
b = 2 * triangles[i + 1],
c = 2 * triangles[i + 2],
cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])
- (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);
if (cross > 1e-10) return false;
}
return true;
}
function delaunay_jitter(x, y, r) {
return [x + Math.sin(x + y) * r, y + Math.cos(x - y) * r];
}
class delaunay_Delaunay {
static from(points, fx = delaunay_pointX, fy = delaunay_pointY, that) {
return new delaunay_Delaunay("length" in points
? delaunay_flatArray(points, fx, fy, that)
: Float64Array.from(delaunay_flatIterable(points, fx, fy, that)));
}
constructor(points) {
this._delaunator = new Delaunator(points);
this.inedges = new Int32Array(points.length / 2);
this._hullIndex = new Int32Array(points.length / 2);
this.points = this._delaunator.coords;
this._init();
}
update() {
this._delaunator.update();
this._init();
return this;
}
_init() {
const d = this._delaunator, points = this.points;
// check for collinear
if (d.hull && d.hull.length > 2 && delaunay_collinear(d)) {
this.collinear = Int32Array.from({length: points.length/2}, (_,i) => i)
.sort((i, j) => points[2 * i] - points[2 * j] || points[2 * i + 1] - points[2 * j + 1]); // for exact neighbors
const e = this.collinear[0], f = this.collinear[this.collinear.length - 1],
bounds = [ points[2 * e], points[2 * e + 1], points[2 * f], points[2 * f + 1] ],
r = 1e-8 * Math.sqrt((bounds[3] - bounds[1])**2 + (bounds[2] - bounds[0])**2);
for (let i = 0, n = points.length / 2; i < n; ++i) {
const p = delaunay_jitter(points[2 * i], points[2 * i + 1], r);
points[2 * i] = p[0];
points[2 * i + 1] = p[1];
}
this._delaunator = new Delaunator(points);
} else {
delete this.collinear;
}
const halfedges = this.halfedges = this._delaunator.halfedges;
const hull = this.hull = this._delaunator.hull;
const triangles = this.triangles = this._delaunator.triangles;
const inedges = this.inedges.fill(-1);
const hullIndex = this._hullIndex.fill(-1);
// Compute an index from each point to an (arbitrary) incoming halfedge
// Used to give the first neighbor of each point; for this reason,
// on the hull we give priority to exterior halfedges
for (let e = 0, n = halfedges.length; e < n; ++e) {
const p = triangles[e % 3 === 2 ? e - 2 : e + 1];
if (halfedges[e] === -1 || inedges[p] === -1) inedges[p] = e;
}
for (let i = 0, n = hull.length; i < n; ++i) {
hullIndex[hull[i]] = i;
}
// degenerate case: 1 or 2 (distinct) points
if (hull.length <= 2 && hull.length > 0) {
this.triangles = new Int32Array(3).fill(-1);
this.halfedges = new Int32Array(3).fill(-1);
this.triangles[0] = hull[0];
this.triangles[1] = hull[1];
this.triangles[2] = hull[1];
inedges[hull[0]] = 1;
if (hull.length === 2) inedges[hull[1]] = 0;
}
}
voronoi(bounds) {
return new voronoi_Voronoi(this, bounds);
}
*neighbors(i) {
const {inedges, hull, _hullIndex, halfedges, triangles, collinear} = this;
// degenerate case with several collinear points
if (collinear) {
const l = collinear.indexOf(i);
if (l > 0) yield collinear[l - 1];
if (l < collinear.length - 1) yield collinear[l + 1];
return;
}
const e0 = inedges[i];
if (e0 === -1) return; // coincident point
let e = e0, p0 = -1;
do {
yield p0 = triangles[e];
e = e % 3 === 2 ? e - 2 : e + 1;
if (triangles[e] !== i) return; // bad triangulation
e = halfedges[e];
if (e === -1) {
const p = hull[(_hullIndex[i] + 1) % hull.length];
if (p !== p0) yield p;
return;
}
} while (e !== e0);
}
find(x, y, i = 0) {
if ((x = +x, x !== x) || (y = +y, y !== y)) return -1;
const i0 = i;
let c;
while ((c = this._step(i, x, y)) >= 0 && c !== i && c !== i0) i = c;
return c;
}
_step(i, x, y) {
const {inedges, hull, _hullIndex, halfedges, triangles, points} = this;
if (inedges[i] === -1 || !points.length) return (i + 1) % (points.length >> 1);
let c = i;
let dc = (x - points[i * 2]) ** 2 + (y - points[i * 2 + 1]) ** 2;
const e0 = inedges[i];
let e = e0;
do {
let t = triangles[e];
const dt = (x - points[t * 2]) ** 2 + (y - points[t * 2 + 1]) ** 2;
if (dt < dc) dc = dt, c = t;
e = e % 3 === 2 ? e - 2 : e + 1;
if (triangles[e] !== i) break; // bad triangulation
e = halfedges[e];
if (e === -1) {
e = hull[(_hullIndex[i] + 1) % hull.length];
if (e !== t) {
if ((x - points[e * 2]) ** 2 + (y - points[e * 2 + 1]) ** 2 < dc) return e;
}
break;
}
} while (e !== e0);
return c;
}
render(context) {
const buffer = context == null ? context = new path_Path : undefined;
const {points, halfedges, triangles} = this;
for (let i = 0, n = halfedges.length; i < n; ++i) {
const j = halfedges[i];
if (j < i) continue;
const ti = triangles[i] * 2;
const tj = triangles[j] * 2;
context.moveTo(points[ti], points[ti + 1]);
context.lineTo(points[tj], points[tj + 1]);
}
this.renderHull(context);
return buffer && buffer.value();
}
renderPoints(context, r = 2) {
const buffer = context == null ? context = new path_Path : undefined;
const {points} = this;
for (let i = 0, n = points.length; i < n; i += 2) {
const x = points[i], y = points[i + 1];
context.moveTo(x + r, y);
context.arc(x, y, r, 0, delaunay_tau);
}
return buffer && buffer.value();
}
renderHull(context) {
const buffer = context == null ? context = new path_Path : undefined;
const {hull, points} = this;
const h = hull[0] * 2, n = hull.length;
context.moveTo(points[h], points[h + 1]);
for (let i = 1; i < n; ++i) {
const h = 2 * hull[i];
context.lineTo(points[h], points[h + 1]);
}
context.closePath();
return buffer && buffer.value();
}
hullPolygon() {
const polygon = new Polygon;
this.renderHull(polygon);
return polygon.value();
}
renderTriangle(i, context) {
const buffer = context == null ? context = new path_Path : undefined;
const {points, triangles} = this;
const t0 = triangles[i *= 3] * 2;
const t1 = triangles[i + 1] * 2;
const t2 = triangles[i + 2] * 2;
context.moveTo(points[t0], points[t0 + 1]);
context.lineTo(points[t1], points[t1 + 1]);
context.lineTo(points[t2], points[t2 + 1]);
context.closePath();
return buffer && buffer.value();
}
*trianglePolygons() {
const {triangles} = this;
for (let i = 0, n = triangles.length / 3; i < n; ++i) {
yield this.trianglePolygon(i);
}
}
trianglePolygon(i) {
const polygon = new Polygon;
this.renderTriangle(i, polygon);
return polygon.value();
}
}
function delaunay_flatArray(points, fx, fy, that) {
const n = points.length;
const array = new Float64Array(n * 2);
for (let i = 0; i < n; ++i) {
const p = points[i];
array[i * 2] = fx.call(that, p, i, points);
array[i * 2 + 1] = fy.call(that, p, i, points);
}
return array;
}
function* delaunay_flatIterable(points, fx, fy, that) {
let i = 0;
for (const p of points) {
yield fx.call(that, p, i, points);
yield fy.call(that, p, i, points);
++i;
}
}
// CONCATENATED MODULE: ./node_modules/vega-voronoi/src/Voronoi.js
function Voronoi_Voronoi(params) {
Transform_Transform.call(this, null, params);
}
Voronoi_Voronoi.Definition = {
"type": "Voronoi",
"metadata": {"modifies": true},
"params": [
{ "name": "x", "type": "field", "required": true },
{ "name": "y", "type": "field", "required": true },
{ "name": "size", "type": "number", "array": true, "length": 2 },
{ "name": "extent", "type": "array", "array": true, "length": 2,
"default": [[-1e5, -1e5], [1e5, 1e5]],
"content": {"type": "number", "array": true, "length": 2} },
{ "name": "as", "type": "string", "default": "path" }
]
};
const Voronoi_prototype = Object(vega_util["y" /* inherits */])(Voronoi_Voronoi, Transform_Transform);
const Voronoi_defaultExtent = [-1e5, -1e5, 1e5, 1e5];
Voronoi_prototype.transform = function(_, pulse) {
const as = _.as || 'path',
data = pulse.source;
// nothing to do if no data
if (!data || !data.length) return pulse;
// configure and construct voronoi diagram
let s = _.size;
s = s ? [0, 0, s[0], s[1]]
: (s = _.extent) ? [s[0][0], s[0][1], s[1][0], s[1][1]]
: Voronoi_defaultExtent;
const voronoi = this.value = delaunay_Delaunay.from(data, _.x, _.y).voronoi(s);
// map polygons to paths
for (let i=0, n=data.length; i<n; ++i) {
const polygon = voronoi.cellPolygon(i);
data[i][as] = polygon ? Voronoi_toPathString(polygon) : null;
}
return pulse.reflow(_.modified()).modifies(as);
};
// suppress duplicated end point vertices
function Voronoi_toPathString(p) {
const x = p[0][0],
y = p[0][1];
let n = p.length - 1;
for (; p[n][0] === x && p[n][1] === y; --n);
return 'M' + p.slice(0, n + 1).join('L') + 'Z';
}
// CONCATENATED MODULE: ./node_modules/vega-voronoi/index.js
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/src/CloudLayout.js
/*
Copyright (c) 2013, Jason Davies.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name Jason Davies may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL JASON DAVIES BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
var CloudLayout_cloudRadians = Math.PI / 180,
CloudLayout_cw = 1 << 11 >> 5,
CloudLayout_ch = 1 << 11;
/* harmony default export */ var CloudLayout = (function() {
var size = [256, 256],
text,
font,
fontSize,
fontStyle,
fontWeight,
rotate,
padding,
spiral = CloudLayout_archimedeanSpiral,
words = [],
random = Math.random,
cloud = {};
cloud.layout = function() {
var contextAndRatio = getContext(domCanvas()),
board = CloudLayout_zeroArray((size[0] >> 5) * size[1]),
bounds = null,
n = words.length,
i = -1,
tags = [],
data = words.map(function(d) {
return {
text: text(d),
font: font(d),
style: fontStyle(d),
weight: fontWeight(d),
rotate: rotate(d),
size: ~~(fontSize(d) + 1e-14),
padding: padding(d),
xoff: 0,
yoff: 0,
x1: 0,
y1: 0,
x0: 0,
y0: 0,
hasText: false,
sprite: null,
datum: d
};
}).sort(function(a, b) { return b.size - a.size; });
while (++i < n) {
var d = data[i];
d.x = (size[0] * (random() + .5)) >> 1;
d.y = (size[1] * (random() + .5)) >> 1;
CloudLayout_cloudSprite(contextAndRatio, d, data, i);
if (d.hasText && place(board, d, bounds)) {
tags.push(d);
if (bounds) CloudLayout_cloudBounds(bounds, d);
else bounds = [{x: d.x + d.x0, y: d.y + d.y0}, {x: d.x + d.x1, y: d.y + d.y1}];
// Temporary hack
d.x -= size[0] >> 1;
d.y -= size[1] >> 1;
}
}
return tags;
};
function getContext(canvas) {
canvas.width = canvas.height = 1;
var ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2);
canvas.width = (CloudLayout_cw << 5) / ratio;
canvas.height = CloudLayout_ch / ratio;
var context = canvas.getContext("2d");
context.fillStyle = context.strokeStyle = "red";
context.textAlign = "center";
return {context: context, ratio: ratio};
}
function place(board, tag, bounds) {
var startX = tag.x,
startY = tag.y,
maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
s = spiral(size),
dt = random() < .5 ? 1 : -1,
t = -dt,
dxdy,
dx,
dy;
while (dxdy = s(t += dt)) {
dx = ~~dxdy[0];
dy = ~~dxdy[1];
if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
tag.x = startX + dx;
tag.y = startY + dy;
if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 ||
tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
// TODO only check for collisions within current bounds.
if (!bounds || !CloudLayout_cloudCollide(tag, board, size[0])) {
if (!bounds || CloudLayout_collideRects(tag, bounds)) {
var sprite = tag.sprite,
w = tag.width >> 5,
sw = size[0] >> 5,
lx = tag.x - (w << 4),
sx = lx & 0x7f,
msx = 32 - sx,
h = tag.y1 - tag.y0,
x = (tag.y + tag.y0) * sw + (lx >> 5),
last;
for (var j = 0; j < h; j++) {
last = 0;
for (var i = 0; i <= w; i++) {
board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
}
x += sw;
}
tag.sprite = null;
return true;
}
}
}
return false;
}
cloud.words = function(_) {
if (arguments.length) {
words = _;
return cloud;
} else {
return words;
}
};
cloud.size = function(_) {
if (arguments.length) {
size = [+_[0], +_[1]];
return cloud;
} else {
return size;
}
};
cloud.font = function(_) {
if (arguments.length) {
font = CloudLayout_functor(_);
return cloud;
} else {
return font;
}
};
cloud.fontStyle = function(_) {
if (arguments.length) {
fontStyle = CloudLayout_functor(_);
return cloud;
} else {
return fontStyle;
}
};
cloud.fontWeight = function(_) {
if (arguments.length) {
fontWeight = CloudLayout_functor(_);
return cloud;
} else {
return fontWeight;
}
};
cloud.rotate = function(_) {
if (arguments.length) {
rotate = CloudLayout_functor(_);
return cloud;
} else {
return rotate;
}
};
cloud.text = function(_) {
if (arguments.length) {
text = CloudLayout_functor(_);
return cloud;
} else {
return text;
}
};
cloud.spiral = function(_) {
if (arguments.length) {
spiral = CloudLayout_spirals[_] || _;
return cloud;
} else {
return spiral;
}
};
cloud.fontSize = function(_) {
if (arguments.length) {
fontSize = CloudLayout_functor(_);
return cloud;
} else {
return fontSize;
}
};
cloud.padding = function(_) {
if (arguments.length) {
padding = CloudLayout_functor(_);
return cloud;
} else {
return padding;
}
};
cloud.random = function(_) {
if (arguments.length) {
random = _;
return cloud;
} else {
return random;
}
};
return cloud;
});
// Fetches a monochrome sprite bitmap for the specified text.
// Load in batches for speed.
function CloudLayout_cloudSprite(contextAndRatio, d, data, di) {
if (d.sprite) return;
var c = contextAndRatio.context,
ratio = contextAndRatio.ratio;
c.clearRect(0, 0, (CloudLayout_cw << 5) / ratio, CloudLayout_ch / ratio);
var x = 0,
y = 0,
maxh = 0,
n = data.length,
w, w32, h, i, j;
--di;
while (++di < n) {
d = data[di];
c.save();
c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font;
w = c.measureText(d.text + "m").width * ratio;
h = d.size << 1;
if (d.rotate) {
var sr = Math.sin(d.rotate * CloudLayout_cloudRadians),
cr = Math.cos(d.rotate * CloudLayout_cloudRadians),
wcr = w * cr,
wsr = w * sr,
hcr = h * cr,
hsr = h * sr;
w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5;
h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
} else {
w = (w + 0x1f) >> 5 << 5;
}
if (h > maxh) maxh = h;
if (x + w >= (CloudLayout_cw << 5)) {
x = 0;
y += maxh;
maxh = 0;
}
if (y + h >= CloudLayout_ch) break;
c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
if (d.rotate) c.rotate(d.rotate * CloudLayout_cloudRadians);
c.fillText(d.text, 0, 0);
if (d.padding) {
c.lineWidth = 2 * d.padding;
c.strokeText(d.text, 0, 0);
}
c.restore();
d.width = w;
d.height = h;
d.xoff = x;
d.yoff = y;
d.x1 = w >> 1;
d.y1 = h >> 1;
d.x0 = -d.x1;
d.y0 = -d.y1;
d.hasText = true;
x += w;
}
var pixels = c.getImageData(0, 0, (CloudLayout_cw << 5) / ratio, CloudLayout_ch / ratio).data,
sprite = [];
while (--di >= 0) {
d = data[di];
if (!d.hasText) continue;
w = d.width;
w32 = w >> 5;
h = d.y1 - d.y0;
// Zero the buffer
for (i = 0; i < h * w32; i++) sprite[i] = 0;
x = d.xoff;
if (x == null) return;
y = d.yoff;
var seen = 0,
seenRow = -1;
for (j = 0; j < h; j++) {
for (i = 0; i < w; i++) {
var k = w32 * j + (i >> 5),
m = pixels[((y + j) * (CloudLayout_cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
sprite[k] |= m;
seen |= m;
}
if (seen) seenRow = j;
else {
d.y0++;
h--;
j--;
y++;
}
}
d.y1 = d.y0 + seenRow;
d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
}
}
// Use mask-based collision detection.
function CloudLayout_cloudCollide(tag, board, sw) {
sw >>= 5;
var sprite = tag.sprite,
w = tag.width >> 5,
lx = tag.x - (w << 4),
sx = lx & 0x7f,
msx = 32 - sx,
h = tag.y1 - tag.y0,
x = (tag.y + tag.y0) * sw + (lx >> 5),
last;
for (var j = 0; j < h; j++) {
last = 0;
for (var i = 0; i <= w; i++) {
if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0))
& board[x + i]) return true;
}
x += sw;
}
return false;
}
function CloudLayout_cloudBounds(bounds, d) {
var b0 = bounds[0],
b1 = bounds[1];
if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
}
function CloudLayout_collideRects(a, b) {
return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
}
function CloudLayout_archimedeanSpiral(size) {
var e = size[0] / size[1];
return function(t) {
return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
};
}
function CloudLayout_rectangularSpiral(size) {
var dy = 4,
dx = dy * size[0] / size[1],
x = 0,
y = 0;
return function(t) {
var sign = t < 0 ? -1 : 1;
// See triangular numbers: T_n = n * (n + 1) / 2.
switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
case 0: x += dx; break;
case 1: y += dy; break;
case 2: x -= dx; break;
default: y -= dy; break;
}
return [x, y];
};
}
// TODO reuse arrays?
function CloudLayout_zeroArray(n) {
var a = [],
i = -1;
while (++i < n) a[i] = 0;
return a;
}
function CloudLayout_functor(d) {
return typeof d === "function" ? d : function() { return d; };
}
var CloudLayout_spirals = {
archimedean: CloudLayout_archimedeanSpiral,
rectangular: CloudLayout_rectangularSpiral
};
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/bandSpace.js
/* harmony default export */ var scales_bandSpace = (function(count, paddingInner, paddingOuter) {
var space = count - paddingInner + paddingOuter * 2;
return count ? (space > 0 ? space : 1) : 0;
});
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/types.js
const types_Identity = 'identity';
const scales_types_Linear = 'linear';
const types_Log = 'log';
const types_Pow = 'pow';
const types_Sqrt = 'sqrt';
const types_Symlog = 'symlog';
const types_Time = 'time';
const types_UTC = 'utc';
const types_Sequential = 'sequential';
const types_Diverging = 'diverging';
const scales_types_Quantile = 'quantile';
const types_Quantize = 'quantize';
const types_Threshold = 'threshold';
const types_Ordinal = 'ordinal';
const types_Point = 'point';
const types_Band = 'band';
const types_BinOrdinal = 'bin-ordinal';
// categories
const types_Continuous = 'continuous';
const types_Discrete = 'discrete';
const types_Discretizing = 'discretizing';
const types_Interpolating = 'interpolating';
const types_Temporal = 'temporal';
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/invertRange.js
/* harmony default export */ var scales_invertRange = (function(scale) {
return function(_) {
var lo = _[0],
hi = _[1],
t;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
return [
scale.invert(lo),
scale.invert(hi)
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/invertRangeExtent.js
/* harmony default export */ var scales_invertRangeExtent = (function(scale) {
return function(_) {
var range = scale.range(),
lo = _[0],
hi = _[1],
min = -1, max, t, i, n;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
for (i=0, n=range.length; i<n; ++i) {
if (range[i] >= lo && range[i] <= hi) {
if (min < 0) min = i;
max = i;
}
}
if (min < 0) return undefined;
lo = scale.invertExtent(range[min]);
hi = scale.invertExtent(range[max]);
return [
lo[0] === undefined ? lo[1] : lo[0],
hi[1] === undefined ? hi[0] : hi[1]
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/scaleBand.js
function scales_scaleBand_band() {
var scale = ordinal_ordinal().unknown(undefined),
domain = scale.domain,
ordinalRange = scale.range,
range = [0, 1],
step,
bandwidth,
round = false,
paddingInner = 0,
paddingOuter = 0,
align = 0.5;
delete scale.unknown;
function rescale() {
var n = domain().length,
reverse = range[1] < range[0],
start = range[reverse - 0],
stop = range[1 - reverse],
space = scales_bandSpace(n, paddingInner, paddingOuter);
step = (stop - start) / (space || 1);
if (round) {
step = Math.floor(step);
}
start += (stop - start - step * (n - paddingInner)) * align;
bandwidth = step * (1 - paddingInner);
if (round) {
start = Math.round(start);
bandwidth = Math.round(bandwidth);
}
var values = src_range(n).map(function(i) { return start + step * i; });
return ordinalRange(reverse ? values.reverse() : values);
}
scale.domain = function(_) {
if (arguments.length) {
domain(_);
return rescale();
} else {
return domain();
}
};
scale.range = function(_) {
if (arguments.length) {
range = [+_[0], +_[1]];
return rescale();
} else {
return range.slice();
}
};
scale.rangeRound = function(_) {
range = [+_[0], +_[1]];
round = true;
return rescale();
};
scale.bandwidth = function() {
return bandwidth;
};
scale.step = function() {
return step;
};
scale.round = function(_) {
if (arguments.length) {
round = !!_;
return rescale();
} else {
return round;
}
};
scale.padding = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
paddingInner = paddingOuter;
return rescale();
} else {
return paddingInner;
}
};
scale.paddingInner = function(_) {
if (arguments.length) {
paddingInner = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingInner;
}
};
scale.paddingOuter = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingOuter;
}
};
scale.align = function(_) {
if (arguments.length) {
align = Math.max(0, Math.min(1, _));
return rescale();
} else {
return align;
}
};
scale.invertRange = function(_) {
// bail if range has null or undefined values
if (_[0] == null || _[1] == null) return;
var lo = +_[0],
hi = +_[1],
reverse = range[1] < range[0],
values = reverse ? ordinalRange().reverse() : ordinalRange(),
n = values.length - 1, a, b, t;
// bail if either range endpoint is invalid
if (lo !== lo || hi !== hi) return;
// order range inputs, bail if outside of scale range
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
if (hi < values[0] || lo > range[1-reverse]) return;
// binary search to index into scale range
a = Math.max(0, bisect_bisectRight(values, lo) - 1);
b = lo===hi ? a : bisect_bisectRight(values, hi) - 1;
// increment index a if lo is within padding gap
if (lo - values[a] > bandwidth + 1e-10) ++a;
if (reverse) {
// map + swap
t = a;
a = n - b;
b = n - t;
}
return (a > b) ? undefined : domain().slice(a, b+1);
};
scale.invert = function(_) {
var value = scale.invertRange([_, _]);
return value ? value[0] : value;
};
scale.copy = function() {
return scales_scaleBand_band()
.domain(domain())
.range(range)
.round(round)
.paddingInner(paddingInner)
.paddingOuter(paddingOuter)
.align(align);
};
return rescale();
}
function scales_scaleBand_pointish(scale) {
var copy = scale.copy;
scale.padding = scale.paddingOuter;
delete scale.paddingInner;
scale.copy = function() {
return scales_scaleBand_pointish(copy());
};
return scale;
}
function scales_scaleBand_point() {
return scales_scaleBand_pointish(scales_scaleBand_band().paddingInner(1));
}
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/numbers.js
var scales_numbers_map = Array.prototype.map;
function scales_numbers_numbers(_) {
return scales_numbers_map.call(_, function(x) { return +x; });
}
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/slice.js
var slice_slice = Array.prototype.slice;
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales/scaleBinOrdinal.js
function scales_scaleBinOrdinal_scaleBinOrdinal() {
var domain = [],
range = [];
function scale(x) {
return x == null || x !== x
? undefined
: range[(d3_array_src_bisect(domain, x) - 1) % range.length];
}
scale.domain = function(_) {
if (arguments.length) {
domain = scales_numbers_numbers(_);
return scale;
} else {
return domain.slice();
}
};
scale.range = function(_) {
if (arguments.length) {
range = slice_slice.call(_);
return scale;
} else {
return range.slice();
}
};
scale.tickFormat = function(count, specifier) {
return src_tickFormat(domain[0], Object(vega_util["U" /* peek */])(domain), count == null ? 10 : count, specifier);
};
scale.copy = function() {
return scales_scaleBinOrdinal_scaleBinOrdinal().domain(scale.domain()).range(scale.range());
};
return scale;
}
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/scales.js
// scale registry
const src_scales_scales = {};
/**
* Augment scales with their type and needed inverse methods.
*/
function src_scales_create(type, constructor, metadata) {
const ctr = function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? scales_invertRange(s)
: s.invertExtent ? scales_invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
ctr.metadata = Object(vega_util["Da" /* toSet */])(Object(vega_util["i" /* array */])(metadata));
return ctr;
}
function src_scales_scale(type, scale, metadata) {
if (arguments.length > 1) {
src_scales_scales[type] = src_scales_create(type, scale, metadata);
return this;
} else {
return src_scales_isValidScaleType(type) ? src_scales_scales[type] : undefined;
}
}
// identity scale
src_scales_scale(types_Identity, identity_identity);
// continuous scales
src_scales_scale(scales_types_Linear, linear_linear, types_Continuous);
src_scales_scale(types_Log, log_log, [types_Continuous, types_Log]);
src_scales_scale(types_Pow, pow_pow, types_Continuous);
src_scales_scale(types_Sqrt, pow_sqrt, types_Continuous);
src_scales_scale(types_Symlog, symlog_symlog, types_Continuous);
src_scales_scale(types_Time, src_time, [types_Continuous, types_Temporal]);
src_scales_scale(types_UTC, utcTime, [types_Continuous, types_Temporal]);
// sequential scales
src_scales_scale(types_Sequential, sequential_sequential, [types_Continuous, types_Interpolating]); // backwards compat
src_scales_scale(`${types_Sequential}-${scales_types_Linear}`, sequential_sequential, [types_Continuous, types_Interpolating]);
src_scales_scale(`${types_Sequential}-${types_Log}`, sequential_sequentialLog, [types_Continuous, types_Interpolating, types_Log]);
src_scales_scale(`${types_Sequential}-${types_Pow}`, sequential_sequentialPow, [types_Continuous, types_Interpolating]);
src_scales_scale(`${types_Sequential}-${types_Sqrt}`, sequential_sequentialSqrt, [types_Continuous, types_Interpolating]);
src_scales_scale(`${types_Sequential}-${types_Symlog}`, sequential_sequentialSymlog, [types_Continuous, types_Interpolating]);
// diverging scales
src_scales_scale(`${types_Diverging}-${scales_types_Linear}`, diverging_diverging, [types_Continuous, types_Interpolating]);
src_scales_scale(`${types_Diverging}-${types_Log}`, diverging_divergingLog, [types_Continuous, types_Interpolating, types_Log]);
src_scales_scale(`${types_Diverging}-${types_Pow}`, diverging_divergingPow, [types_Continuous, types_Interpolating]);
src_scales_scale(`${types_Diverging}-${types_Sqrt}`, diverging_divergingSqrt, [types_Continuous, types_Interpolating]);
src_scales_scale(`${types_Diverging}-${types_Symlog}`, diverging_divergingSymlog, [types_Continuous, types_Interpolating]);
// discretizing scales
src_scales_scale(scales_types_Quantile, src_quantile_quantile, [types_Discretizing, scales_types_Quantile]);
src_scales_scale(types_Quantize, quantize_quantize, types_Discretizing);
src_scales_scale(types_Threshold, threshold_threshold, types_Discretizing);
// discrete scales
src_scales_scale(types_BinOrdinal, scales_scaleBinOrdinal_scaleBinOrdinal, [types_Discrete, types_Discretizing]);
src_scales_scale(types_Ordinal, ordinal_ordinal, types_Discrete);
src_scales_scale(types_Band, scales_scaleBand_band, types_Discrete);
src_scales_scale(types_Point, scales_scaleBand_point, types_Discrete);
function src_scales_isValidScaleType(type) {
return Object(vega_util["v" /* hasOwnProperty */])(src_scales_scales, type);
}
function src_scales_hasType(key, type) {
const s = src_scales_scales[key];
return s && s.metadata[type];
}
function src_scales_isContinuous(key) {
return src_scales_hasType(key, types_Continuous);
}
function src_scales_isDiscrete(key) {
return src_scales_hasType(key, types_Discrete);
}
function src_scales_isDiscretizing(key) {
return src_scales_hasType(key, types_Discretizing);
}
function src_scales_isLogarithmic(key) {
return src_scales_hasType(key, types_Log);
}
function src_scales_isTemporal(key) {
return src_scales_hasType(key, types_Temporal);
}
function src_scales_isInterpolating(key) {
return src_scales_hasType(key, types_Interpolating);
}
function src_scales_isQuantile(key) {
return src_scales_hasType(key, scales_types_Quantile);
}
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/interpolate.js
const src_interpolate_scaleProps = ['clamp', 'base', 'constant', 'exponent'];
function src_interpolate_interpolateRange(interpolator, range) {
var start = range[0],
span = Object(vega_util["U" /* peek */])(range) - start;
return function(i) { return interpolator(start + i * span); };
}
function src_interpolate_interpolateColors(colors, type, gamma) {
return piecewise_piecewise(src_interpolate_interpolate(type || 'rgb', gamma), colors);
}
function src_interpolate_quantizeInterpolator(interpolator, count) {
var samples = new Array(count),
n = count + 1;
for (var i = 0; i < count;) samples[i] = interpolator(++i / n);
return samples;
}
function src_interpolate_scaleCopy(scale) {
const t = scale.type,
s = scale.copy();
s.type = t;
return s;
}
function src_interpolate_scaleFraction(scale, min, max) {
var delta = max - min, i, t, s;
if (!delta || !Number.isFinite(delta)) {
return Object(vega_util["l" /* constant */])(0.5);
} else {
i = (t = scale.type).indexOf('-');
t = i < 0 ? t : t.slice(i + 1);
s = src_scales_scale(t)().domain([min, max]).range([0, 1]);
src_interpolate_scaleProps.forEach(m => scale[m] ? s[m](scale[m]()) : 0);
return s;
}
}
function src_interpolate_interpolate(type, gamma) {
var interp = d3_interpolate_src_namespaceObject[src_interpolate_method(type)];
return (gamma != null && interp && interp.gamma)
? interp.gamma(gamma)
: interp;
}
function src_interpolate_method(type) {
return 'interpolate' + type.toLowerCase()
.split('-')
.map(function(s) { return s[0].toUpperCase() + s.slice(1); })
.join('');
}
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/palettes.js
const src_palettes_continuous = {
blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',
greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',
greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',
oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',
purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',
reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',
blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',
bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',
greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',
orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',
purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',
purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',
purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',
redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',
yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',
yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',
yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',
blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',
brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',
purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',
purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',
redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',
redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',
yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',
redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',
redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',
pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',
spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',
viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',
magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',
inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',
plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',
rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',
sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',
browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',
tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',
teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',
warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',
goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',
goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',
goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',
lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',
lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',
lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',
lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',
lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',
darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',
darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',
darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',
darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',
darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'
};
const src_palettes_discrete = {
category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',
category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',
category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',
category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',
tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',
tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',
accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',
dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',
paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',
pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',
pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',
set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',
set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',
set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f'
};
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/src/schemes.js
function src_schemes_colors(palette) {
var n = palette.length / 6 | 0, c = new Array(n), i = 0;
while (i < n) c[i] = '#' + palette.slice(i * 6, ++i * 6);
return c;
}
function src_schemes_apply(_, f) {
for (let k in _) src_schemes_scheme(k, f(_[k]));
}
const src_schemes_schemes = {};
src_schemes_apply(src_palettes_discrete, src_schemes_colors);
src_schemes_apply(src_palettes_continuous, _ => src_interpolate_interpolateColors(src_schemes_colors(_)));
function src_schemes_scheme(name, scheme) {
name = name && name.toLowerCase();
if (arguments.length > 1) {
src_schemes_schemes[name] = scheme;
return this;
} else {
return src_schemes_schemes[name];
}
}
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/node_modules/vega-scale/index.js
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/src/Wordcloud.js
var Wordcloud_Output = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle'];
var Wordcloud_Params = ['text', 'font', 'rotate', 'fontSize', 'fontStyle', 'fontWeight'];
function Wordcloud_Wordcloud(params) {
Transform_Transform.call(this, CloudLayout(), params);
}
Wordcloud_Wordcloud.Definition = {
"type": "Wordcloud",
"metadata": {"modifies": true},
"params": [
{ "name": "size", "type": "number", "array": true, "length": 2 },
{ "name": "font", "type": "string", "expr": true, "default": "sans-serif" },
{ "name": "fontStyle", "type": "string", "expr": true, "default": "normal" },
{ "name": "fontWeight", "type": "string", "expr": true, "default": "normal" },
{ "name": "fontSize", "type": "number", "expr": true, "default": 14 },
{ "name": "fontSizeRange", "type": "number", "array": "nullable", "default": [10, 50] },
{ "name": "rotate", "type": "number", "expr": true, "default": 0 },
{ "name": "text", "type": "field" },
{ "name": "spiral", "type": "string", "values": ["archimedean", "rectangular"] },
{ "name": "padding", "type": "number", "expr": true },
{ "name": "as", "type": "string", "array": true, "length": 7, "default": Wordcloud_Output }
]
};
var Wordcloud_prototype = Object(vega_util["y" /* inherits */])(Wordcloud_Wordcloud, Transform_Transform);
Wordcloud_prototype.transform = function(_, pulse) {
if (_.size && !(_.size[0] && _.size[1])) {
Object(vega_util["n" /* error */])('Wordcloud size dimensions must be non-zero.');
}
function modp(param) {
var p = _[param];
return Object(vega_util["D" /* isFunction */])(p) && pulse.modified(p.fields);
}
var mod = _.modified();
if (!(mod || pulse.changed(pulse.ADD_REM) || Wordcloud_Params.some(modp))) return;
var data = pulse.materialize(pulse.SOURCE).source,
layout = this.value,
as = _.as || Wordcloud_Output,
fontSize = _.fontSize || 14,
range;
Object(vega_util["D" /* isFunction */])(fontSize)
? (range = _.fontSizeRange)
: (fontSize = Object(vega_util["l" /* constant */])(fontSize));
// create font size scaling function as needed
if (range) {
var fsize = fontSize,
sizeScale = src_scales_scale('sqrt')()
.domain(Object(vega_util["p" /* extent */])(data, fsize))
.range(range);
fontSize = function(x) { return sizeScale(fsize(x)); };
}
data.forEach(function(t) {
t[as[0]] = NaN;
t[as[1]] = NaN;
t[as[3]] = 0;
});
// configure layout
var words = layout
.words(data)
.text(_.text)
.size(_.size || [500, 500])
.padding(_.padding || 1)
.spiral(_.spiral || 'archimedean')
.rotate(_.rotate || 0)
.font(_.font || 'sans-serif')
.fontStyle(_.fontStyle || 'normal')
.fontWeight(_.fontWeight || 'normal')
.fontSize(fontSize)
.random(random_random)
.layout();
var size = layout.size(),
dx = size[0] >> 1,
dy = size[1] >> 1,
i = 0,
n = words.length,
w, t;
for (; i<n; ++i) {
w = words[i];
t = w.datum;
t[as[0]] = w.x + dx;
t[as[1]] = w.y + dy;
t[as[2]] = w.font;
t[as[3]] = w.size;
t[as[4]] = w.style;
t[as[5]] = w.weight;
t[as[6]] = w.rotate;
}
return pulse.reflow(mod).modifies(as);
};
// CONCATENATED MODULE: ./node_modules/vega-wordcloud/index.js
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/src/arrays.js
function array8(n) { return new Uint8Array(n); }
function array16(n) { return new Uint16Array(n); }
function array32(n) { return new Uint32Array(n); }
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/src/Bitmaps.js
/**
* Maintains CrossFilter state.
*/
function Bitmaps_Bitmaps() {
var width = 8,
data = [],
seen = array32(0),
curr = Bitmaps_array(0, width),
prev = Bitmaps_array(0, width);
return {
data: function() { return data; },
seen: function() {
return (seen = Bitmaps_lengthen(seen, data.length));
},
add: function(array) {
for (var i=0, j=data.length, n=array.length, t; i<n; ++i) {
t = array[i];
t._index = j++;
data.push(t);
}
},
remove: function(num, map) { // map: index -> boolean (true => remove)
var n = data.length,
copy = Array(n - num),
reindex = data, // reuse old data array for index map
t, i, j;
// seek forward to first removal
for (i=0; !map[i] && i<n; ++i) {
copy[i] = data[i];
reindex[i] = i;
}
// condense arrays
for (j=i; i<n; ++i) {
t = data[i];
if (!map[i]) {
reindex[i] = j;
curr[j] = curr[i];
prev[j] = prev[i];
copy[j] = t;
t._index = j++;
} else {
reindex[i] = -1;
}
curr[i] = 0; // clear unused bits
}
data = copy;
return reindex;
},
size: function() { return data.length; },
curr: function() { return curr; },
prev: function() { return prev; },
reset: function(k) { prev[k] = curr[k]; },
all: function() {
return width < 0x101 ? 0xff : width < 0x10001 ? 0xffff : 0xffffffff;
},
set: function(k, one) { curr[k] |= one; },
clear: function(k, one) { curr[k] &= ~one; },
resize: function(n, m) {
var k = curr.length;
if (n > k || m > width) {
width = Math.max(m, width);
curr = Bitmaps_array(n, width, curr);
prev = Bitmaps_array(n, width);
}
}
};
}
function Bitmaps_lengthen(array, length, copy) {
if (array.length >= length) return array;
copy = copy || new array.constructor(length);
copy.set(array);
return copy;
}
function Bitmaps_array(n, m, array) {
var copy = (m < 0x101 ? array8 : m < 0x10001 ? array16 : array32)(n);
if (array) copy.set(array);
return copy;
}
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/src/Dimension.js
/* harmony default export */ var Dimension = (function(index, i, query) {
var bit = (1 << i);
return {
one: bit,
zero: ~bit,
range: query.slice(),
bisect: index.bisect,
index: index.index,
size: index.size,
onAdd: function(added, curr) {
var dim = this,
range = dim.bisect(dim.range, added.value),
idx = added.index,
lo = range[0],
hi = range[1],
n1 = idx.length, i;
for (i=0; i<lo; ++i) curr[idx[i]] |= bit;
for (i=hi; i<n1; ++i) curr[idx[i]] |= bit;
return dim;
}
};
});
// CONCATENATED MODULE: ./node_modules/d3-array/src/permute.js
/* harmony default export */ var src_permute = (function(source, keys) {
return Array.from(keys, key => source[key]);
});
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/src/SortedIndex.js
/**
* Maintains a list of values, sorted by key.
*/
function SortedIndex_SortedIndex() {
var index = array32(0),
value = [],
size = 0;
function insert(key, data, base) {
if (!data.length) return [];
var n0 = size,
n1 = data.length,
addv = Array(n1),
addi = array32(n1),
oldv, oldi, i;
for (i=0; i<n1; ++i) {
addv[i] = key(data[i]);
addi[i] = i;
}
addv = SortedIndex_sort(addv, addi);
if (n0) {
oldv = value;
oldi = index;
value = Array(n0 + n1);
index = array32(n0 + n1);
SortedIndex_merge(base, oldv, oldi, n0, addv, addi, n1, value, index);
} else {
if (base > 0) for (i=0; i<n1; ++i) {
addi[i] += base;
}
value = addv;
index = addi;
}
size = n0 + n1;
return {index: addi, value: addv};
}
function remove(num, map) {
// map: index -> remove
var n = size,
idx, i, j;
// seek forward to first removal
for (i=0; !map[index[i]] && i<n; ++i);
// condense index and value arrays
for (j=i; i<n; ++i) {
if (!map[idx=index[i]]) {
index[j] = idx;
value[j] = value[i];
++j;
}
}
size = n - num;
}
function reindex(map) {
for (var i=0, n=size; i<n; ++i) {
index[i] = map[index[i]];
}
}
function bisect(range, array) {
var n;
if (array) {
n = array.length;
} else {
array = value;
n = size;
}
return [
bisect_bisectLeft(array, range[0], 0, n),
bisect_bisectRight(array, range[1], 0, n)
];
}
return {
insert: insert,
remove: remove,
bisect: bisect,
reindex: reindex,
index: function() { return index; },
size: function() { return size; }
};
}
function SortedIndex_sort(values, index) {
values.sort.call(index, function(a, b) {
var x = values[a],
y = values[b];
return x < y ? -1 : x > y ? 1 : 0;
});
return src_permute(values, index);
}
function SortedIndex_merge(base, value0, index0, n0, value1, index1, n1, value, index) {
var i0 = 0, i1 = 0, i;
for (i=0; i0 < n0 && i1 < n1; ++i) {
if (value0[i0] < value1[i1]) {
value[i] = value0[i0];
index[i] = index0[i0++];
} else {
value[i] = value1[i1];
index[i] = index1[i1++] + base;
}
}
for (; i0 < n0; ++i0, ++i) {
value[i] = value0[i0];
index[i] = index0[i0];
}
for (; i1 < n1; ++i1, ++i) {
value[i] = value1[i1];
index[i] = index1[i1] + base;
}
}
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/src/CrossFilter.js
/**
* An indexed multi-dimensional filter.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {Array<function(object): *>} params.fields - An array of dimension accessors to filter.
* @param {Array} params.query - An array of per-dimension range queries.
*/
function CrossFilter_CrossFilter(params) {
Transform_Transform.call(this, Bitmaps_Bitmaps(), params);
this._indices = null;
this._dims = null;
}
CrossFilter_CrossFilter.Definition = {
"type": "CrossFilter",
"metadata": {},
"params": [
{ "name": "fields", "type": "field", "array": true, "required": true },
{ "name": "query", "type": "array", "array": true, "required": true,
"content": {"type": "number", "array": true, "length": 2} }
]
};
var CrossFilter_prototype = Object(vega_util["y" /* inherits */])(CrossFilter_CrossFilter, Transform_Transform);
CrossFilter_prototype.transform = function(_, pulse) {
if (!this._dims) {
return this.init(_, pulse);
} else {
var init = _.modified('fields')
|| _.fields.some(function(f) { return pulse.modified(f.fields); });
return init
? this.reinit(_, pulse)
: this.eval(_, pulse);
}
};
CrossFilter_prototype.init = function(_, pulse) {
var fields = _.fields,
query = _.query,
indices = this._indices = {},
dims = this._dims = [],
m = query.length,
i = 0, key, index;
// instantiate indices and dimensions
for (; i<m; ++i) {
key = fields[i].fname;
index = indices[key] || (indices[key] = SortedIndex_SortedIndex());
dims.push(Dimension(index, i, query[i]));
}
return this.eval(_, pulse);
};
CrossFilter_prototype.reinit = function(_, pulse) {
var output = pulse.materialize().fork(),
fields = _.fields,
query = _.query,
indices = this._indices,
dims = this._dims,
bits = this.value,
curr = bits.curr(),
prev = bits.prev(),
all = bits.all(),
out = (output.rem = output.add),
mod = output.mod,
m = query.length,
adds = {}, add, index, key,
mods, remMap, modMap, i, n, f;
// set prev to current state
prev.set(curr);
// if pulse has remove tuples, process them first
if (pulse.rem.length) {
remMap = this.remove(_, pulse, output);
}
// if pulse has added tuples, add them to state
if (pulse.add.length) {
bits.add(pulse.add);
}
// if pulse has modified tuples, create an index map
if (pulse.mod.length) {
modMap = {};
for (mods=pulse.mod, i=0, n=mods.length; i<n; ++i) {
modMap[mods[i]._index] = 1;
}
}
// re-initialize indices as needed, update curr bitmap
for (i=0; i<m; ++i) {
f = fields[i];
if (!dims[i] || _.modified('fields', i) || pulse.modified(f.fields)) {
key = f.fname;
if (!(add = adds[key])) {
indices[key] = index = SortedIndex_SortedIndex();
adds[key] = add = index.insert(f, pulse.source, 0);
}
dims[i] = Dimension(index, i, query[i]).onAdd(add, curr);
}
}
// visit each tuple
// if filter state changed, push index to add/rem
// else if in mod and passes a filter, push index to mod
for (i=0, n=bits.data().length; i<n; ++i) {
if (remMap[i]) { // skip if removed tuple
continue;
} else if (prev[i] !== curr[i]) { // add if state changed
out.push(i);
} else if (modMap[i] && curr[i] !== all) { // otherwise, pass mods through
mod.push(i);
}
}
bits.mask = (1 << m) - 1;
return output;
};
CrossFilter_prototype.eval = function(_, pulse) {
var output = pulse.materialize().fork(),
m = this._dims.length,
mask = 0;
if (pulse.rem.length) {
this.remove(_, pulse, output);
mask |= (1 << m) - 1;
}
if (_.modified('query') && !_.modified('fields')) {
mask |= this.update(_, pulse, output);
}
if (pulse.add.length) {
this.insert(_, pulse, output);
mask |= (1 << m) - 1;
}
if (pulse.mod.length) {
this.modify(pulse, output);
mask |= (1 << m) - 1;
}
this.value.mask = mask;
return output;
};
CrossFilter_prototype.insert = function(_, pulse, output) {
var tuples = pulse.add,
bits = this.value,
dims = this._dims,
indices = this._indices,
fields = _.fields,
adds = {},
out = output.add,
k = bits.size(),
n = k + tuples.length,
m = dims.length, j, key, add;
// resize bitmaps and add tuples as needed
bits.resize(n, m);
bits.add(tuples);
var curr = bits.curr(),
prev = bits.prev(),
all = bits.all();
// add to dimensional indices
for (j=0; j<m; ++j) {
key = fields[j].fname;
add = adds[key] || (adds[key] = indices[key].insert(fields[j], tuples, k));
dims[j].onAdd(add, curr);
}
// set previous filters, output if passes at least one filter
for (; k<n; ++k) {
prev[k] = all;
if (curr[k] !== all) out.push(k);
}
};
CrossFilter_prototype.modify = function(pulse, output) {
var out = output.mod,
bits = this.value,
curr = bits.curr(),
all = bits.all(),
tuples = pulse.mod,
i, n, k;
for (i=0, n=tuples.length; i<n; ++i) {
k = tuples[i]._index;
if (curr[k] !== all) out.push(k);
}
};
CrossFilter_prototype.remove = function(_, pulse, output) {
var indices = this._indices,
bits = this.value,
curr = bits.curr(),
prev = bits.prev(),
all = bits.all(),
map = {},
out = output.rem,
tuples = pulse.rem,
i, n, k, f;
// process tuples, output if passes at least one filter
for (i=0, n=tuples.length; i<n; ++i) {
k = tuples[i]._index;
map[k] = 1; // build index map
prev[k] = (f = curr[k]);
curr[k] = all;
if (f !== all) out.push(k);
}
// remove from dimensional indices
for (k in indices) {
indices[k].remove(n, map);
}
this.reindex(pulse, n, map);
return map;
};
// reindex filters and indices after propagation completes
CrossFilter_prototype.reindex = function(pulse, num, map) {
var indices = this._indices,
bits = this.value;
pulse.runAfter(function() {
var indexMap = bits.remove(num, map);
for (var key in indices) indices[key].reindex(indexMap);
});
};
CrossFilter_prototype.update = function(_, pulse, output) {
var dims = this._dims,
query = _.query,
stamp = pulse.stamp,
m = dims.length,
mask = 0, i, q;
// survey how many queries have changed
output.filters = 0;
for (q=0; q<m; ++q) {
if (_.modified('query', q)) { i = q; ++mask; }
}
if (mask === 1) {
// only one query changed, use more efficient update
mask = dims[i].one;
this.incrementOne(dims[i], query[i], output.add, output.rem);
} else {
// multiple queries changed, perform full record keeping
for (q=0, mask=0; q<m; ++q) {
if (!_.modified('query', q)) continue;
mask |= dims[q].one;
this.incrementAll(dims[q], query[q], stamp, output.add);
output.rem = output.add; // duplicate add/rem for downstream resolve
}
}
return mask;
};
CrossFilter_prototype.incrementAll = function(dim, query, stamp, out) {
var bits = this.value,
seen = bits.seen(),
curr = bits.curr(),
prev = bits.prev(),
index = dim.index(),
old = dim.bisect(dim.range),
range = dim.bisect(query),
lo1 = range[0],
hi1 = range[1],
lo0 = old[0],
hi0 = old[1],
one = dim.one,
i, j, k;
// Fast incremental update based on previous lo index.
if (lo1 < lo0) {
for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
k = index[i];
if (seen[k] !== stamp) {
prev[k] = curr[k];
seen[k] = stamp;
out.push(k);
}
curr[k] ^= one;
}
} else if (lo1 > lo0) {
for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
k = index[i];
if (seen[k] !== stamp) {
prev[k] = curr[k];
seen[k] = stamp;
out.push(k);
}
curr[k] ^= one;
}
}
// Fast incremental update based on previous hi index.
if (hi1 > hi0) {
for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
k = index[i];
if (seen[k] !== stamp) {
prev[k] = curr[k];
seen[k] = stamp;
out.push(k);
}
curr[k] ^= one;
}
} else if (hi1 < hi0) {
for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
k = index[i];
if (seen[k] !== stamp) {
prev[k] = curr[k];
seen[k] = stamp;
out.push(k);
}
curr[k] ^= one;
}
}
dim.range = query.slice();
};
CrossFilter_prototype.incrementOne = function(dim, query, add, rem) {
var bits = this.value,
curr = bits.curr(),
index = dim.index(),
old = dim.bisect(dim.range),
range = dim.bisect(query),
lo1 = range[0],
hi1 = range[1],
lo0 = old[0],
hi0 = old[1],
one = dim.one,
i, j, k;
// Fast incremental update based on previous lo index.
if (lo1 < lo0) {
for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
k = index[i];
curr[k] ^= one;
add.push(k);
}
} else if (lo1 > lo0) {
for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
k = index[i];
curr[k] ^= one;
rem.push(k);
}
}
// Fast incremental update based on previous hi index.
if (hi1 > hi0) {
for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
k = index[i];
curr[k] ^= one;
add.push(k);
}
} else if (hi1 < hi0) {
for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
k = index[i];
curr[k] ^= one;
rem.push(k);
}
}
dim.range = query.slice();
};
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/src/ResolveFilter.js
/**
* Selectively filters tuples by resolving against a filter bitmap.
* Useful for processing the output of a cross-filter transform.
* @constructor
* @param {object} params - The parameters for this operator.
* @param {object} params.ignore - A bit mask indicating which filters to ignore.
* @param {object} params.filter - The per-tuple filter bitmaps. Typically this
* parameter value is a reference to a {@link CrossFilter} transform.
*/
function ResolveFilter_ResolveFilter(params) {
Transform_Transform.call(this, null, params);
}
ResolveFilter_ResolveFilter.Definition = {
"type": "ResolveFilter",
"metadata": {},
"params": [
{ "name": "ignore", "type": "number", "required": true,
"description": "A bit mask indicating which filters to ignore." },
{ "name": "filter", "type": "object", "required": true,
"description": "Per-tuple filter bitmaps from a CrossFilter transform." }
]
};
var ResolveFilter_prototype = Object(vega_util["y" /* inherits */])(ResolveFilter_ResolveFilter, Transform_Transform);
ResolveFilter_prototype.transform = function(_, pulse) {
var ignore = ~(_.ignore || 0), // bit mask where zeros -> dims to ignore
bitmap = _.filter,
mask = bitmap.mask;
// exit early if no relevant filter changes
if ((mask & ignore) === 0) return pulse.StopPropagation;
var output = pulse.fork(pulse.ALL),
data = bitmap.data(),
curr = bitmap.curr(),
prev = bitmap.prev(),
pass = function(k) {
return !(curr[k] & ignore) ? data[k] : null;
};
// propagate all mod tuples that pass the filter
output.filter(output.MOD, pass);
// determine add & rem tuples via filter functions
// for efficiency, we do *not* populate new arrays,
// instead we add filter functions applied downstream
if (!(mask & (mask-1))) { // only one filter changed
output.filter(output.ADD, pass);
output.filter(output.REM, function(k) {
return (curr[k] & ignore) === mask ? data[k] : null;
});
} else { // multiple filters changed
output.filter(output.ADD, function(k) {
var c = curr[k] & ignore,
f = !c && (c ^ (prev[k] & ignore));
return f ? data[k] : null;
});
output.filter(output.REM, function(k) {
var c = curr[k] & ignore,
f = c && !(c ^ (c ^ (prev[k] & ignore)));
return f ? data[k] : null;
});
}
// add filter to source data in case of reflow...
return output.filter(output.SOURCE, function(t) { return pass(t._index); });
};
// CONCATENATED MODULE: ./node_modules/vega-crossfilter/index.js
// EXTERNAL MODULE: ./node_modules/vega/package.json
var vega_package = __webpack_require__(241);
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/bandSpace.js
/* harmony default export */ var src_scales_bandSpace = (function(count, paddingInner, paddingOuter) {
var space = count - paddingInner + paddingOuter * 2;
return count ? (space > 0 ? space : 1) : 0;
});
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/types.js
const scales_types_Identity = 'identity';
const src_scales_types_Linear = 'linear';
const scales_types_Log = 'log';
const scales_types_Pow = 'pow';
const scales_types_Sqrt = 'sqrt';
const scales_types_Symlog = 'symlog';
const scales_types_Time = 'time';
const scales_types_UTC = 'utc';
const scales_types_Sequential = 'sequential';
const scales_types_Diverging = 'diverging';
const src_scales_types_Quantile = 'quantile';
const scales_types_Quantize = 'quantize';
const scales_types_Threshold = 'threshold';
const scales_types_Ordinal = 'ordinal';
const scales_types_Point = 'point';
const scales_types_Band = 'band';
const scales_types_BinOrdinal = 'bin-ordinal';
function types_isValidScaleType(type) {
switch (type) {
case scales_types_Identity:
case src_scales_types_Linear:
case scales_types_Log:
case scales_types_Pow:
case scales_types_Sqrt:
case scales_types_Symlog:
case scales_types_Time:
case scales_types_UTC:
case scales_types_Sequential:
case src_scales_types_Quantile:
case scales_types_Quantize:
case scales_types_Threshold:
case scales_types_Ordinal:
case scales_types_Point:
case scales_types_Band:
case scales_types_BinOrdinal:
return true;
}
return false;
}
function types_isTemporal(key) {
return key === scales_types_Time || key === scales_types_UTC;
}
function types_isBinned(key) {
return key === scales_types_BinOrdinal;
}
function types_isQuantile(key) {
return key === src_scales_types_Quantile;
}
function isSequential(key) {
return key && key.startsWith(scales_types_Sequential);
}
function isDiverging(key) {
return key && key.startsWith(scales_types_Diverging);
}
function types_isInterpolating(key) {
return isSequential(key) || isDiverging(key);
}
function types_isLogarithmic(key) {
return key === scales_types_Log || key.endsWith('-log');
}
function types_isContinuous(key) {
switch (key) {
case src_scales_types_Linear:
case scales_types_Log:
case scales_types_Pow:
case scales_types_Sqrt:
case scales_types_Symlog:
case scales_types_Time:
case scales_types_UTC:
case scales_types_Sequential:
return true;
}
return false;
}
function types_isDiscrete(key) {
return key === scales_types_BinOrdinal
|| key === scales_types_Ordinal
|| key === scales_types_Band
|| key === scales_types_Point;
}
function types_isDiscretizing(key) {
return key === scales_types_BinOrdinal
|| key === src_scales_types_Quantile
|| key === scales_types_Quantize
|| key === scales_types_Threshold;
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/timeInterval.js
var timeInterval_time = {
millisecond: src_millisecond,
second: src_second,
minute: src_minute,
hour: src_hour,
day: src_day,
week: week_sunday,
month: src_month,
year: src_year
};
var timeInterval_utc = {
millisecond: src_millisecond,
second: src_second,
minute: src_utcMinute,
hour: src_utcHour,
day: src_utcDay,
week: utcWeek_utcSunday,
month: src_utcMonth,
year: src_utcYear
}
function timeInterval_timeInterval(unit, type) {
const t = (type === scales_types_UTC ? timeInterval_utc : timeInterval_time);
return Object(vega_util["v" /* hasOwnProperty */])(t, unit) && t[unit];
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/invertRange.js
/* harmony default export */ var src_scales_invertRange = (function(scale) {
return function(_) {
var lo = _[0],
hi = _[1],
t;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
return [
scale.invert(lo),
scale.invert(hi)
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/invertRangeExtent.js
/* harmony default export */ var src_scales_invertRangeExtent = (function(scale) {
return function(_) {
var range = scale.range(),
lo = _[0],
hi = _[1],
min = -1, max, t, i, n;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
for (i=0, n=range.length; i<n; ++i) {
if (range[i] >= lo && range[i] <= hi) {
if (min < 0) min = i;
max = i;
}
}
if (min < 0) return undefined;
lo = scale.invertExtent(range[min]);
hi = scale.invertExtent(range[max]);
return [
lo[0] === undefined ? lo[1] : lo[0],
hi[1] === undefined ? hi[0] : hi[1]
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/scaleBand.js
function src_scales_scaleBand_band() {
var scale = ordinal_ordinal().unknown(undefined),
domain = scale.domain,
ordinalRange = scale.range,
range = [0, 1],
step,
bandwidth,
round = false,
paddingInner = 0,
paddingOuter = 0,
align = 0.5;
delete scale.unknown;
function rescale() {
var n = domain().length,
reverse = range[1] < range[0],
start = range[reverse - 0],
stop = range[1 - reverse],
space = src_scales_bandSpace(n, paddingInner, paddingOuter);
step = (stop - start) / (space || 1);
if (round) {
step = Math.floor(step);
}
start += (stop - start - step * (n - paddingInner)) * align;
bandwidth = step * (1 - paddingInner);
if (round) {
start = Math.round(start);
bandwidth = Math.round(bandwidth);
}
var values = src_range(n).map(function(i) { return start + step * i; });
return ordinalRange(reverse ? values.reverse() : values);
}
scale.domain = function(_) {
if (arguments.length) {
domain(_);
return rescale();
} else {
return domain();
}
};
scale.range = function(_) {
if (arguments.length) {
range = [+_[0], +_[1]];
return rescale();
} else {
return range.slice();
}
};
scale.rangeRound = function(_) {
range = [+_[0], +_[1]];
round = true;
return rescale();
};
scale.bandwidth = function() {
return bandwidth;
};
scale.step = function() {
return step;
};
scale.round = function(_) {
if (arguments.length) {
round = !!_;
return rescale();
} else {
return round;
}
};
scale.padding = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
paddingInner = paddingOuter;
return rescale();
} else {
return paddingInner;
}
};
scale.paddingInner = function(_) {
if (arguments.length) {
paddingInner = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingInner;
}
};
scale.paddingOuter = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingOuter;
}
};
scale.align = function(_) {
if (arguments.length) {
align = Math.max(0, Math.min(1, _));
return rescale();
} else {
return align;
}
};
scale.invertRange = function(_) {
// bail if range has null or undefined values
if (_[0] == null || _[1] == null) return;
var lo = +_[0],
hi = +_[1],
reverse = range[1] < range[0],
values = reverse ? ordinalRange().reverse() : ordinalRange(),
n = values.length - 1, a, b, t;
// bail if either range endpoint is invalid
if (lo !== lo || hi !== hi) return;
// order range inputs, bail if outside of scale range
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
if (hi < values[0] || lo > range[1-reverse]) return;
// binary search to index into scale range
a = Math.max(0, bisect_bisectRight(values, lo) - 1);
b = lo===hi ? a : bisect_bisectRight(values, hi) - 1;
// increment index a if lo is within padding gap
if (lo - values[a] > bandwidth + 1e-10) ++a;
if (reverse) {
// map + swap
t = a;
a = n - b;
b = n - t;
}
return (a > b) ? undefined : domain().slice(a, b+1);
};
scale.invert = function(_) {
var value = scale.invertRange([_, _]);
return value ? value[0] : value;
};
scale.copy = function() {
return src_scales_scaleBand_band()
.domain(domain())
.range(range)
.round(round)
.paddingInner(paddingInner)
.paddingOuter(paddingOuter)
.align(align);
};
return rescale();
}
function src_scales_scaleBand_pointish(scale) {
var copy = scale.copy;
scale.padding = scale.paddingOuter;
delete scale.paddingInner;
scale.copy = function() {
return src_scales_scaleBand_pointish(copy());
};
return scale;
}
function src_scales_scaleBand_point() {
return src_scales_scaleBand_pointish(src_scales_scaleBand_band().paddingInner(1));
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/numbers.js
var src_scales_numbers_map = Array.prototype.map;
function src_scales_numbers_numbers(_) {
return src_scales_numbers_map.call(_, function(x) { return +x; });
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/slice.js
var scales_slice_slice = Array.prototype.slice;
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales/scaleBinOrdinal.js
function src_scales_scaleBinOrdinal_scaleBinOrdinal() {
var domain = [],
range = [];
function scale(x) {
return x == null || x !== x
? undefined
: range[(d3_array_src_bisect(domain, x) - 1) % range.length];
}
scale.domain = function(_) {
if (arguments.length) {
domain = src_scales_numbers_numbers(_);
return scale;
} else {
return domain.slice();
}
};
scale.range = function(_) {
if (arguments.length) {
range = scales_slice_slice.call(_);
return scale;
} else {
return range.slice();
}
};
scale.tickFormat = function(count, specifier) {
return src_tickFormat(domain[0], Object(vega_util["U" /* peek */])(domain), count == null ? 10 : count, specifier);
};
scale.copy = function() {
return src_scales_scaleBinOrdinal_scaleBinOrdinal().domain(scale.domain()).range(scale.range());
};
return scale;
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/scales.js
/**
* Augment scales with their type and needed inverse methods.
*/
function vega_scale_src_scales_create(type, constructor) {
return function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? src_scales_invertRange(s)
: s.invertExtent ? src_scales_invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
}
function vega_scale_src_scales_scale(type, scale) {
if (arguments.length > 1) {
vega_scale_src_scales_scales[type] = vega_scale_src_scales_create(type, scale);
return this;
} else {
return Object(vega_util["v" /* hasOwnProperty */])(vega_scale_src_scales_scales, type) ? vega_scale_src_scales_scales[type] : undefined;
}
}
var vega_scale_src_scales_scales = {
// identity scale
[scales_types_Identity]: identity_identity,
// continuous scales
[src_scales_types_Linear]: linear_linear,
[scales_types_Log]: log_log,
[scales_types_Pow]: pow_pow,
[scales_types_Sqrt]: pow_sqrt,
[scales_types_Symlog]: symlog_symlog,
[scales_types_Time]: src_time,
[scales_types_UTC]: utcTime,
// sequential scales
[scales_types_Sequential]: sequential_sequential, // backwards compat
[scales_types_Sequential+'-'+src_scales_types_Linear]: sequential_sequential,
[scales_types_Sequential+'-'+scales_types_Log]: sequential_sequentialLog,
[scales_types_Sequential+'-'+scales_types_Pow]: sequential_sequentialPow,
[scales_types_Sequential+'-'+scales_types_Sqrt]: sequential_sequentialSqrt,
[scales_types_Sequential+'-'+scales_types_Symlog]: sequential_sequentialSymlog,
// diverging scales
[scales_types_Diverging+'-'+src_scales_types_Linear]: diverging_diverging,
[scales_types_Diverging+'-'+scales_types_Log]: diverging_divergingLog,
[scales_types_Diverging+'-'+scales_types_Pow]: diverging_divergingPow,
[scales_types_Diverging+'-'+scales_types_Sqrt]: diverging_divergingSqrt,
[scales_types_Diverging+'-'+scales_types_Symlog]: diverging_divergingSymlog,
// discretizing scales
[src_scales_types_Quantile]: src_quantile_quantile,
[scales_types_Quantize]: quantize_quantize,
[scales_types_Threshold]: threshold_threshold,
// discrete scales
[scales_types_BinOrdinal]: src_scales_scaleBinOrdinal_scaleBinOrdinal,
[scales_types_Ordinal]: ordinal_ordinal,
[scales_types_Band]: src_scales_scaleBand_band,
[scales_types_Point]: src_scales_scaleBand_point
};
for (var scales_key in vega_scale_src_scales_scales) {
vega_scale_src_scales_scale(scales_key, vega_scale_src_scales_scales[scales_key]);
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/interpolate.js
const vega_scale_src_interpolate_scaleProps = ['clamp', 'base', 'constant', 'exponent'];
function vega_scale_src_interpolate_interpolateRange(interpolator, range) {
var start = range[0],
span = Object(vega_util["U" /* peek */])(range) - start;
return function(i) { return interpolator(start + i * span); };
}
function vega_scale_src_interpolate_interpolateColors(colors, type, gamma) {
return piecewise_piecewise(vega_scale_src_interpolate_interpolate(type || 'rgb', gamma), colors);
}
function vega_scale_src_interpolate_quantizeInterpolator(interpolator, count) {
var samples = new Array(count),
n = count + 1;
for (var i = 0; i < count;) samples[i] = interpolator(++i / n);
return samples;
}
function vega_scale_src_interpolate_scaleCopy(scale) {
const t = scale.type,
s = scale.copy();
s.type = t;
return s;
}
function vega_scale_src_interpolate_scaleFraction(scale, min, max) {
var delta = max - min, i, t, s;
if (!delta || !Number.isFinite(delta)) {
return Object(vega_util["l" /* constant */])(0.5);
} else {
i = (t = scale.type).indexOf('-');
t = i < 0 ? t : t.slice(i + 1);
s = vega_scale_src_scales_scale(t)().domain([min, max]).range([0, 1]);
vega_scale_src_interpolate_scaleProps.forEach(m => scale[m] ? s[m](scale[m]()) : 0);
return s;
}
}
function vega_scale_src_interpolate_interpolate(type, gamma) {
var interp = d3_interpolate_src_namespaceObject[vega_scale_src_interpolate_method(type)];
return (gamma != null && interp && interp.gamma)
? interp.gamma(gamma)
: interp;
}
function vega_scale_src_interpolate_method(type) {
return 'interpolate' + type.toLowerCase()
.split('-')
.map(function(s) { return s[0].toUpperCase() + s.slice(1); })
.join('');
}
// CONCATENATED MODULE: ./node_modules/vega-scale/src/palettes.js
const vega_scale_src_palettes_continuous = {
blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',
greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',
greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',
oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',
purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',
reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',
blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',
bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',
greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',
orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',
purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',
purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',
purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',
redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',
yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',
yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',
yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',
blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',
brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',
purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',
purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',
redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',
redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',
yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',
redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',
redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',
pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',
spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',
viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',
magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',
inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',
plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',
rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',
sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',
browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',
tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',
teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',
warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',
goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',
goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',
goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',
lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',
lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',
lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',
lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',
lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',
darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',
darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',
darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',
darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',
darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'
};
const vega_scale_src_palettes_discrete = {
category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',
category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',
category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',
category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',
tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',
tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',
accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',
dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',
paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',
pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',
pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',
set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',
set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',
set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f'
};
// CONCATENATED MODULE: ./node_modules/vega-scale/src/schemes.js
function vega_scale_src_schemes_colors(palette) {
var n = palette.length / 6 | 0, c = new Array(n), i = 0;
while (i < n) c[i] = '#' + palette.slice(i * 6, ++i * 6);
return c;
}
function vega_scale_src_schemes_apply(_, f) {
for (let k in _) vega_scale_src_schemes_scheme(k, f(_[k]));
}
const vega_scale_src_schemes_schemes = {};
vega_scale_src_schemes_apply(vega_scale_src_palettes_discrete, vega_scale_src_schemes_colors);
vega_scale_src_schemes_apply(vega_scale_src_palettes_continuous, _ => vega_scale_src_interpolate_interpolateColors(vega_scale_src_schemes_colors(_)));
function vega_scale_src_schemes_scheme(name, scheme) {
name = name && name.toLowerCase();
if (arguments.length > 1) {
vega_scale_src_schemes_schemes[name] = scheme;
return this;
} else {
return vega_scale_src_schemes_schemes[name];
}
}
// CONCATENATED MODULE: ./node_modules/vega-scale/index.js
// CONCATENATED MODULE: ./node_modules/vega-view/src/aria.js
// initialize aria role and label attributes
function initializeAria(view) {
const el = view.container();
if (el) {
el.setAttribute('role', 'figure');
ariaLabel(el, view.description());
}
}
// update aria-label if we have a DOM container element
function ariaLabel(el, desc) {
if (el) desc == null
? el.removeAttribute('aria-label')
: el.setAttribute('aria-label', desc);
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/background.js
/* harmony default export */ var src_background = (function(view) {
// respond to background signal
view.add(null, _ => {
view._background = _.bg;
view._resize = 1;
return _.bg;
}, { bg: view._signals.background });
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/cursor.js
var cursor_Default = 'default';
/* harmony default export */ var src_cursor = (function(view) {
var cursor = view._signals.cursor;
// add cursor signal to dataflow, if needed
if (!cursor) {
view._signals.cursor = (cursor = view.add({user: cursor_Default, item: null}));
}
// evaluate cursor on each mousemove event
view.on(view.events('view', 'mousemove'), cursor,
function(_, event) {
var value = cursor.value,
user = value ? (Object(vega_util["H" /* isString */])(value) ? value : value.user) : cursor_Default,
item = event.item && event.item.cursor || null;
return (value && user === value.user && item == value.item) ? value
: {user: user, item: item};
}
);
// when cursor signal updates, set visible cursor
view.add(null, function(_) {
var user = _.cursor,
item = this.value;
if (!Object(vega_util["H" /* isString */])(user)) {
item = user.item;
user = user.user;
}
cursor_setCursor(user && user !== cursor_Default ? user : (item || user));
return item;
}, {cursor: cursor});
});
function cursor_setCursor(cursor) {
// set cursor on document body
// this ensures cursor applies even if dragging out of view
if (typeof document !== 'undefined' && document.body) {
document.body.style.cursor = cursor;
}
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/data.js
function data_dataref(view, name) {
var data = view._runtime.data;
if (!Object(vega_util["v" /* hasOwnProperty */])(data, name)) {
Object(vega_util["n" /* error */])('Unrecognized data set: ' + name);
}
return data[name];
}
function data_data(name, values) {
return arguments.length < 2
? data_dataref(this, name).values.value
: data_change.call(this, name, ChangeSet_changeset().remove(vega_util["Ga" /* truthy */]).insert(values));
}
function data_change(name, changes) {
if (!ChangeSet_isChangeSet(changes)) {
Object(vega_util["n" /* error */])('Second argument to changes must be a changeset.');
}
var dataset = data_dataref(this, name);
dataset.modified = true;
return this.pulse(dataset.input, changes);
}
function data_insert(name, _) {
return data_change.call(this, name, ChangeSet_changeset().insert(_));
}
function data_remove(name, _) {
return data_change.call(this, name, ChangeSet_changeset().remove(_));
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/render-size.js
function render_size_width(view) {
var padding = view.padding();
return Math.max(0, view._viewWidth + padding.left + padding.right);
}
function render_size_height(view) {
var padding = view.padding();
return Math.max(0, view._viewHeight + padding.top + padding.bottom);
}
function render_size_offset(view) {
var padding = view.padding(),
origin = view._origin;
return [
padding.left + origin[0],
padding.top + origin[1]
];
}
function resizeRenderer(view) {
var origin = render_size_offset(view),
w = render_size_width(view),
h = render_size_height(view);
view._renderer.background(view.background());
view._renderer.resize(w, h, origin);
view._handler.origin(origin);
view._resizeListeners.forEach(function(handler) {
try {
handler(w, h);
} catch (error) {
view.error(error);
}
});
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/events-extend.js
/**
* Extend an event with additional view-specific methods.
* Adds a new property ('vega') to an event that provides a number
* of methods for querying information about the current interaction.
* The vega object provides the following methods:
* view - Returns the backing View instance.
* item - Returns the currently active scenegraph item (if any).
* group - Returns the currently active scenegraph group (if any).
* This method accepts a single string-typed argument indicating the name
* of the desired parent group. The scenegraph will be traversed from
* the item up towards the root to search for a matching group. If no
* argument is provided the enclosing group for the active item is
* returned, unless the item it itself a group, in which case it is
* returned directly.
* xy - Returns a two-element array containing the x and y coordinates for
* mouse or touch events. For touch events, this is based on the first
* elements in the changedTouches array. This method accepts a single
* argument: either an item instance or mark name that should serve as
* the reference coordinate system. If no argument is provided the
* top-level view coordinate system is assumed.
* x - Returns the current x-coordinate, accepts the same arguments as xy.
* y - Returns the current y-coordinate, accepts the same arguments as xy.
* @param {Event} event - The input event to extend.
* @param {Item} item - The currently active scenegraph item (if any).
* @return {Event} - The extended input event.
*/
/* harmony default export */ var events_extend = (function(view, event, item) {
var r = view._renderer,
el = r && r.canvas(),
p, e, translate;
if (el) {
translate = render_size_offset(view);
e = event.changedTouches ? event.changedTouches[0] : event;
p = util_point(e, el);
p[0] -= translate[0];
p[1] -= translate[1];
}
event.dataflow = view;
event.item = item;
event.vega = events_extend_extension(view, item, p);
return event;
});
function events_extend_extension(view, item, point) {
var itemGroup = item
? item.mark.marktype === 'group' ? item : item.mark.group
: null;
function group(name) {
var g = itemGroup, i;
if (name) for (i = item; i; i = i.mark.group) {
if (i.mark.name === name) { g = i; break; }
}
return g && g.mark && g.mark.interactive ? g : {};
}
function xy(item) {
if (!item) return point;
if (Object(vega_util["H" /* isString */])(item)) item = group(item);
var p = point.slice();
while (item) {
p[0] -= item.x || 0;
p[1] -= item.y || 0;
item = item.mark && item.mark.group;
}
return p;
}
return {
view: Object(vega_util["l" /* constant */])(view),
item: Object(vega_util["l" /* constant */])(item || {}),
group: group,
xy: xy,
x: function(item) { return xy(item)[0]; },
y: function(item) { return xy(item)[1]; }
};
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/events.js
const events_VIEW = 'view',
events_TIMER = 'timer',
events_WINDOW = 'window',
events_NO_TRAP = {trap: false};
/**
* Initialize event handling configuration.
* @param {object} config - The configuration settings.
* @return {object}
*/
function events_initializeEventConfig(config) {
const events = Object(vega_util["o" /* extend */])({defaults: {}}, config);
const unpack = (obj, keys) => {
keys.forEach(k => {
if (Object(vega_util["A" /* isArray */])(obj[k])) obj[k] = Object(vega_util["Da" /* toSet */])(obj[k]);
});
};
unpack(events.defaults, ['prevent', 'allow']);
unpack(events, ['view', 'window', 'selector']);
return events;
}
function events_prevent(view, type) {
var def = view._eventConfig.defaults,
prevent = def.prevent,
allow = def.allow;
return prevent === false || allow === true ? false
: prevent === true || allow === false ? true
: prevent ? prevent[type]
: allow ? !allow[type]
: view.preventDefault();
}
function events_permit(view, key, type) {
const rule = view._eventConfig && view._eventConfig[key];
if (rule === false || (Object(vega_util["F" /* isObject */])(rule) && !rule[type])) {
view.warn(`Blocked ${key} ${type} event listener.`);
return false;
}
return true;
}
/**
* Create a new event stream from an event source.
* @param {object} source - The event source to monitor.
* @param {string} type - The event type.
* @param {function(object): boolean} [filter] - Event filter function.
* @return {EventStream}
*/
function events_events(source, type, filter) {
var view = this,
s = new EventStream_EventStream(filter),
send = function(e, item) {
view.runAsync(null, () => {
if (source === events_VIEW && events_prevent(view, type)) {
e.preventDefault();
}
s.receive(events_extend(view, e, item));
});
},
sources;
if (source === events_TIMER) {
if (events_permit(view, 'timer', type)) {
view.timer(send, type);
}
}
else if (source === events_VIEW) {
if (events_permit(view, 'view', type)) {
// send traps errors, so use {trap: false} option
view.addEventListener(type, send, events_NO_TRAP);
}
}
else {
if (source === events_WINDOW) {
if (events_permit(view, 'window', type) && typeof window !== 'undefined') {
sources = [window];
}
} else if (typeof document !== 'undefined') {
if (events_permit(view, 'selector', type)) {
sources = document.querySelectorAll(source);
}
}
if (!sources) {
view.warn('Can not resolve event source: ' + source);
} else {
for (var i=0, n=sources.length; i<n; ++i) {
sources[i].addEventListener(type, send);
}
view._eventListeners.push({
type: type,
sources: sources,
handler: send
});
}
}
return s;
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/hover.js
function itemFilter(event) {
return event.item;
}
function markTarget(event) {
// grab upstream collector feeding the mark operator
return event.item.mark.source;
}
function invoke(name) {
return function(_, event) {
return event.vega.view()
.changeset()
.encode(event.item, name);
};
}
/* harmony default export */ var src_hover = (function(hoverSet, leaveSet) {
hoverSet = [hoverSet || 'hover'];
leaveSet = [leaveSet || 'update', hoverSet[0]];
// invoke hover set upon mouseover
this.on(
this.events('view', 'mouseover', itemFilter),
markTarget,
invoke(hoverSet)
);
// invoke leave set upon mouseout
this.on(
this.events('view', 'mouseout', itemFilter),
markTarget,
invoke(leaveSet)
);
return this;
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/finalize.js
/**
* Finalize a View instance that is being removed.
* Cancel any running timers.
* Remove all external event listeners.
* Remove any currently displayed tooltip.
*/
/* harmony default export */ var finalize = (function() {
var tooltip = this._tooltip,
timers = this._timers,
listeners = this._eventListeners,
n, m, e;
n = timers.length;
while (--n >= 0) {
timers[n].stop();
}
n = listeners.length;
while (--n >= 0) {
e = listeners[n];
m = e.sources.length;
while (--m >= 0) {
e.sources[m].removeEventListener(e.type, e.handler);
}
}
if (tooltip) {
tooltip.call(this, this._handler, null, null, null);
}
return this;
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/element.js
/* harmony default export */ var src_element = (function(tag, attr, text) {
var el = document.createElement(tag);
for (var key in attr) el.setAttribute(key, attr[key]);
if (text != null) el.textContent = text;
return el;
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/bind.js
var bind_BindClass = 'vega-bind',
bind_NameClass = 'vega-bind-name',
bind_RadioClass = 'vega-bind-radio',
bind_OptionClass = 'vega-option-';
/**
* Bind a signal to an external HTML input element. The resulting two-way
* binding will propagate input changes to signals, and propagate signal
* changes to the input element state. If this view instance has no parent
* element, we assume the view is headless and no bindings are created.
* @param {Element|string} el - The parent DOM element to which the input
* element should be appended as a child. If string-valued, this argument
* will be treated as a CSS selector. If null or undefined, the parent
* element of this view will be used as the element.
* @param {object} param - The binding parameters which specify the signal
* to bind to, the input element type, and type-specific configuration.
* @return {View} - This view instance.
*/
/* harmony default export */ var src_bind = (function(view, el, binding) {
if (!el) return;
var param = binding.param,
bind = binding.state;
if (!bind) {
bind = binding.state = {
elements: null,
active: false,
set: null,
update: function(value) {
if (value !== view.signal(param.signal)) {
view.runAsync(null, function() {
bind.source = true;
view.signal(param.signal, value);
});
}
}
};
if (param.debounce) {
bind.update = Object(vega_util["m" /* debounce */])(param.debounce, bind.update);
}
}
bind_generate(bind, el, param, view.signal(param.signal));
if (!bind.active) {
view.on(view._signals[param.signal], null, function() {
bind.source
? (bind.source = false)
: bind.set(view.signal(param.signal));
});
bind.active = true;
}
return bind;
});
/**
* Generate an HTML input form element and bind it to a signal.
*/
function bind_generate(bind, el, param, value) {
var div = src_element('div', {'class': bind_BindClass});
div.appendChild(src_element('span',
{'class': bind_NameClass},
(param.name || param.signal)
));
el.appendChild(div);
var input = bind_form;
switch (param.input) {
case 'checkbox': input = bind_checkbox; break;
case 'select': input = bind_select; break;
case 'radio': input = bind_radio; break;
case 'range': input = bind_range; break;
}
input(bind, div, param, value);
}
/**
* Generates an arbitrary input form element.
* The input type is controlled via user-provided parameters.
*/
function bind_form(bind, el, param, value) {
var node = src_element('input');
for (var key in param) {
if (key !== 'signal' && key !== 'element') {
node.setAttribute(key === 'input' ? 'type' : key, param[key]);
}
}
node.setAttribute('name', param.signal);
node.value = value;
el.appendChild(node);
node.addEventListener('input', function() {
bind.update(node.value);
});
bind.elements = [node];
bind.set = function(value) { node.value = value; };
}
/**
* Generates a checkbox input element.
*/
function bind_checkbox(bind, el, param, value) {
var attr = {type: 'checkbox', name: param.signal};
if (value) attr.checked = true;
var node = src_element('input', attr);
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(node.checked);
});
bind.elements = [node];
bind.set = function(value) { node.checked = !!value || null; }
}
/**
* Generates a selection list input element.
*/
function bind_select(bind, el, param, value) {
var node = src_element('select', {name: param.signal}),
label = param.labels || [];
param.options.forEach(function(option, i) {
var attr = {value: option};
if (bind_valuesEqual(option, value)) attr.selected = true;
node.appendChild(src_element('option', attr, (label[i] || option)+''));
});
el.appendChild(node);
node.addEventListener('change', function() {
bind.update(param.options[node.selectedIndex]);
});
bind.elements = [node];
bind.set = function(value) {
for (var i=0, n=param.options.length; i<n; ++i) {
if (bind_valuesEqual(param.options[i], value)) {
node.selectedIndex = i; return;
}
}
};
}
/**
* Generates a radio button group.
*/
function bind_radio(bind, el, param, value) {
var group = src_element('span', {'class': bind_RadioClass}),
label = param.labels || [];
el.appendChild(group);
bind.elements = param.options.map(function(option, i) {
var id = bind_OptionClass + param.signal + '-' + option;
var attr = {
id: id,
type: 'radio',
name: param.signal,
value: option
};
if (bind_valuesEqual(option, value)) attr.checked = true;
var input = src_element('input', attr);
input.addEventListener('change', function() {
bind.update(option);
});
group.appendChild(input);
group.appendChild(src_element('label', {'for': id}, (label[i] || option)+''));
return input;
});
bind.set = function(value) {
var nodes = bind.elements,
i = 0,
n = nodes.length;
for (; i<n; ++i) {
if (bind_valuesEqual(nodes[i].value, value)) nodes[i].checked = true;
}
};
}
/**
* Generates a slider input element.
*/
function bind_range(bind, el, param, value) {
value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2;
var max = param.max != null ? param.max : Math.max(100, +value) || 100,
min = param.min || Math.min(0, max, +value) || 0,
step = param.step || tickStep(min, max, 100);
var node = src_element('input', {
type: 'range',
name: param.signal,
min: min,
max: max,
step: step
});
node.value = value;
var label = src_element('label', {}, +value);
el.appendChild(node);
el.appendChild(label);
function update() {
label.textContent = node.value;
bind.update(+node.value);
}
// subscribe to both input and change
node.addEventListener('input', update);
node.addEventListener('change', update);
bind.elements = [node];
bind.set = function(value) {
node.value = value;
label.textContent = value;
};
}
function bind_valuesEqual(a, b) {
return a === b || (a+'' === b+'');
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/initialize-renderer.js
/* harmony default export */ var initialize_renderer = (function(view, r, el, constructor, scaleFactor, opt) {
r = r || new constructor(view.loader());
return r
.initialize(el, render_size_width(view), render_size_height(view), render_size_offset(view), scaleFactor, opt)
.background(view.background());
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/trap.js
/* harmony default export */ var trap = (function(view, fn) {
return !fn ? null : function() {
try {
fn.apply(this, arguments);
} catch (error) {
view.error(error);
}
};
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/initialize-handler.js
/* harmony default export */ var initialize_handler = (function(view, prevHandler, el, constructor) {
// instantiate scenegraph handler
var handler = new constructor(view.loader(), trap(view, view.tooltip()))
.scene(view.scenegraph().root)
.initialize(el, render_size_offset(view), view);
// transfer event handlers
if (prevHandler) {
prevHandler.handlers().forEach(function(h) {
handler.on(h.type, h.handler);
});
}
return handler;
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/initialize.js
/* harmony default export */ var src_initialize = (function(el, elBind) {
const view = this,
type = view._renderType,
config = view._eventConfig.bind,
module = modules_renderModule(type);
// containing dom element
el = view._el = el ? initialize_lookup(view, el) : null;
// initialize aria attributes
initializeAria(view);
// select appropriate renderer & handler
if (!module) view.error('Unrecognized renderer type: ' + type);
const Handler = module.handler || CanvasHandler_CanvasHandler,
Renderer = (el ? module.renderer : module.headless);
// initialize renderer and input handler
view._renderer = !Renderer ? null
: initialize_renderer(view, view._renderer, el, Renderer);
view._handler = initialize_handler(view, view._handler, el, Handler);
view._redraw = true;
// initialize signal bindings
if (el && config !== 'none') {
elBind = elBind ? (view._elBind = initialize_lookup(view, elBind))
: el.appendChild(src_element('div', {'class': 'vega-bindings'}));
view._bind.forEach(function(_) {
if (_.param.element && config !== 'container') {
_.element = initialize_lookup(view, _.param.element);
}
});
view._bind.forEach(function(_) {
src_bind(view, _.element || elBind, _);
});
}
return view;
});
function initialize_lookup(view, el) {
if (typeof el === 'string') {
if (typeof document !== 'undefined') {
el = document.querySelector(el);
if (!el) {
view.error('Signal bind element not found: ' + el);
return null;
}
} else {
view.error('DOM document instance not found.');
return null;
}
}
if (el) {
try {
el.innerHTML = '';
} catch (e) {
el = null;
view.error(e);
}
}
return el;
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/padding.js
const padding_number = _ => +_ || 0;
const padding_paddingObject = _ => ({top: _, bottom: _, left: _, right: _});
/* harmony default export */ var src_padding = (function(_) {
return Object(vega_util["F" /* isObject */])(_)
? {
top: padding_number(_.top),
bottom: padding_number(_.bottom),
left: padding_number(_.left),
right: padding_number(_.right)
}
: padding_paddingObject(padding_number(_));
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/render-headless.js
/**
* Render the current scene in a headless fashion.
* This method is asynchronous, returning a Promise instance.
* @return {Promise} - A Promise that resolves to a renderer.
*/
/* harmony default export */ var render_headless = (async function(view, type, scaleFactor, opt) {
const module = modules_renderModule(type),
ctr = module && module.headless;
if (!ctr) Object(vega_util["n" /* error */])('Unrecognized renderer type: ' + type);
await view.runAsync();
return initialize_renderer(view, null, null, ctr, scaleFactor, opt)
.renderAsync(view._scenegraph.root);
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/render-to-image-url.js
/**
* Produce an image URL for the visualization. Depending on the type
* parameter, the generated URL contains data for either a PNG or SVG image.
* The URL can be used (for example) to download images of the visualization.
* This method is asynchronous, returning a Promise instance.
* @param {string} type - The image type. One of 'svg', 'png' or 'canvas'.
* The 'canvas' and 'png' types are synonyms for a PNG image.
* @return {Promise} - A promise that resolves to an image URL.
*/
/* harmony default export */ var render_to_image_url = (async function(type, scaleFactor) {
if (type !== modules_RenderType.Canvas && type !== modules_RenderType.SVG && type !== modules_RenderType.PNG) {
Object(vega_util["n" /* error */])('Unrecognized image type: ' + type);
}
const r = await render_headless(this, type, scaleFactor);
return type === modules_RenderType.SVG
? render_to_image_url_toBlobURL(r.svg(), 'image/svg+xml')
: r.canvas().toDataURL('image/png');
});
function render_to_image_url_toBlobURL(data, mime) {
var blob = new Blob([data], {type: mime});
return window.URL.createObjectURL(blob);
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/render-to-canvas.js
/**
* Produce a Canvas instance containing a rendered visualization.
* This method is asynchronous, returning a Promise instance.
* @return {Promise} - A promise that resolves to a Canvas instance.
*/
/* harmony default export */ var render_to_canvas = (async function(scaleFactor, opt) {
const r = await render_headless(this, modules_RenderType.Canvas, scaleFactor, opt);
return r.canvas();
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/render-to-svg.js
/**
* Produce a rendered SVG string of the visualization.
* This method is asynchronous, returning a Promise instance.
* @return {Promise} - A promise that resolves to an SVG string.
*/
/* harmony default export */ var render_to_svg = (async function(scaleFactor) {
const r = await render_headless(this, modules_RenderType.SVG, scaleFactor);
return r.svg();
});
// CONCATENATED MODULE: ./node_modules/vega-expression/src/ast.js
var RawCode = 'RawCode';
var Literal = 'Literal';
var Property = 'Property';
var ast_Identifier = 'Identifier';
var ArrayExpression = 'ArrayExpression';
var BinaryExpression = 'BinaryExpression';
var CallExpression = 'CallExpression';
var ConditionalExpression = 'ConditionalExpression';
var LogicalExpression = 'LogicalExpression';
var MemberExpression = 'MemberExpression';
var ObjectExpression = 'ObjectExpression';
var UnaryExpression = 'UnaryExpression';
function ASTNode(type) {
this.type = type;
}
ASTNode.prototype.visit = function(visitor) {
var node = this, c, i, n;
if (visitor(node)) return 1;
for (c=ast_children(node), i=0, n=c.length; i<n; ++i) {
if (c[i].visit(visitor)) return 1;
}
};
function ast_children(node) {
switch (node.type) {
case ArrayExpression:
return node.elements;
case BinaryExpression:
case LogicalExpression:
return [node.left, node.right];
case CallExpression:
var args = node.arguments.slice();
args.unshift(node.callee);
return args;
case ConditionalExpression:
return [node.test, node.consequent, node.alternate];
case MemberExpression:
return [node.object, node.property];
case ObjectExpression:
return node.properties;
case Property:
return [node.key, node.value];
case UnaryExpression:
return [node.argument];
case ast_Identifier:
case Literal:
case RawCode:
default:
return [];
}
}
// CONCATENATED MODULE: ./node_modules/vega-expression/src/parser.js
/*
The following expression parser is based on Esprima (http://esprima.org/).
Original header comment and license for Esprima is included here:
Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var parser_TokenName,
parser_source,
parser_index,
parser_length,
parser_lookahead;
var parser_TokenBooleanLiteral = 1,
parser_TokenEOF = 2,
parser_TokenIdentifier = 3,
parser_TokenKeyword = 4,
parser_TokenNullLiteral = 5,
parser_TokenNumericLiteral = 6,
parser_TokenPunctuator = 7,
parser_TokenStringLiteral = 8,
parser_TokenRegularExpression = 9;
parser_TokenName = {};
parser_TokenName[parser_TokenBooleanLiteral] = 'Boolean';
parser_TokenName[parser_TokenEOF] = '<end>';
parser_TokenName[parser_TokenIdentifier] = 'Identifier';
parser_TokenName[parser_TokenKeyword] = 'Keyword';
parser_TokenName[parser_TokenNullLiteral] = 'Null';
parser_TokenName[parser_TokenNumericLiteral] = 'Numeric';
parser_TokenName[parser_TokenPunctuator] = 'Punctuator';
parser_TokenName[parser_TokenStringLiteral] = 'String';
parser_TokenName[parser_TokenRegularExpression] = 'RegularExpression';
var parser_SyntaxArrayExpression = 'ArrayExpression',
parser_SyntaxBinaryExpression = 'BinaryExpression',
parser_SyntaxCallExpression = 'CallExpression',
parser_SyntaxConditionalExpression = 'ConditionalExpression',
parser_SyntaxIdentifier = 'Identifier',
parser_SyntaxLiteral = 'Literal',
parser_SyntaxLogicalExpression = 'LogicalExpression',
parser_SyntaxMemberExpression = 'MemberExpression',
parser_SyntaxObjectExpression = 'ObjectExpression',
parser_SyntaxProperty = 'Property',
parser_SyntaxUnaryExpression = 'UnaryExpression';
// Error messages should be identical to V8.
var parser_MessageUnexpectedToken = 'Unexpected token %0',
parser_MessageUnexpectedNumber = 'Unexpected number',
parser_MessageUnexpectedString = 'Unexpected string',
parser_MessageUnexpectedIdentifier = 'Unexpected identifier',
parser_MessageUnexpectedReserved = 'Unexpected reserved word',
parser_MessageUnexpectedEOS = 'Unexpected end of input',
parser_MessageInvalidRegExp = 'Invalid regular expression',
parser_MessageUnterminatedRegExp = 'Invalid regular expression: missing /',
parser_MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.',
parser_MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode';
var parser_ILLEGAL = 'ILLEGAL',
parser_DISABLED = 'Disabled.';
// See also tools/generate-unicode-regex.py.
var parser_RegexNonAsciiIdentifierStart = new RegExp("[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
// eslint-disable-next-line no-misleading-character-class
parser_RegexNonAsciiIdentifierPart = new RegExp("[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]");
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function parser_assert(condition, message) {
/* istanbul ignore next */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function parser_isDecimalDigit(ch) {
return (ch >= 0x30 && ch <= 0x39); // 0..9
}
function parser_isHexDigit(ch) {
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
}
function parser_isOctalDigit(ch) {
return '01234567'.indexOf(ch) >= 0;
}
// 7.2 White Space
function parser_isWhiteSpace(ch) {
return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
(ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
}
// 7.3 Line Terminators
function parser_isLineTerminator(ch) {
return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function parser_isIdentifierStart(ch) {
return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
(ch >= 0x41 && ch <= 0x5A) || // A..Z
(ch >= 0x61 && ch <= 0x7A) || // a..z
(ch === 0x5C) || // \ (backslash)
((ch >= 0x80) && parser_RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function parser_isIdentifierPart(ch) {
return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore)
(ch >= 0x41 && ch <= 0x5A) || // A..Z
(ch >= 0x61 && ch <= 0x7A) || // a..z
(ch >= 0x30 && ch <= 0x39) || // 0..9
(ch === 0x5C) || // \ (backslash)
((ch >= 0x80) && parser_RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch)));
}
// 7.6.1.1 Keywords
var parser_keywords = {
'if':1, 'in':1, 'do':1,
'var':1, 'for':1, 'new':1, 'try':1, 'let':1,
'this':1, 'else':1, 'case':1, 'void':1, 'with':1, 'enum':1,
'while':1, 'break':1, 'catch':1, 'throw':1, 'const':1, 'yield':1, 'class':1, 'super':1,
'return':1, 'typeof':1, 'delete':1, 'switch':1, 'export':1, 'import':1, 'public':1, 'static':1,
'default':1, 'finally':1, 'extends':1, 'package':1, 'private':1,
'function':1, 'continue':1, 'debugger':1,
'interface':1, 'protected':1,
'instanceof':1, 'implements':1
};
function parser_skipComment() {
var ch;
while (parser_index < parser_length) {
ch = parser_source.charCodeAt(parser_index);
if (parser_isWhiteSpace(ch) || parser_isLineTerminator(ch)) {
++parser_index;
} else {
break;
}
}
}
function parser_scanHexEscape(prefix) {
var i, len, ch, code = 0;
len = (prefix === 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (parser_index < parser_length && parser_isHexDigit(parser_source[parser_index])) {
ch = parser_source[parser_index++];
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
} else {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
}
return String.fromCharCode(code);
}
function parser_scanUnicodeCodePointEscape() {
var ch, code, cu1, cu2;
ch = parser_source[parser_index];
code = 0;
// At least, one hex digit is required.
if (ch === '}') {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
while (parser_index < parser_length) {
ch = parser_source[parser_index++];
if (!parser_isHexDigit(ch)) {
break;
}
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
}
if (code > 0x10FFFF || ch !== '}') {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
// UTF-16 Encoding
if (code <= 0xFFFF) {
return String.fromCharCode(code);
}
cu1 = ((code - 0x10000) >> 10) + 0xD800;
cu2 = ((code - 0x10000) & 1023) + 0xDC00;
return String.fromCharCode(cu1, cu2);
}
function parser_getEscapedIdentifier() {
var ch, id;
ch = parser_source.charCodeAt(parser_index++);
id = String.fromCharCode(ch);
// '\u' (U+005C, U+0075) denotes an escaped character.
if (ch === 0x5C) {
if (parser_source.charCodeAt(parser_index) !== 0x75) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
++parser_index;
ch = parser_scanHexEscape('u');
if (!ch || ch === '\\' || !parser_isIdentifierStart(ch.charCodeAt(0))) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
id = ch;
}
while (parser_index < parser_length) {
ch = parser_source.charCodeAt(parser_index);
if (!parser_isIdentifierPart(ch)) {
break;
}
++parser_index;
id += String.fromCharCode(ch);
// '\u' (U+005C, U+0075) denotes an escaped character.
if (ch === 0x5C) {
id = id.substr(0, id.length - 1);
if (parser_source.charCodeAt(parser_index) !== 0x75) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
++parser_index;
ch = parser_scanHexEscape('u');
if (!ch || ch === '\\' || !parser_isIdentifierPart(ch.charCodeAt(0))) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
id += ch;
}
}
return id;
}
function parser_getIdentifier() {
var start, ch;
start = parser_index++;
while (parser_index < parser_length) {
ch = parser_source.charCodeAt(parser_index);
if (ch === 0x5C) {
// Blackslash (U+005C) marks Unicode escape sequence.
parser_index = start;
return parser_getEscapedIdentifier();
}
if (parser_isIdentifierPart(ch)) {
++parser_index;
} else {
break;
}
}
return parser_source.slice(start, parser_index);
}
function parser_scanIdentifier() {
var start, id, type;
start = parser_index;
// Backslash (U+005C) starts an escaped character.
id = (parser_source.charCodeAt(parser_index) === 0x5C) ? parser_getEscapedIdentifier() : parser_getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = parser_TokenIdentifier;
} else if (parser_keywords.hasOwnProperty(id)) { // eslint-disable-line no-prototype-builtins
type = parser_TokenKeyword;
} else if (id === 'null') {
type = parser_TokenNullLiteral;
} else if (id === 'true' || id === 'false') {
type = parser_TokenBooleanLiteral;
} else {
type = parser_TokenIdentifier;
}
return {
type: type,
value: id,
start: start,
end: parser_index
};
}
// 7.7 Punctuators
function parser_scanPunctuator() {
var start = parser_index,
code = parser_source.charCodeAt(parser_index),
code2,
ch1 = parser_source[parser_index],
ch2,
ch3,
ch4;
switch (code) {
// Check for most common single-character punctuators.
case 0x2E: // . dot
case 0x28: // ( open bracket
case 0x29: // ) close bracket
case 0x3B: // ; semicolon
case 0x2C: // , comma
case 0x7B: // { open curly brace
case 0x7D: // } close curly brace
case 0x5B: // [
case 0x5D: // ]
case 0x3A: // :
case 0x3F: // ?
case 0x7E: // ~
++parser_index;
return {
type: parser_TokenPunctuator,
value: String.fromCharCode(code),
start: start,
end: parser_index
};
default:
code2 = parser_source.charCodeAt(parser_index + 1);
// '=' (U+003D) marks an assignment or comparison operator.
if (code2 === 0x3D) {
switch (code) {
case 0x2B: // +
case 0x2D: // -
case 0x2F: // /
case 0x3C: // <
case 0x3E: // >
case 0x5E: // ^
case 0x7C: // |
case 0x25: // %
case 0x26: // &
case 0x2A: // *
parser_index += 2;
return {
type: parser_TokenPunctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
start: start,
end: parser_index
};
case 0x21: // !
case 0x3D: // =
parser_index += 2;
// !== and ===
if (parser_source.charCodeAt(parser_index) === 0x3D) {
++parser_index;
}
return {
type: parser_TokenPunctuator,
value: parser_source.slice(start, parser_index),
start: start,
end: parser_index
};
}
}
}
// 4-character punctuator: >>>=
ch4 = parser_source.substr(parser_index, 4);
if (ch4 === '>>>=') {
parser_index += 4;
return {
type: parser_TokenPunctuator,
value: ch4,
start: start,
end: parser_index
};
}
// 3-character punctuators: === !== >>> <<= >>=
ch3 = ch4.substr(0, 3);
if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') {
parser_index += 3;
return {
type: parser_TokenPunctuator,
value: ch3,
start: start,
end: parser_index
};
}
// Other 2-character punctuators: ++ -- << >> && ||
ch2 = ch3.substr(0, 2);
if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') {
parser_index += 2;
return {
type: parser_TokenPunctuator,
value: ch2,
start: start,
end: parser_index
};
}
// 1-character punctuators: < > = ! + - * % & | ^ /
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++parser_index;
return {
type: parser_TokenPunctuator,
value: ch1,
start: start,
end: parser_index
};
}
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
// 7.8.3 Numeric Literals
function parser_scanHexLiteral(start) {
var number = '';
while (parser_index < parser_length) {
if (!parser_isHexDigit(parser_source[parser_index])) {
break;
}
number += parser_source[parser_index++];
}
if (number.length === 0) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
if (parser_isIdentifierStart(parser_source.charCodeAt(parser_index))) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
return {
type: parser_TokenNumericLiteral,
value: parseInt('0x' + number, 16),
start: start,
end: parser_index
};
}
function parser_scanOctalLiteral(start) {
var number = '0' + parser_source[parser_index++];
while (parser_index < parser_length) {
if (!parser_isOctalDigit(parser_source[parser_index])) {
break;
}
number += parser_source[parser_index++];
}
if (parser_isIdentifierStart(parser_source.charCodeAt(parser_index)) || parser_isDecimalDigit(parser_source.charCodeAt(parser_index))) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
return {
type: parser_TokenNumericLiteral,
value: parseInt(number, 8),
octal: true,
start: start,
end: parser_index
};
}
function parser_scanNumericLiteral() {
var number, start, ch;
ch = parser_source[parser_index];
parser_assert(parser_isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = parser_index;
number = '';
if (ch !== '.') {
number = parser_source[parser_index++];
ch = parser_source[parser_index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++parser_index;
return parser_scanHexLiteral(start);
}
if (parser_isOctalDigit(ch)) {
return parser_scanOctalLiteral(start);
}
// decimal number starts with '0' such as '09' is illegal.
if (ch && parser_isDecimalDigit(ch.charCodeAt(0))) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
}
while (parser_isDecimalDigit(parser_source.charCodeAt(parser_index))) {
number += parser_source[parser_index++];
}
ch = parser_source[parser_index];
}
if (ch === '.') {
number += parser_source[parser_index++];
while (parser_isDecimalDigit(parser_source.charCodeAt(parser_index))) {
number += parser_source[parser_index++];
}
ch = parser_source[parser_index];
}
if (ch === 'e' || ch === 'E') {
number += parser_source[parser_index++];
ch = parser_source[parser_index];
if (ch === '+' || ch === '-') {
number += parser_source[parser_index++];
}
if (parser_isDecimalDigit(parser_source.charCodeAt(parser_index))) {
while (parser_isDecimalDigit(parser_source.charCodeAt(parser_index))) {
number += parser_source[parser_index++];
}
} else {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
}
if (parser_isIdentifierStart(parser_source.charCodeAt(parser_index))) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
return {
type: parser_TokenNumericLiteral,
value: parseFloat(number),
start: start,
end: parser_index
};
}
// 7.8.4 String Literals
function parser_scanStringLiteral() {
var str = '',
quote, start, ch, code, octal = false;
quote = parser_source[parser_index];
parser_assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = parser_index;
++parser_index;
while (parser_index < parser_length) {
ch = parser_source[parser_index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = parser_source[parser_index++];
if (!ch || !parser_isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'u':
case 'x':
if (parser_source[parser_index] === '{') {
++parser_index;
str += parser_scanUnicodeCodePointEscape();
} else {
str += parser_scanHexEscape(ch);
}
break;
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
if (parser_isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
if (parser_index < parser_length && parser_isOctalDigit(parser_source[parser_index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(parser_source[parser_index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
parser_index < parser_length &&
parser_isOctalDigit(parser_source[parser_index])) {
code = code * 8 + '01234567'.indexOf(parser_source[parser_index++]);
}
}
str += String.fromCharCode(code);
} else {
str += ch;
}
break;
}
} else {
if (ch === '\r' && parser_source[parser_index] === '\n') {
++parser_index;
}
}
} else if (parser_isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
}
return {
type: parser_TokenStringLiteral,
value: str,
octal: octal,
start: start,
end: parser_index
};
}
function parser_testRegExp(pattern, flags) {
var tmp = pattern;
if (flags.indexOf('u') >= 0) {
// Replace each astral symbol and every Unicode code point
// escape sequence with a single ASCII symbol to avoid throwing on
// regular expressions that are only valid in combination with the
// `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it
// would be replaced by `[x-b]` which throws an error.
tmp = tmp
.replace(/\\u\{([0-9a-fA-F]+)\}/g, function($0, $1) {
if (parseInt($1, 16) <= 0x10FFFF) {
return 'x';
}
parser_throwError({}, parser_MessageInvalidRegExp);
})
.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
}
// First, detect invalid regular expressions.
try {
new RegExp(tmp);
} catch (e) {
parser_throwError({}, parser_MessageInvalidRegExp);
}
// Return a regular expression object for this pattern-flag pair, or
// `null` in case the current environment doesn't support the flags it
// uses.
try {
return new RegExp(pattern, flags);
} catch (exception) {
return null;
}
}
function parser_scanRegExpBody() {
var ch, str, classMarker, terminated, body;
ch = parser_source[parser_index];
parser_assert(ch === '/', 'Regular expression literal must start with a slash');
str = parser_source[parser_index++];
classMarker = false;
terminated = false;
while (parser_index < parser_length) {
ch = parser_source[parser_index++];
str += ch;
if (ch === '\\') {
ch = parser_source[parser_index++];
// ECMA-262 7.8.5
if (parser_isLineTerminator(ch.charCodeAt(0))) {
parser_throwError({}, parser_MessageUnterminatedRegExp);
}
str += ch;
} else if (parser_isLineTerminator(ch.charCodeAt(0))) {
parser_throwError({}, parser_MessageUnterminatedRegExp);
} else if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
}
}
}
if (!terminated) {
parser_throwError({}, parser_MessageUnterminatedRegExp);
}
// Exclude leading and trailing slash.
body = str.substr(1, str.length - 2);
return {
value: body,
literal: str
};
}
function parser_scanRegExpFlags() {
var ch, str, flags;
str = '';
flags = '';
while (parser_index < parser_length) {
ch = parser_source[parser_index];
if (!parser_isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++parser_index;
if (ch === '\\' && parser_index < parser_length) {
parser_throwError({}, parser_MessageUnexpectedToken, parser_ILLEGAL);
} else {
flags += ch;
str += ch;
}
}
if (flags.search(/[^gimuy]/g) >= 0) {
parser_throwError({}, parser_MessageInvalidRegExp, flags);
}
return {
value: flags,
literal: str
};
}
function parser_scanRegExp() {
var start, body, flags, value;
parser_lookahead = null;
parser_skipComment();
start = parser_index;
body = parser_scanRegExpBody();
flags = parser_scanRegExpFlags();
value = parser_testRegExp(body.value, flags.value);
return {
literal: body.literal + flags.literal,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
start: start,
end: parser_index
};
}
function parser_isIdentifierName(token) {
return token.type === parser_TokenIdentifier ||
token.type === parser_TokenKeyword ||
token.type === parser_TokenBooleanLiteral ||
token.type === parser_TokenNullLiteral;
}
function parser_advance() {
var ch;
parser_skipComment();
if (parser_index >= parser_length) {
return {
type: parser_TokenEOF,
start: parser_index,
end: parser_index
};
}
ch = parser_source.charCodeAt(parser_index);
if (parser_isIdentifierStart(ch)) {
return parser_scanIdentifier();
}
// Very common: ( and ) and ;
if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
return parser_scanPunctuator();
}
// String literal starts with single quote (U+0027) or double quote (U+0022).
if (ch === 0x27 || ch === 0x22) {
return parser_scanStringLiteral();
}
// Dot (.) U+002E can also start a floating-point number, hence the need
// to check the next character.
if (ch === 0x2E) {
if (parser_isDecimalDigit(parser_source.charCodeAt(parser_index + 1))) {
return parser_scanNumericLiteral();
}
return parser_scanPunctuator();
}
if (parser_isDecimalDigit(ch)) {
return parser_scanNumericLiteral();
}
return parser_scanPunctuator();
}
function parser_lex() {
var token;
token = parser_lookahead;
parser_index = token.end;
parser_lookahead = parser_advance();
parser_index = token.end;
return token;
}
function parser_peek() {
var pos;
pos = parser_index;
parser_lookahead = parser_advance();
parser_index = pos;
}
function parser_finishArrayExpression(elements) {
var node = new ASTNode(parser_SyntaxArrayExpression);
node.elements = elements;
return node;
}
function parser_finishBinaryExpression(operator, left, right) {
var node = new ASTNode((operator === '||' || operator === '&&') ? parser_SyntaxLogicalExpression : parser_SyntaxBinaryExpression);
node.operator = operator;
node.left = left;
node.right = right;
return node;
}
function parser_finishCallExpression(callee, args) {
var node = new ASTNode(parser_SyntaxCallExpression);
node.callee = callee;
node.arguments = args;
return node;
}
function parser_finishConditionalExpression(test, consequent, alternate) {
var node = new ASTNode(parser_SyntaxConditionalExpression);
node.test = test;
node.consequent = consequent;
node.alternate = alternate;
return node;
}
function parser_finishIdentifier(name) {
var node = new ASTNode(parser_SyntaxIdentifier);
node.name = name;
return node;
}
function parser_finishLiteral(token) {
var node = new ASTNode(parser_SyntaxLiteral);
node.value = token.value;
node.raw = parser_source.slice(token.start, token.end);
if (token.regex) {
if (node.raw === '//') {
node.raw = '/(?:)/';
}
node.regex = token.regex;
}
return node;
}
function parser_finishMemberExpression(accessor, object, property) {
var node = new ASTNode(parser_SyntaxMemberExpression);
node.computed = accessor === '[';
node.object = object;
node.property = property;
if (!node.computed) property.member = true;
return node;
}
function parser_finishObjectExpression(properties) {
var node = new ASTNode(parser_SyntaxObjectExpression);
node.properties = properties;
return node;
}
function parser_finishProperty(kind, key, value) {
var node = new ASTNode(parser_SyntaxProperty);
node.key = key;
node.value = value;
node.kind = kind;
return node;
}
function parser_finishUnaryExpression(operator, argument) {
var node = new ASTNode(parser_SyntaxUnaryExpression);
node.operator = operator;
node.argument = argument;
node.prefix = true;
return node;
}
// Throw an exception
function parser_throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function(whole, index) {
parser_assert(index < args.length, 'Message reference must be in range');
return args[index];
}
);
error = new Error(msg);
error.index = parser_index;
error.description = msg;
throw error;
}
// Throw an exception because of the token.
function parser_throwUnexpected(token) {
if (token.type === parser_TokenEOF) {
parser_throwError(token, parser_MessageUnexpectedEOS);
}
if (token.type === parser_TokenNumericLiteral) {
parser_throwError(token, parser_MessageUnexpectedNumber);
}
if (token.type === parser_TokenStringLiteral) {
parser_throwError(token, parser_MessageUnexpectedString);
}
if (token.type === parser_TokenIdentifier) {
parser_throwError(token, parser_MessageUnexpectedIdentifier);
}
if (token.type === parser_TokenKeyword) {
parser_throwError(token, parser_MessageUnexpectedReserved);
}
// BooleanLiteral, NullLiteral, or Punctuator.
parser_throwError(token, parser_MessageUnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function parser_expect(value) {
var token = parser_lex();
if (token.type !== parser_TokenPunctuator || token.value !== value) {
parser_throwUnexpected(token);
}
}
// Return true if the next token matches the specified punctuator.
function parser_match(value) {
return parser_lookahead.type === parser_TokenPunctuator && parser_lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function parser_matchKeyword(keyword) {
return parser_lookahead.type === parser_TokenKeyword && parser_lookahead.value === keyword;
}
// 11.1.4 Array Initialiser
function parser_parseArrayInitialiser() {
var elements = [];
parser_index = parser_lookahead.start;
parser_expect('[');
while (!parser_match(']')) {
if (parser_match(',')) {
parser_lex();
elements.push(null);
} else {
elements.push(parser_parseConditionalExpression());
if (!parser_match(']')) {
parser_expect(',');
}
}
}
parser_lex();
return parser_finishArrayExpression(elements);
}
// 11.1.5 Object Initialiser
function parser_parseObjectPropertyKey() {
var token;
parser_index = parser_lookahead.start;
token = parser_lex();
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === parser_TokenStringLiteral || token.type === parser_TokenNumericLiteral) {
if (token.octal) {
parser_throwError(token, parser_MessageStrictOctalLiteral);
}
return parser_finishLiteral(token);
}
return parser_finishIdentifier(token.value);
}
function parser_parseObjectProperty() {
var token, key, id, value;
parser_index = parser_lookahead.start;
token = parser_lookahead;
if (token.type === parser_TokenIdentifier) {
id = parser_parseObjectPropertyKey();
parser_expect(':');
value = parser_parseConditionalExpression();
return parser_finishProperty('init', id, value);
}
if (token.type === parser_TokenEOF || token.type === parser_TokenPunctuator) {
parser_throwUnexpected(token);
} else {
key = parser_parseObjectPropertyKey();
parser_expect(':');
value = parser_parseConditionalExpression();
return parser_finishProperty('init', key, value);
}
}
function parser_parseObjectInitialiser() {
var properties = [],
property, name, key, map = {},
toString = String;
parser_index = parser_lookahead.start;
parser_expect('{');
while (!parser_match('}')) {
property = parser_parseObjectProperty();
if (property.key.type === parser_SyntaxIdentifier) {
name = property.key.name;
} else {
name = toString(property.key.value);
}
key = '$' + name;
if (Object.prototype.hasOwnProperty.call(map, key)) {
parser_throwError({}, parser_MessageStrictDuplicateProperty);
} else {
map[key] = true;
}
properties.push(property);
if (!parser_match('}')) {
parser_expect(',');
}
}
parser_expect('}');
return parser_finishObjectExpression(properties);
}
// 11.1.6 The Grouping Operator
function parser_parseGroupExpression() {
var expr;
parser_expect('(');
expr = parser_parseExpression();
parser_expect(')');
return expr;
}
// 11.1 Primary Expressions
var parser_legalKeywords = {
"if": 1,
"this": 1
};
function parser_parsePrimaryExpression() {
var type, token, expr;
if (parser_match('(')) {
return parser_parseGroupExpression();
}
if (parser_match('[')) {
return parser_parseArrayInitialiser();
}
if (parser_match('{')) {
return parser_parseObjectInitialiser();
}
type = parser_lookahead.type;
parser_index = parser_lookahead.start;
if (type === parser_TokenIdentifier || parser_legalKeywords[parser_lookahead.value]) {
expr = parser_finishIdentifier(parser_lex().value);
} else if (type === parser_TokenStringLiteral || type === parser_TokenNumericLiteral) {
if (parser_lookahead.octal) {
parser_throwError(parser_lookahead, parser_MessageStrictOctalLiteral);
}
expr = parser_finishLiteral(parser_lex());
} else if (type === parser_TokenKeyword) {
throw new Error(parser_DISABLED);
} else if (type === parser_TokenBooleanLiteral) {
token = parser_lex();
token.value = (token.value === 'true');
expr = parser_finishLiteral(token);
} else if (type === parser_TokenNullLiteral) {
token = parser_lex();
token.value = null;
expr = parser_finishLiteral(token);
} else if (parser_match('/') || parser_match('/=')) {
expr = parser_finishLiteral(parser_scanRegExp());
parser_peek();
} else {
parser_throwUnexpected(parser_lex());
}
return expr;
}
// 11.2 Left-Hand-Side Expressions
function parser_parseArguments() {
var args = [];
parser_expect('(');
if (!parser_match(')')) {
while (parser_index < parser_length) {
args.push(parser_parseConditionalExpression());
if (parser_match(')')) {
break;
}
parser_expect(',');
}
}
parser_expect(')');
return args;
}
function parser_parseNonComputedProperty() {
var token;
parser_index = parser_lookahead.start;
token = parser_lex();
if (!parser_isIdentifierName(token)) {
parser_throwUnexpected(token);
}
return parser_finishIdentifier(token.value);
}
function parser_parseNonComputedMember() {
parser_expect('.');
return parser_parseNonComputedProperty();
}
function parser_parseComputedMember() {
var expr;
parser_expect('[');
expr = parser_parseExpression();
parser_expect(']');
return expr;
}
function parser_parseLeftHandSideExpressionAllowCall() {
var expr, args, property;
expr = parser_parsePrimaryExpression();
for (;;) {
if (parser_match('.')) {
property = parser_parseNonComputedMember();
expr = parser_finishMemberExpression('.', expr, property);
} else if (parser_match('(')) {
args = parser_parseArguments();
expr = parser_finishCallExpression(expr, args);
} else if (parser_match('[')) {
property = parser_parseComputedMember();
expr = parser_finishMemberExpression('[', expr, property);
} else {
break;
}
}
return expr;
}
// 11.3 Postfix Expressions
function parser_parsePostfixExpression() {
var expr = parser_parseLeftHandSideExpressionAllowCall();
if (parser_lookahead.type === parser_TokenPunctuator) {
if ((parser_match('++') || parser_match('--'))) {
throw new Error(parser_DISABLED);
}
}
return expr;
}
// 11.4 Unary Operators
function parser_parseUnaryExpression() {
var token, expr;
if (parser_lookahead.type !== parser_TokenPunctuator && parser_lookahead.type !== parser_TokenKeyword) {
expr = parser_parsePostfixExpression();
} else if (parser_match('++') || parser_match('--')) {
throw new Error(parser_DISABLED);
} else if (parser_match('+') || parser_match('-') || parser_match('~') || parser_match('!')) {
token = parser_lex();
expr = parser_parseUnaryExpression();
expr = parser_finishUnaryExpression(token.value, expr);
} else if (parser_matchKeyword('delete') || parser_matchKeyword('void') || parser_matchKeyword('typeof')) {
throw new Error(parser_DISABLED);
} else {
expr = parser_parsePostfixExpression();
}
return expr;
}
function parser_binaryPrecedence(token) {
var prec = 0;
if (token.type !== parser_TokenPunctuator && token.type !== parser_TokenKeyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '|':
prec = 3;
break;
case '^':
prec = 4;
break;
case '&':
prec = 5;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
case 'in':
prec = 7;
break;
case '<<':
case '>>':
case '>>>':
prec = 8;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parser_parseBinaryExpression() {
var marker, markers, expr, token, prec, stack, right, operator, left, i;
marker = parser_lookahead;
left = parser_parseUnaryExpression();
token = parser_lookahead;
prec = parser_binaryPrecedence(token);
if (prec === 0) {
return left;
}
token.prec = prec;
parser_lex();
markers = [marker, parser_lookahead];
right = parser_parseUnaryExpression();
stack = [left, token, right];
while ((prec = parser_binaryPrecedence(parser_lookahead)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
markers.pop();
expr = parser_finishBinaryExpression(operator, left, right);
stack.push(expr);
}
// Shift.
token = parser_lex();
token.prec = prec;
stack.push(token);
markers.push(parser_lookahead);
expr = parser_parseUnaryExpression();
stack.push(expr);
}
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
markers.pop()
expr = parser_finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
}
return expr;
}
// 11.12 Conditional Operator
function parser_parseConditionalExpression() {
var expr, consequent, alternate;
expr = parser_parseBinaryExpression();
if (parser_match('?')) {
parser_lex();
consequent = parser_parseConditionalExpression();
parser_expect(':');
alternate = parser_parseConditionalExpression();
expr = parser_finishConditionalExpression(expr, consequent, alternate);
}
return expr;
}
// 11.14 Comma Operator
function parser_parseExpression() {
var expr = parser_parseConditionalExpression();
if (parser_match(',')) {
throw new Error(parser_DISABLED); // no sequence expressions
}
return expr;
}
/* harmony default export */ var parser = (function(code) {
parser_source = code;
parser_index = 0;
parser_length = parser_source.length;
parser_lookahead = null;
parser_peek();
var expr = parser_parseExpression();
if (parser_lookahead.type !== parser_TokenEOF) {
throw new Error("Unexpect token after expression.");
}
return expr;
});
// CONCATENATED MODULE: ./node_modules/vega-expression/src/constants.js
/* harmony default export */ var src_constants = ({
NaN: 'NaN',
E: 'Math.E',
LN2: 'Math.LN2',
LN10: 'Math.LN10',
LOG2E: 'Math.LOG2E',
LOG10E: 'Math.LOG10E',
PI: 'Math.PI',
SQRT1_2: 'Math.SQRT1_2',
SQRT2: 'Math.SQRT2',
MIN_VALUE: 'Number.MIN_VALUE',
MAX_VALUE: 'Number.MAX_VALUE'
});
// CONCATENATED MODULE: ./node_modules/vega-expression/src/functions.js
/* harmony default export */ var src_functions = (function(codegen) {
function fncall(name, args, cast, type) {
var obj = codegen(args[0]);
if (cast) {
obj = cast + '(' + obj + ')';
if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')';
}
return obj + '.' + name + (type < 0 ? '' : type === 0 ?
'()' :
'(' + args.slice(1).map(codegen).join(',') + ')');
}
function fn(name, cast, type) {
return function(args) {
return fncall(name, args, cast, type);
};
}
var DATE = 'new Date',
STRING = 'String',
REGEXP = 'RegExp';
return {
// MATH functions
isNaN: 'Number.isNaN',
isFinite: 'Number.isFinite',
abs: 'Math.abs',
acos: 'Math.acos',
asin: 'Math.asin',
atan: 'Math.atan',
atan2: 'Math.atan2',
ceil: 'Math.ceil',
cos: 'Math.cos',
exp: 'Math.exp',
floor: 'Math.floor',
log: 'Math.log',
max: 'Math.max',
min: 'Math.min',
pow: 'Math.pow',
random: 'Math.random',
round: 'Math.round',
sin: 'Math.sin',
sqrt: 'Math.sqrt',
tan: 'Math.tan',
clamp: function(args) {
if (args.length < 3) Object(vega_util["n" /* error */])('Missing arguments to clamp function.');
if (args.length > 3) Object(vega_util["n" /* error */])('Too many arguments to clamp function.');
var a = args.map(codegen);
return 'Math.max('+a[1]+', Math.min('+a[2]+','+a[0]+'))';
},
// DATE functions
now: 'Date.now',
utc: 'Date.UTC',
datetime: DATE,
date: fn('getDate', DATE, 0),
day: fn('getDay', DATE, 0),
year: fn('getFullYear', DATE, 0),
month: fn('getMonth', DATE, 0),
hours: fn('getHours', DATE, 0),
minutes: fn('getMinutes', DATE, 0),
seconds: fn('getSeconds', DATE, 0),
milliseconds: fn('getMilliseconds', DATE, 0),
time: fn('getTime', DATE, 0),
timezoneoffset: fn('getTimezoneOffset', DATE, 0),
utcdate: fn('getUTCDate', DATE, 0),
utcday: fn('getUTCDay', DATE, 0),
utcyear: fn('getUTCFullYear', DATE, 0),
utcmonth: fn('getUTCMonth', DATE, 0),
utchours: fn('getUTCHours', DATE, 0),
utcminutes: fn('getUTCMinutes', DATE, 0),
utcseconds: fn('getUTCSeconds', DATE, 0),
utcmilliseconds: fn('getUTCMilliseconds', DATE, 0),
// sequence functions
length: fn('length', null, -1),
join: fn('join', null),
indexof: fn('indexOf', null),
lastindexof: fn('lastIndexOf', null),
slice: fn('slice', null),
reverse: function(args) {
return '('+codegen(args[0])+').slice().reverse()';
},
// STRING functions
parseFloat: 'parseFloat',
parseInt: 'parseInt',
upper: fn('toUpperCase', STRING, 0),
lower: fn('toLowerCase', STRING, 0),
substring: fn('substring', STRING),
split: fn('split', STRING),
replace: fn('replace', STRING),
trim: fn('trim', STRING, 0),
// REGEXP functions
regexp: REGEXP,
test: fn('test', REGEXP),
// Control Flow functions
if: function(args) {
if (args.length < 3) Object(vega_util["n" /* error */])('Missing arguments to if function.');
if (args.length > 3) Object(vega_util["n" /* error */])('Too many arguments to if function.');
var a = args.map(codegen);
return '('+a[0]+'?'+a[1]+':'+a[2]+')';
}
};
});
// CONCATENATED MODULE: ./node_modules/vega-expression/src/codegen.js
function codegen_stripQuotes(s) {
var n = s && s.length - 1;
return n && (
(s[0]==='"' && s[n]==='"') ||
(s[0]==='\'' && s[n]==='\'')
) ? s.slice(1, -1) : s;
}
/* harmony default export */ var src_codegen = (function(opt) {
opt = opt || {};
var whitelist = opt.whitelist ? Object(vega_util["Da" /* toSet */])(opt.whitelist) : {},
blacklist = opt.blacklist ? Object(vega_util["Da" /* toSet */])(opt.blacklist) : {},
constants = opt.constants || src_constants,
functions = (opt.functions || src_functions)(visit),
globalvar = opt.globalvar,
fieldvar = opt.fieldvar,
globals = {},
fields = {},
memberDepth = 0;
var outputGlobal = Object(vega_util["D" /* isFunction */])(globalvar)
? globalvar
: function (id) { return globalvar + '["' + id + '"]'; };
function visit(ast) {
if (Object(vega_util["H" /* isString */])(ast)) return ast;
var generator = Generators[ast.type];
if (generator == null) Object(vega_util["n" /* error */])('Unsupported type: ' + ast.type);
return generator(ast);
}
var Generators = {
Literal: function(n) {
return n.raw;
},
Identifier: function(n) {
var id = n.name;
if (memberDepth > 0) {
return id;
} else if (Object(vega_util["v" /* hasOwnProperty */])(blacklist, id)) {
return Object(vega_util["n" /* error */])('Illegal identifier: ' + id);
} else if (Object(vega_util["v" /* hasOwnProperty */])(constants, id)) {
return constants[id];
} else if (Object(vega_util["v" /* hasOwnProperty */])(whitelist, id)) {
return id;
} else {
globals[id] = 1;
return outputGlobal(id);
}
},
MemberExpression: function(n) {
var d = !n.computed;
var o = visit(n.object);
if (d) memberDepth += 1;
var p = visit(n.property);
if (o === fieldvar) {
// strip quotes to sanitize field name (#1653)
fields[codegen_stripQuotes(p)] = 1;
}
if (d) memberDepth -= 1;
return o + (d ? '.'+p : '['+p+']');
},
CallExpression: function(n) {
if (n.callee.type !== 'Identifier') {
Object(vega_util["n" /* error */])('Illegal callee type: ' + n.callee.type);
}
var callee = n.callee.name;
var args = n.arguments;
var fn = Object(vega_util["v" /* hasOwnProperty */])(functions, callee) && functions[callee];
if (!fn) Object(vega_util["n" /* error */])('Unrecognized function: ' + callee);
return Object(vega_util["D" /* isFunction */])(fn)
? fn(args)
: fn + '(' + args.map(visit).join(',') + ')';
},
ArrayExpression: function(n) {
return '[' + n.elements.map(visit).join(',') + ']';
},
BinaryExpression: function(n) {
return '(' + visit(n.left) + n.operator + visit(n.right) + ')';
},
UnaryExpression: function(n) {
return '(' + n.operator + visit(n.argument) + ')';
},
ConditionalExpression: function(n) {
return '(' + visit(n.test) +
'?' + visit(n.consequent) +
':' + visit(n.alternate) +
')';
},
LogicalExpression: function(n) {
return '(' + visit(n.left) + n.operator + visit(n.right) + ')';
},
ObjectExpression: function(n) {
return '{' + n.properties.map(visit).join(',') + '}';
},
Property: function(n) {
memberDepth += 1;
var k = visit(n.key);
memberDepth -= 1;
return k + ':' + visit(n.value);
}
};
function codegen(ast) {
var result = {
code: visit(ast),
globals: Object.keys(globals),
fields: Object.keys(fields)
};
globals = {};
fields = {};
return result;
}
codegen.functions = functions;
codegen.constants = constants;
return codegen;
});
// CONCATENATED MODULE: ./node_modules/vega-expression/index.js
// CONCATENATED MODULE: ./node_modules/vega-selections/src/constants.js
const Intersect = 'intersect';
const Union = 'union';
const VlMulti = 'vlMulti';
const Or = 'or';
const And = 'and';
// CONCATENATED MODULE: ./node_modules/vega-selections/src/selectionTest.js
var selectionTest_TYPE_ENUM = 'E',
selectionTest_TYPE_RANGE_INC = 'R',
selectionTest_TYPE_RANGE_EXC = 'R-E',
selectionTest_TYPE_RANGE_LE = 'R-LE',
selectionTest_TYPE_RANGE_RE = 'R-RE',
selectionTest_UNIT_INDEX = 'index:unit';
// TODO: revisit date coercion?
function selectionTest_testPoint(datum, entry) {
var fields = entry.fields,
values = entry.values,
n = fields.length,
i = 0, dval, f;
for (; i<n; ++i) {
f = fields[i];
f.getter = vega_util["t" /* field */].getter || Object(vega_util["t" /* field */])(f.field);
dval = f.getter(datum);
if (Object(vega_util["C" /* isDate */])(dval)) dval = Object(vega_util["Ca" /* toNumber */])(dval);
if (Object(vega_util["C" /* isDate */])(values[i])) values[i] = Object(vega_util["Ca" /* toNumber */])(values[i]);
if (Object(vega_util["C" /* isDate */])(values[i][0])) values[i] = values[i].map(vega_util["Ca" /* toNumber */]);
if (f.type === selectionTest_TYPE_ENUM) {
// Enumerated fields can either specify individual values (single/multi selections)
// or an array of values (interval selections).
if(Object(vega_util["A" /* isArray */])(values[i]) ? values[i].indexOf(dval) < 0 : dval !== values[i]) {
return false;
}
} else {
if (f.type === selectionTest_TYPE_RANGE_INC) {
if (!Object(vega_util["z" /* inrange */])(dval, values[i])) return false;
} else if (f.type === selectionTest_TYPE_RANGE_RE) {
// Discrete selection of bins test within the range [bin_start, bin_end).
if (!Object(vega_util["z" /* inrange */])(dval, values[i], true, false)) return false;
} else if (f.type === selectionTest_TYPE_RANGE_EXC) { // 'R-E'/'R-LE' included for completeness.
if (!Object(vega_util["z" /* inrange */])(dval, values[i], false, false)) return false;
} else if (f.type === selectionTest_TYPE_RANGE_LE) {
if (!Object(vega_util["z" /* inrange */])(dval, values[i], false, true)) return false;
}
}
}
return true;
}
/**
* Tests if a tuple is contained within an interactive selection.
* @param {string} name - The name of the data set representing the selection.
* Tuples in the dataset are of the form
* {unit: string, fields: array<fielddef>, values: array<*>}.
* Fielddef is of the form
* {field: string, channel: string, type: 'E' | 'R'} where
* 'type' identifies whether tuples in the dataset enumerate
* values for the field, or specify a continuous range.
* @param {object} datum - The tuple to test for inclusion.
* @param {string} op - The set operation for combining selections.
* One of 'intersect' or 'union' (default).
* @return {boolean} - True if the datum is in the selection, false otherwise.
*/
function selectionTest_selectionTest(name, datum, op) {
var data = this.context.data[name],
entries = data ? data.values.value : [],
unitIdx = data ? data[selectionTest_UNIT_INDEX] && data[selectionTest_UNIT_INDEX].value : undefined,
intersect = op === Intersect,
n = entries.length,
i = 0,
entry, miss, count, unit, b;
for (; i<n; ++i) {
entry = entries[i];
if (unitIdx && intersect) {
// multi selections union within the same unit and intersect across units.
miss = miss || {};
count = miss[unit=entry.unit] || 0;
// if we've already matched this unit, skip.
if (count === -1) continue;
b = selectionTest_testPoint(datum, entry);
miss[unit] = b ? -1 : ++count;
// if we match and there are no other units return true
// if we've missed against all tuples in this unit return false
if (b && unitIdx.size === 1) return true;
if (!b && count === unitIdx.get(unit).count) return false;
} else {
b = selectionTest_testPoint(datum, entry);
// if we find a miss and we do require intersection return false
// if we find a match and we don't require intersection return true
if (intersect ^ b) return b;
}
}
// if intersecting and we made it here, then we saw no misses
// if not intersecting, then we saw no matches
// if no active selections, return false
return n && intersect;
}
// CONCATENATED MODULE: ./node_modules/vega-selections/src/selectionResolve.js
/**
* Resolves selection for use as a scale domain or reads via the API.
* @param {string} name - The name of the dataset representing the selection
* @param {string} [op='union'] - The set operation for combining selections.
* One of 'intersect' or 'union' (default).
* @returns {object} An object of selected fields and values.
*/
function selectionResolve_selectionResolve(name, op, isMulti) {
var data = this.context.data[name],
entries = data ? data.values.value : [],
resolved = {}, multiRes = {}, types = {},
entry, fields, values, unit, field, res, resUnit, type, union,
n = entries.length, i = 0, j, m;
// First union all entries within the same unit.
for (; i < n; ++i) {
entry = entries[i];
unit = entry.unit;
fields = entry.fields;
values = entry.values;
for (j = 0, m = fields.length; j < m; ++j) {
field = fields[j];
res = resolved[field.field] || (resolved[field.field] = {});
resUnit = res[unit] || (res[unit] = []);
types[field.field] = type = field.type.charAt(0);
union = selectionResolve_ops[type + '_union'];
res[unit] = union(resUnit, Object(vega_util["i" /* array */])(values[j]));
}
// If the same multi-selection is repeated over views and projected over
// an encoding, it may operate over different fields making it especially
// tricky to reliably resolve it. At best, we can de-dupe identical entries
// but doing so may be more computationally expensive than it is worth.
// Instead, for now, we simply transform our store representation into
// a more human-friendly one.
if (isMulti) {
resUnit = multiRes[unit] || (multiRes[unit] = []);
resUnit.push(Object(vega_util["i" /* array */])(values).reduce((obj, curr, j) => (obj[fields[j].field] = curr, obj), {}));
}
}
// Then resolve fields across units as per the op.
op = op || Union;
Object.keys(resolved).forEach(function (field) {
resolved[field] = Object.keys(resolved[field])
.map(unit => resolved[field][unit])
.reduce((acc, curr) => acc === undefined ? curr : selectionResolve_ops[types[field] + '_' + op](acc, curr));
});
entries = Object.keys(multiRes);
if (isMulti && entries.length) {
resolved[VlMulti] = op === Union
? {[Or]: entries.reduce((acc, k) => (acc.push.apply(acc, multiRes[k]), acc), [])}
: {[And]: entries.map(k => ({[Or]: multiRes[k]}))};
}
return resolved;
}
var selectionResolve_ops = {
E_union: function(base, value) {
if (!base.length) return value;
var i = 0, n = value.length;
for (; i<n; ++i) if (base.indexOf(value[i]) < 0) base.push(value[i]);
return base;
},
E_intersect: function(base, value) {
return !base.length ? value :
base.filter(function (v) { return value.indexOf(v) >= 0; });
},
R_union: function(base, value) {
var lo = Object(vega_util["Ca" /* toNumber */])(value[0]), hi = Object(vega_util["Ca" /* toNumber */])(value[1]);
if (lo > hi) {
lo = value[1];
hi = value[0];
}
if (!base.length) return [lo, hi];
if (base[0] > lo) base[0] = lo;
if (base[1] < hi) base[1] = hi;
return base;
},
R_intersect: function(base, value) {
var lo = Object(vega_util["Ca" /* toNumber */])(value[0]), hi = Object(vega_util["Ca" /* toNumber */])(value[1]);
if (lo > hi) {
lo = value[1];
hi = value[0];
}
if (!base.length) return [lo, hi];
if (hi < base[0] || base[1] < lo) {
return [];
} else {
if (base[0] < lo) base[0] = lo;
if (base[1] > hi) base[1] = hi;
}
return base;
}
};
// CONCATENATED MODULE: ./node_modules/vega-selections/src/selectionVisitor.js
const selectionVisitor_DataPrefix = ':',
selectionVisitor_IndexPrefix = '@';
function selectionVisitor_selectionVisitor(name, args, scope, params) {
if (args[0].type !== Literal) Object(vega_util["n" /* error */])('First argument to selection functions must be a string literal.');
const data = args[0].value,
op = args.length >= 2 && Object(vega_util["U" /* peek */])(args).value,
field = 'unit',
indexName = selectionVisitor_IndexPrefix + field,
dataName = selectionVisitor_DataPrefix + data;
// eslint-disable-next-line no-prototype-builtins
if (op === Intersect && !Object(vega_util["v" /* hasOwnProperty */])(params, indexName)) {
params[indexName] = scope.getData(data).indataRef(scope, field);
}
// eslint-disable-next-line no-prototype-builtins
if (!Object(vega_util["v" /* hasOwnProperty */])(params, dataName)) {
params[dataName] = scope.getData(data).tuplesRef();
}
}
// CONCATENATED MODULE: ./node_modules/vega-selections/index.js
// CONCATENATED MODULE: ./node_modules/vega-functions/src/luminance.js
// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
function luminance_channel_luminance_value(channelValue) {
const val = channelValue / 255;
if (val <= 0.03928) {
return val / 12.92;
}
return Math.pow((val + 0.055) / 1.055, 2.4);
}
function luminance_luminance(color) {
const c = color_rgb(color),
r = luminance_channel_luminance_value(c.r),
g = luminance_channel_luminance_value(c.g),
b = luminance_channel_luminance_value(c.b);
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
function luminance_contrast(color1, color2) {
const lum1 = luminance_luminance(color1),
lum2 = luminance_luminance(color2),
lumL = Math.max(lum1, lum2),
lumD = Math.min(lum1, lum2);
return (lumL + 0.05) / (lumD + 0.05);
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/data.js
function src_data_data(name) {
const data = this.context.data[name];
return data ? data.values.value : [];
}
function data_indata(name, field, value) {
const index = this.context.data[name]['index:' + field],
entry = index ? index.value.get(value) : undefined;
return entry ? entry.count : entry;
}
function data_setdata(name, tuples) {
const df = this.context.dataflow,
data = this.context.data[name],
input = data.input;
df.pulse(input, df.changeset().remove(vega_util["Ga" /* truthy */]).insert(tuples));
return 1;
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/encode.js
/* harmony default export */ var src_encode = (function(item, name, retval) {
if (item) {
const df = this.context.dataflow,
target = item.mark.source;
df.pulse(target, df.changeset().encode(item, name));
}
return retval !== undefined ? retval : item;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatDecimal.js
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimal(1.23) returns ["123", 0].
/* harmony default export */ var src_formatDecimal = (function(x, p) {
if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
var i, coefficient = x.slice(0, i);
// The string returned by toExponential either has the form \d\.\d+e[-+]\d+
// (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
return [
coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
+x.slice(i + 1)
];
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/exponent.js
/* harmony default export */ var d3_format_src_exponent = (function(x) {
return x = src_formatDecimal(Math.abs(x)), x ? x[1] : NaN;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatGroup.js
/* harmony default export */ var src_formatGroup = (function(grouping, thousands) {
return function(value, width) {
var i = value.length,
t = [],
j = 0,
g = grouping[0],
length = 0;
while (i > 0 && g > 0) {
if (length + g + 1 > width) g = Math.max(1, width - length);
t.push(value.substring(i -= g, i + g));
if ((length += g + 1) > width) break;
g = grouping[j = (j + 1) % grouping.length];
}
return t.reverse().join(thousands);
};
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ var src_formatNumerals = (function(numerals) {
return function(value) {
return value.replace(/[0-9]/g, function(i) {
return numerals[+i];
});
};
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var formatSpecifier_re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier_formatSpecifier(specifier) {
if (!(match = formatSpecifier_re.exec(specifier))) throw new Error("invalid format: " + specifier);
var match;
return new formatSpecifier_FormatSpecifier({
fill: match[1],
align: match[2],
sign: match[3],
symbol: match[4],
zero: match[5],
width: match[6],
comma: match[7],
precision: match[8] && match[8].slice(1),
trim: match[9],
type: match[10]
});
}
formatSpecifier_formatSpecifier.prototype = formatSpecifier_FormatSpecifier.prototype; // instanceof
function formatSpecifier_FormatSpecifier(specifier) {
this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
this.align = specifier.align === undefined ? ">" : specifier.align + "";
this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
this.zero = !!specifier.zero;
this.width = specifier.width === undefined ? undefined : +specifier.width;
this.comma = !!specifier.comma;
this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
this.trim = !!specifier.trim;
this.type = specifier.type === undefined ? "" : specifier.type + "";
}
formatSpecifier_FormatSpecifier.prototype.toString = function() {
return this.fill
+ this.align
+ this.sign
+ this.symbol
+ (this.zero ? "0" : "")
+ (this.width === undefined ? "" : Math.max(1, this.width | 0))
+ (this.comma ? "," : "")
+ (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
+ (this.trim ? "~" : "")
+ this.type;
};
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ var src_formatTrim = (function(s) {
out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (s[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) i0 = i; i1 = i; break;
default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
}
}
return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatPrefixAuto.js
var src_formatPrefixAuto_prefixExponent;
/* harmony default export */ var src_formatPrefixAuto = (function(x, p) {
var d = src_formatDecimal(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1],
i = exponent - (src_formatPrefixAuto_prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
n = coefficient.length;
return i === n ? coefficient
: i > n ? coefficient + new Array(i - n + 1).join("0")
: i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
: "0." + new Array(1 - i).join("0") + src_formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y!
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatRounded.js
/* harmony default export */ var src_formatRounded = (function(x, p) {
var d = src_formatDecimal(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1];
return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
: coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
: coefficient + new Array(exponent - coefficient.length + 2).join("0");
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/formatTypes.js
/* harmony default export */ var src_formatTypes = ({
"%": function(x, p) { return (x * 100).toFixed(p); },
"b": function(x) { return Math.round(x).toString(2); },
"c": function(x) { return x + ""; },
"d": function(x) { return Math.round(x).toString(10); },
"e": function(x, p) { return x.toExponential(p); },
"f": function(x, p) { return x.toFixed(p); },
"g": function(x, p) { return x.toPrecision(p); },
"o": function(x) { return Math.round(x).toString(8); },
"p": function(x, p) { return src_formatRounded(x * 100, p); },
"r": src_formatRounded,
"s": src_formatPrefixAuto,
"X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
"x": function(x) { return Math.round(x).toString(16); }
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/identity.js
/* harmony default export */ var node_modules_d3_format_src_identity = (function(x) {
return x;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/locale.js
var src_locale_map = Array.prototype.map,
src_locale_prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
/* harmony default export */ var d3_format_src_locale = (function(locale) {
var group = locale.grouping === undefined || locale.thousands === undefined ? node_modules_d3_format_src_identity : src_formatGroup(src_locale_map.call(locale.grouping, Number), locale.thousands + ""),
currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
decimal = locale.decimal === undefined ? "." : locale.decimal + "",
numerals = locale.numerals === undefined ? node_modules_d3_format_src_identity : src_formatNumerals(src_locale_map.call(locale.numerals, String)),
percent = locale.percent === undefined ? "%" : locale.percent + "",
minus = locale.minus === undefined ? "-" : locale.minus + "",
nan = locale.nan === undefined ? "NaN" : locale.nan + "";
function newFormat(specifier) {
specifier = formatSpecifier_formatSpecifier(specifier);
var fill = specifier.fill,
align = specifier.align,
sign = specifier.sign,
symbol = specifier.symbol,
zero = specifier.zero,
width = specifier.width,
comma = specifier.comma,
precision = specifier.precision,
trim = specifier.trim,
type = specifier.type;
// The "n" type is an alias for ",g".
if (type === "n") comma = true, type = "g";
// The "" type, and any invalid type, is an alias for ".12~g".
else if (!src_formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";
// If zero fill is specified, padding goes after sign and before digits.
if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
// Compute the prefix and suffix.
// For SI-prefix, the suffix is lazily computed.
var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
// What format function should we use?
// Is this an integer type?
// Can this type generate exponential notation?
var formatType = src_formatTypes[type],
maybeSuffix = /[defgprs%]/.test(type);
// Set the default precision if not specified,
// or clamp the specified precision to the supported range.
// For significant precision, it must be in [1, 21].
// For fixed precision, it must be in [0, 20].
precision = precision === undefined ? 6
: /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
: Math.max(0, Math.min(20, precision));
function format(value) {
var valuePrefix = prefix,
valueSuffix = suffix,
i, n, c;
if (type === "c") {
valueSuffix = formatType(value) + valueSuffix;
value = "";
} else {
value = +value;
// Determine the sign. -0 is not less than 0, but 1 / -0 is!
var valueNegative = value < 0 || 1 / value < 0;
// Perform the initial formatting.
value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
// Trim insignificant zeros.
if (trim) value = src_formatTrim(value);
// If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
// Compute the prefix and suffix.
valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
valueSuffix = (type === "s" ? src_locale_prefixes[8 + src_formatPrefixAuto_prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
if (maybeSuffix) {
i = -1, n = value.length;
while (++i < n) {
if (c = value.charCodeAt(i), 48 > c || c > 57) {
valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
value = value.slice(0, i);
break;
}
}
}
}
// If the fill character is not "0", grouping is applied before padding.
if (comma && !zero) value = group(value, Infinity);
// Compute the padding.
var length = valuePrefix.length + value.length + valueSuffix.length,
padding = length < width ? new Array(width - length + 1).join(fill) : "";
// If the fill character is "0", grouping is applied after padding.
if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
// Reconstruct the final output based on the desired alignment.
switch (align) {
case "<": value = valuePrefix + value + valueSuffix + padding; break;
case "=": value = valuePrefix + padding + value + valueSuffix; break;
case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
default: value = padding + valuePrefix + value + valueSuffix; break;
}
return numerals(value);
}
format.toString = function() {
return specifier + "";
};
return format;
}
function formatPrefix(specifier, value) {
var f = newFormat((specifier = formatSpecifier_formatSpecifier(specifier), specifier.type = "f", specifier)),
e = Math.max(-8, Math.min(8, Math.floor(d3_format_src_exponent(value) / 3))) * 3,
k = Math.pow(10, -e),
prefix = src_locale_prefixes[8 + e / 3];
return function(value) {
return f(k * value) + prefix;
};
}
return {
format: newFormat,
formatPrefix: formatPrefix
};
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/defaultLocale.js
var d3_format_src_defaultLocale_locale;
var src_defaultLocale_format;
var src_defaultLocale_formatPrefix;
d3_format_src_defaultLocale_defaultLocale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["$", ""],
minus: "-"
});
function d3_format_src_defaultLocale_defaultLocale(definition) {
d3_format_src_defaultLocale_locale = d3_format_src_locale(definition);
src_defaultLocale_format = d3_format_src_defaultLocale_locale.format;
src_defaultLocale_formatPrefix = d3_format_src_defaultLocale_locale.formatPrefix;
return d3_format_src_defaultLocale_locale;
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/format.js
const format_formatCache = {};
function src_format_formatter(type, method, specifier) {
let k = type + ':' + specifier,
e = format_formatCache[k];
if (!e || e[0] !== method) {
format_formatCache[k] = (e = [method, method(specifier)]);
}
return e[1];
}
function format_format(_, specifier) {
return src_format_formatter('format', src_defaultLocale_format, specifier)(_);
}
function src_format_timeFormat(_, specifier) {
return src_format_formatter('timeFormat', format_timeFormat, specifier)(_);
}
function src_format_utcFormat(_, specifier) {
return src_format_formatter('utcFormat', format_utcFormat, specifier)(_);
}
function format_timeParse(_, specifier) {
return src_format_formatter('timeParse', defaultLocale_timeParse, specifier)(_);
}
function format_utcParse(_, specifier) {
return src_format_formatter('utcParse', defaultLocale_utcParse, specifier)(_);
}
var format_dateObj = new Date(2000, 0, 1);
function format_time(month, day, specifier) {
if (!Number.isInteger(month) || !Number.isInteger(day)) return '';
format_dateObj.setYear(2000);
format_dateObj.setMonth(month);
format_dateObj.setDate(day);
return src_format_timeFormat(format_dateObj, specifier);
}
function format_monthFormat(month) {
return format_time(month, 1, '%B');
}
function format_monthAbbrevFormat(month) {
return format_time(month, 1, '%b');
}
function format_dayFormat(day) {
return format_time(0, 2 + day, '%A');
}
function format_dayAbbrevFormat(day) {
return format_time(0, 2 + day, '%a');
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/bandSpace.js
/* harmony default export */ var vega_scale_src_scales_bandSpace = (function(count, paddingInner, paddingOuter) {
var space = count - paddingInner + paddingOuter * 2;
return count ? (space > 0 ? space : 1) : 0;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/types.js
const src_scales_types_Identity = 'identity';
const vega_scale_src_scales_types_Linear = 'linear';
const src_scales_types_Log = 'log';
const src_scales_types_Pow = 'pow';
const src_scales_types_Sqrt = 'sqrt';
const src_scales_types_Symlog = 'symlog';
const src_scales_types_Time = 'time';
const src_scales_types_UTC = 'utc';
const src_scales_types_Sequential = 'sequential';
const src_scales_types_Diverging = 'diverging';
const vega_scale_src_scales_types_Quantile = 'quantile';
const src_scales_types_Quantize = 'quantize';
const src_scales_types_Threshold = 'threshold';
const src_scales_types_Ordinal = 'ordinal';
const src_scales_types_Point = 'point';
const src_scales_types_Band = 'band';
const src_scales_types_BinOrdinal = 'bin-ordinal';
// categories
const scales_types_Continuous = 'continuous';
const scales_types_Discrete = 'discrete';
const scales_types_Discretizing = 'discretizing';
const scales_types_Interpolating = 'interpolating';
const scales_types_Temporal = 'temporal';
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/invertRange.js
/* harmony default export */ var vega_scale_src_scales_invertRange = (function(scale) {
return function(_) {
var lo = _[0],
hi = _[1],
t;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
return [
scale.invert(lo),
scale.invert(hi)
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/invertRangeExtent.js
/* harmony default export */ var vega_scale_src_scales_invertRangeExtent = (function(scale) {
return function(_) {
var range = scale.range(),
lo = _[0],
hi = _[1],
min = -1, max, t, i, n;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
for (i=0, n=range.length; i<n; ++i) {
if (range[i] >= lo && range[i] <= hi) {
if (min < 0) min = i;
max = i;
}
}
if (min < 0) return undefined;
lo = scale.invertExtent(range[min]);
hi = scale.invertExtent(range[max]);
return [
lo[0] === undefined ? lo[1] : lo[0],
hi[1] === undefined ? hi[0] : hi[1]
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/scaleBand.js
function vega_scale_src_scales_scaleBand_band() {
var scale = ordinal_ordinal().unknown(undefined),
domain = scale.domain,
ordinalRange = scale.range,
range = [0, 1],
step,
bandwidth,
round = false,
paddingInner = 0,
paddingOuter = 0,
align = 0.5;
delete scale.unknown;
function rescale() {
var n = domain().length,
reverse = range[1] < range[0],
start = range[reverse - 0],
stop = range[1 - reverse],
space = vega_scale_src_scales_bandSpace(n, paddingInner, paddingOuter);
step = (stop - start) / (space || 1);
if (round) {
step = Math.floor(step);
}
start += (stop - start - step * (n - paddingInner)) * align;
bandwidth = step * (1 - paddingInner);
if (round) {
start = Math.round(start);
bandwidth = Math.round(bandwidth);
}
var values = src_range(n).map(function(i) { return start + step * i; });
return ordinalRange(reverse ? values.reverse() : values);
}
scale.domain = function(_) {
if (arguments.length) {
domain(_);
return rescale();
} else {
return domain();
}
};
scale.range = function(_) {
if (arguments.length) {
range = [+_[0], +_[1]];
return rescale();
} else {
return range.slice();
}
};
scale.rangeRound = function(_) {
range = [+_[0], +_[1]];
round = true;
return rescale();
};
scale.bandwidth = function() {
return bandwidth;
};
scale.step = function() {
return step;
};
scale.round = function(_) {
if (arguments.length) {
round = !!_;
return rescale();
} else {
return round;
}
};
scale.padding = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
paddingInner = paddingOuter;
return rescale();
} else {
return paddingInner;
}
};
scale.paddingInner = function(_) {
if (arguments.length) {
paddingInner = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingInner;
}
};
scale.paddingOuter = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingOuter;
}
};
scale.align = function(_) {
if (arguments.length) {
align = Math.max(0, Math.min(1, _));
return rescale();
} else {
return align;
}
};
scale.invertRange = function(_) {
// bail if range has null or undefined values
if (_[0] == null || _[1] == null) return;
var lo = +_[0],
hi = +_[1],
reverse = range[1] < range[0],
values = reverse ? ordinalRange().reverse() : ordinalRange(),
n = values.length - 1, a, b, t;
// bail if either range endpoint is invalid
if (lo !== lo || hi !== hi) return;
// order range inputs, bail if outside of scale range
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
if (hi < values[0] || lo > range[1-reverse]) return;
// binary search to index into scale range
a = Math.max(0, bisect_bisectRight(values, lo) - 1);
b = lo===hi ? a : bisect_bisectRight(values, hi) - 1;
// increment index a if lo is within padding gap
if (lo - values[a] > bandwidth + 1e-10) ++a;
if (reverse) {
// map + swap
t = a;
a = n - b;
b = n - t;
}
return (a > b) ? undefined : domain().slice(a, b+1);
};
scale.invert = function(_) {
var value = scale.invertRange([_, _]);
return value ? value[0] : value;
};
scale.copy = function() {
return vega_scale_src_scales_scaleBand_band()
.domain(domain())
.range(range)
.round(round)
.paddingInner(paddingInner)
.paddingOuter(paddingOuter)
.align(align);
};
return rescale();
}
function vega_scale_src_scales_scaleBand_pointish(scale) {
var copy = scale.copy;
scale.padding = scale.paddingOuter;
delete scale.paddingInner;
scale.copy = function() {
return vega_scale_src_scales_scaleBand_pointish(copy());
};
return scale;
}
function vega_scale_src_scales_scaleBand_point() {
return vega_scale_src_scales_scaleBand_pointish(vega_scale_src_scales_scaleBand_band().paddingInner(1));
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/numbers.js
var vega_scale_src_scales_numbers_map = Array.prototype.map;
function vega_scale_src_scales_numbers_numbers(_) {
return vega_scale_src_scales_numbers_map.call(_, function(x) { return +x; });
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/slice.js
var src_scales_slice_slice = Array.prototype.slice;
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales/scaleBinOrdinal.js
function vega_scale_src_scales_scaleBinOrdinal_scaleBinOrdinal() {
var domain = [],
range = [];
function scale(x) {
return x == null || x !== x
? undefined
: range[(d3_array_src_bisect(domain, x) - 1) % range.length];
}
scale.domain = function(_) {
if (arguments.length) {
domain = vega_scale_src_scales_numbers_numbers(_);
return scale;
} else {
return domain.slice();
}
};
scale.range = function(_) {
if (arguments.length) {
range = src_scales_slice_slice.call(_);
return scale;
} else {
return range.slice();
}
};
scale.tickFormat = function(count, specifier) {
return src_tickFormat(domain[0], Object(vega_util["U" /* peek */])(domain), count == null ? 10 : count, specifier);
};
scale.copy = function() {
return vega_scale_src_scales_scaleBinOrdinal_scaleBinOrdinal().domain(scale.domain()).range(scale.range());
};
return scale;
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/scales.js
// scale registry
const node_modules_vega_scale_src_scales_scales = {};
/**
* Augment scales with their type and needed inverse methods.
*/
function node_modules_vega_scale_src_scales_create(type, constructor, metadata) {
const ctr = function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? vega_scale_src_scales_invertRange(s)
: s.invertExtent ? vega_scale_src_scales_invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
ctr.metadata = Object(vega_util["Da" /* toSet */])(Object(vega_util["i" /* array */])(metadata));
return ctr;
}
function node_modules_vega_scale_src_scales_scale(type, scale, metadata) {
if (arguments.length > 1) {
node_modules_vega_scale_src_scales_scales[type] = node_modules_vega_scale_src_scales_create(type, scale, metadata);
return this;
} else {
return vega_scale_src_scales_isValidScaleType(type) ? node_modules_vega_scale_src_scales_scales[type] : undefined;
}
}
// identity scale
node_modules_vega_scale_src_scales_scale(src_scales_types_Identity, identity_identity);
// continuous scales
node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Linear, linear_linear, scales_types_Continuous);
node_modules_vega_scale_src_scales_scale(src_scales_types_Log, log_log, [scales_types_Continuous, src_scales_types_Log]);
node_modules_vega_scale_src_scales_scale(src_scales_types_Pow, pow_pow, scales_types_Continuous);
node_modules_vega_scale_src_scales_scale(src_scales_types_Sqrt, pow_sqrt, scales_types_Continuous);
node_modules_vega_scale_src_scales_scale(src_scales_types_Symlog, symlog_symlog, scales_types_Continuous);
node_modules_vega_scale_src_scales_scale(src_scales_types_Time, src_time, [scales_types_Continuous, scales_types_Temporal]);
node_modules_vega_scale_src_scales_scale(src_scales_types_UTC, utcTime, [scales_types_Continuous, scales_types_Temporal]);
// sequential scales
node_modules_vega_scale_src_scales_scale(src_scales_types_Sequential, sequential_sequential, [scales_types_Continuous, scales_types_Interpolating]); // backwards compat
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Sequential}-${vega_scale_src_scales_types_Linear}`, sequential_sequential, [scales_types_Continuous, scales_types_Interpolating]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Sequential}-${src_scales_types_Log}`, sequential_sequentialLog, [scales_types_Continuous, scales_types_Interpolating, src_scales_types_Log]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Sequential}-${src_scales_types_Pow}`, sequential_sequentialPow, [scales_types_Continuous, scales_types_Interpolating]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Sequential}-${src_scales_types_Sqrt}`, sequential_sequentialSqrt, [scales_types_Continuous, scales_types_Interpolating]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Sequential}-${src_scales_types_Symlog}`, sequential_sequentialSymlog, [scales_types_Continuous, scales_types_Interpolating]);
// diverging scales
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Diverging}-${vega_scale_src_scales_types_Linear}`, diverging_diverging, [scales_types_Continuous, scales_types_Interpolating]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Diverging}-${src_scales_types_Log}`, diverging_divergingLog, [scales_types_Continuous, scales_types_Interpolating, src_scales_types_Log]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Diverging}-${src_scales_types_Pow}`, diverging_divergingPow, [scales_types_Continuous, scales_types_Interpolating]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Diverging}-${src_scales_types_Sqrt}`, diverging_divergingSqrt, [scales_types_Continuous, scales_types_Interpolating]);
node_modules_vega_scale_src_scales_scale(`${src_scales_types_Diverging}-${src_scales_types_Symlog}`, diverging_divergingSymlog, [scales_types_Continuous, scales_types_Interpolating]);
// discretizing scales
node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Quantile, src_quantile_quantile, [scales_types_Discretizing, vega_scale_src_scales_types_Quantile]);
node_modules_vega_scale_src_scales_scale(src_scales_types_Quantize, quantize_quantize, scales_types_Discretizing);
node_modules_vega_scale_src_scales_scale(src_scales_types_Threshold, threshold_threshold, scales_types_Discretizing);
// discrete scales
node_modules_vega_scale_src_scales_scale(src_scales_types_BinOrdinal, vega_scale_src_scales_scaleBinOrdinal_scaleBinOrdinal, [scales_types_Discrete, scales_types_Discretizing]);
node_modules_vega_scale_src_scales_scale(src_scales_types_Ordinal, ordinal_ordinal, scales_types_Discrete);
node_modules_vega_scale_src_scales_scale(src_scales_types_Band, vega_scale_src_scales_scaleBand_band, scales_types_Discrete);
node_modules_vega_scale_src_scales_scale(src_scales_types_Point, vega_scale_src_scales_scaleBand_point, scales_types_Discrete);
function vega_scale_src_scales_isValidScaleType(type) {
return Object(vega_util["v" /* hasOwnProperty */])(node_modules_vega_scale_src_scales_scales, type);
}
function vega_scale_src_scales_hasType(key, type) {
const s = node_modules_vega_scale_src_scales_scales[key];
return s && s.metadata[type];
}
function vega_scale_src_scales_isContinuous(key) {
return vega_scale_src_scales_hasType(key, scales_types_Continuous);
}
function vega_scale_src_scales_isDiscrete(key) {
return vega_scale_src_scales_hasType(key, scales_types_Discrete);
}
function vega_scale_src_scales_isDiscretizing(key) {
return vega_scale_src_scales_hasType(key, scales_types_Discretizing);
}
function vega_scale_src_scales_isLogarithmic(key) {
return vega_scale_src_scales_hasType(key, src_scales_types_Log);
}
function vega_scale_src_scales_isTemporal(key) {
return vega_scale_src_scales_hasType(key, scales_types_Temporal);
}
function vega_scale_src_scales_isInterpolating(key) {
return vega_scale_src_scales_hasType(key, scales_types_Interpolating);
}
function vega_scale_src_scales_isQuantile(key) {
return vega_scale_src_scales_hasType(key, vega_scale_src_scales_types_Quantile);
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/interpolate.js
const node_modules_vega_scale_src_interpolate_scaleProps = ['clamp', 'base', 'constant', 'exponent'];
function node_modules_vega_scale_src_interpolate_interpolateRange(interpolator, range) {
var start = range[0],
span = Object(vega_util["U" /* peek */])(range) - start;
return function(i) { return interpolator(start + i * span); };
}
function node_modules_vega_scale_src_interpolate_interpolateColors(colors, type, gamma) {
return piecewise_piecewise(node_modules_vega_scale_src_interpolate_interpolate(type || 'rgb', gamma), colors);
}
function node_modules_vega_scale_src_interpolate_quantizeInterpolator(interpolator, count) {
var samples = new Array(count),
n = count + 1;
for (var i = 0; i < count;) samples[i] = interpolator(++i / n);
return samples;
}
function node_modules_vega_scale_src_interpolate_scaleCopy(scale) {
const t = scale.type,
s = scale.copy();
s.type = t;
return s;
}
function node_modules_vega_scale_src_interpolate_scaleFraction(scale, min, max) {
var delta = max - min, i, t, s;
if (!delta || !Number.isFinite(delta)) {
return Object(vega_util["l" /* constant */])(0.5);
} else {
i = (t = scale.type).indexOf('-');
t = i < 0 ? t : t.slice(i + 1);
s = node_modules_vega_scale_src_scales_scale(t)().domain([min, max]).range([0, 1]);
node_modules_vega_scale_src_interpolate_scaleProps.forEach(m => scale[m] ? s[m](scale[m]()) : 0);
return s;
}
}
function node_modules_vega_scale_src_interpolate_interpolate(type, gamma) {
var interp = d3_interpolate_src_namespaceObject[node_modules_vega_scale_src_interpolate_method(type)];
return (gamma != null && interp && interp.gamma)
? interp.gamma(gamma)
: interp;
}
function node_modules_vega_scale_src_interpolate_method(type) {
return 'interpolate' + type.toLowerCase()
.split('-')
.map(function(s) { return s[0].toUpperCase() + s.slice(1); })
.join('');
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/palettes.js
const node_modules_vega_scale_src_palettes_continuous = {
blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',
greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',
greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',
oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',
purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',
reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',
blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',
bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',
greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',
orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',
purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',
purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',
purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',
redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',
yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',
yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',
yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',
blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',
brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',
purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',
purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',
redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',
redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',
yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',
redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',
redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',
pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',
spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',
viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',
magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',
inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',
plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',
rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',
sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',
browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',
tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',
teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',
warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',
goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',
goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',
goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',
lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',
lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',
lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',
lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',
lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',
darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',
darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',
darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',
darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',
darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'
};
const node_modules_vega_scale_src_palettes_discrete = {
category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',
category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',
category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',
category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',
tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',
tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',
accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',
dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',
paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',
pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',
pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',
set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',
set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',
set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f'
};
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/src/schemes.js
function node_modules_vega_scale_src_schemes_colors(palette) {
var n = palette.length / 6 | 0, c = new Array(n), i = 0;
while (i < n) c[i] = '#' + palette.slice(i * 6, ++i * 6);
return c;
}
function node_modules_vega_scale_src_schemes_apply(_, f) {
for (let k in _) node_modules_vega_scale_src_schemes_scheme(k, f(_[k]));
}
const node_modules_vega_scale_src_schemes_schemes = {};
node_modules_vega_scale_src_schemes_apply(node_modules_vega_scale_src_palettes_discrete, node_modules_vega_scale_src_schemes_colors);
node_modules_vega_scale_src_schemes_apply(node_modules_vega_scale_src_palettes_continuous, _ => node_modules_vega_scale_src_interpolate_interpolateColors(node_modules_vega_scale_src_schemes_colors(_)));
function node_modules_vega_scale_src_schemes_scheme(name, scheme) {
name = name && name.toLowerCase();
if (arguments.length > 1) {
node_modules_vega_scale_src_schemes_schemes[name] = scheme;
return this;
} else {
return node_modules_vega_scale_src_schemes_schemes[name];
}
}
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/vega-scale/index.js
// CONCATENATED MODULE: ./node_modules/vega-functions/src/scale.js
function scale_getScale(name, ctx) {
let s;
return Object(vega_util["D" /* isFunction */])(name) ? name
: Object(vega_util["H" /* isString */])(name) ? (s = ctx.scales[name]) && s.value
: undefined;
}
function scale_range(name, group) {
const s = scale_getScale(name, (group || this).context);
return s && s.range ? s.range() : [];
}
function scale_domain(name, group) {
const s = scale_getScale(name, (group || this).context);
return s ? s.domain() : [];
}
function scale_bandwidth(name, group) {
const s = scale_getScale(name, (group || this).context);
return s && s.bandwidth ? s.bandwidth() : 0;
}
function scale_bandspace(count, paddingInner, paddingOuter) {
return vega_scale_src_scales_bandSpace(count || 0, paddingInner || 0, paddingOuter || 0);
}
function scale_copy(name, group) {
const s = scale_getScale(name, (group || this).context);
return s ? s.copy() : undefined;
}
function scale_scale(name, value, group) {
const s = scale_getScale(name, (group || this).context);
return s && value !== undefined ? s(value) : undefined;
}
function scale_invert(name, range, group) {
const s = scale_getScale(name, (group || this).context);
return !s ? undefined
: Object(vega_util["A" /* isArray */])(range) ? (s.invertRange || s.invert)(range)
: (s.invert || s.invertExtent)(range);
}
// CONCATENATED MODULE: ./node_modules/d3-geo/src/area.js
var src_area_areaRingSum = adder();
var src_area_areaSum = adder(),
area_lambda00,
area_phi00,
area_lambda0,
area_cosPhi0,
area_sinPhi0;
var src_area_areaStream = {
point: noop_noop,
lineStart: noop_noop,
lineEnd: noop_noop,
polygonStart: function() {
src_area_areaRingSum.reset();
src_area_areaStream.lineStart = src_area_areaRingStart;
src_area_areaStream.lineEnd = src_area_areaRingEnd;
},
polygonEnd: function() {
var areaRing = +src_area_areaRingSum;
src_area_areaSum.add(areaRing < 0 ? src_math_tau + areaRing : areaRing);
this.lineStart = this.lineEnd = this.point = noop_noop;
},
sphere: function() {
src_area_areaSum.add(src_math_tau);
}
};
function src_area_areaRingStart() {
src_area_areaStream.point = src_area_areaPointFirst;
}
function src_area_areaRingEnd() {
src_area_areaPoint(area_lambda00, area_phi00);
}
function src_area_areaPointFirst(lambda, phi) {
src_area_areaStream.point = src_area_areaPoint;
area_lambda00 = lambda, area_phi00 = phi;
lambda *= radians, phi *= radians;
area_lambda0 = lambda, area_cosPhi0 = src_math_cos(phi = phi / 2 + quarterPi), area_sinPhi0 = src_math_sin(phi);
}
function src_area_areaPoint(lambda, phi) {
lambda *= radians, phi *= radians;
phi = phi / 2 + quarterPi; // half the angular distance from south pole
// Spherical excess E for a spherical triangle with vertices: south pole,
// previous point, current point. Uses a formula derived from Cagnolis
// theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).
var dLambda = lambda - area_lambda0,
sdLambda = dLambda >= 0 ? 1 : -1,
adLambda = sdLambda * dLambda,
cosPhi = src_math_cos(phi),
sinPhi = src_math_sin(phi),
k = area_sinPhi0 * sinPhi,
u = area_cosPhi0 * cosPhi + k * src_math_cos(adLambda),
v = k * sdLambda * src_math_sin(adLambda);
src_area_areaRingSum.add(math_atan2(v, u));
// Advance the previous points.
area_lambda0 = lambda, area_cosPhi0 = cosPhi, area_sinPhi0 = sinPhi;
}
/* harmony default export */ var d3_geo_src_area = (function(object) {
src_area_areaSum.reset();
src_stream(object, src_area_areaStream);
return src_area_areaSum * 2;
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/bounds.js
var bounds_lambda0, bounds_phi0, bounds_lambda1, bounds_phi1, // bounds
bounds_lambda2, // previous lambda-coordinate
bounds_lambda00, bounds_phi00, // first point
bounds_p0, // previous 3D point
bounds_deltaSum = adder(),
bounds_ranges,
bounds_range;
var src_bounds_boundsStream = {
point: src_bounds_boundsPoint,
lineStart: bounds_boundsLineStart,
lineEnd: bounds_boundsLineEnd,
polygonStart: function() {
src_bounds_boundsStream.point = bounds_boundsRingPoint;
src_bounds_boundsStream.lineStart = bounds_boundsRingStart;
src_bounds_boundsStream.lineEnd = bounds_boundsRingEnd;
bounds_deltaSum.reset();
src_area_areaStream.polygonStart();
},
polygonEnd: function() {
src_area_areaStream.polygonEnd();
src_bounds_boundsStream.point = src_bounds_boundsPoint;
src_bounds_boundsStream.lineStart = bounds_boundsLineStart;
src_bounds_boundsStream.lineEnd = bounds_boundsLineEnd;
if (src_area_areaRingSum < 0) bounds_lambda0 = -(bounds_lambda1 = 180), bounds_phi0 = -(bounds_phi1 = 90);
else if (bounds_deltaSum > src_math_epsilon) bounds_phi1 = 90;
else if (bounds_deltaSum < -src_math_epsilon) bounds_phi0 = -90;
bounds_range[0] = bounds_lambda0, bounds_range[1] = bounds_lambda1;
},
sphere: function() {
bounds_lambda0 = -(bounds_lambda1 = 180), bounds_phi0 = -(bounds_phi1 = 90);
}
};
function src_bounds_boundsPoint(lambda, phi) {
bounds_ranges.push(bounds_range = [bounds_lambda0 = lambda, bounds_lambda1 = lambda]);
if (phi < bounds_phi0) bounds_phi0 = phi;
if (phi > bounds_phi1) bounds_phi1 = phi;
}
function bounds_linePoint(lambda, phi) {
var p = cartesian_cartesian([lambda * radians, phi * radians]);
if (bounds_p0) {
var normal = cartesian_cartesianCross(bounds_p0, p),
equatorial = [normal[1], -normal[0], 0],
inflection = cartesian_cartesianCross(equatorial, normal);
cartesian_cartesianNormalizeInPlace(inflection);
inflection = cartesian_spherical(inflection);
var delta = lambda - bounds_lambda2,
sign = delta > 0 ? 1 : -1,
lambdai = inflection[0] * math_degrees * sign,
phii,
antimeridian = math_abs(delta) > 180;
if (antimeridian ^ (sign * bounds_lambda2 < lambdai && lambdai < sign * lambda)) {
phii = inflection[1] * math_degrees;
if (phii > bounds_phi1) bounds_phi1 = phii;
} else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * bounds_lambda2 < lambdai && lambdai < sign * lambda)) {
phii = -inflection[1] * math_degrees;
if (phii < bounds_phi0) bounds_phi0 = phii;
} else {
if (phi < bounds_phi0) bounds_phi0 = phi;
if (phi > bounds_phi1) bounds_phi1 = phi;
}
if (antimeridian) {
if (lambda < bounds_lambda2) {
if (bounds_angle(bounds_lambda0, lambda) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda1 = lambda;
} else {
if (bounds_angle(lambda, bounds_lambda1) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda0 = lambda;
}
} else {
if (bounds_lambda1 >= bounds_lambda0) {
if (lambda < bounds_lambda0) bounds_lambda0 = lambda;
if (lambda > bounds_lambda1) bounds_lambda1 = lambda;
} else {
if (lambda > bounds_lambda2) {
if (bounds_angle(bounds_lambda0, lambda) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda1 = lambda;
} else {
if (bounds_angle(lambda, bounds_lambda1) > bounds_angle(bounds_lambda0, bounds_lambda1)) bounds_lambda0 = lambda;
}
}
}
} else {
bounds_ranges.push(bounds_range = [bounds_lambda0 = lambda, bounds_lambda1 = lambda]);
}
if (phi < bounds_phi0) bounds_phi0 = phi;
if (phi > bounds_phi1) bounds_phi1 = phi;
bounds_p0 = p, bounds_lambda2 = lambda;
}
function bounds_boundsLineStart() {
src_bounds_boundsStream.point = bounds_linePoint;
}
function bounds_boundsLineEnd() {
bounds_range[0] = bounds_lambda0, bounds_range[1] = bounds_lambda1;
src_bounds_boundsStream.point = src_bounds_boundsPoint;
bounds_p0 = null;
}
function bounds_boundsRingPoint(lambda, phi) {
if (bounds_p0) {
var delta = lambda - bounds_lambda2;
bounds_deltaSum.add(math_abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
} else {
bounds_lambda00 = lambda, bounds_phi00 = phi;
}
src_area_areaStream.point(lambda, phi);
bounds_linePoint(lambda, phi);
}
function bounds_boundsRingStart() {
src_area_areaStream.lineStart();
}
function bounds_boundsRingEnd() {
bounds_boundsRingPoint(bounds_lambda00, bounds_phi00);
src_area_areaStream.lineEnd();
if (math_abs(bounds_deltaSum) > src_math_epsilon) bounds_lambda0 = -(bounds_lambda1 = 180);
bounds_range[0] = bounds_lambda0, bounds_range[1] = bounds_lambda1;
bounds_p0 = null;
}
// Finds the left-right distance between two longitudes.
// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want
// the distance between ±180° to be 360°.
function bounds_angle(lambda0, lambda1) {
return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;
}
function bounds_rangeCompare(a, b) {
return a[0] - b[0];
}
function bounds_rangeContains(range, x) {
return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
}
/* harmony default export */ var src_bounds = (function(feature) {
var i, n, a, b, merged, deltaMax, delta;
bounds_phi1 = bounds_lambda1 = -(bounds_lambda0 = bounds_phi0 = Infinity);
bounds_ranges = [];
src_stream(feature, src_bounds_boundsStream);
// First, sort ranges by their minimum longitudes.
if (n = bounds_ranges.length) {
bounds_ranges.sort(bounds_rangeCompare);
// Then, merge any ranges that overlap.
for (i = 1, a = bounds_ranges[0], merged = [a]; i < n; ++i) {
b = bounds_ranges[i];
if (bounds_rangeContains(a, b[0]) || bounds_rangeContains(a, b[1])) {
if (bounds_angle(a[0], b[1]) > bounds_angle(a[0], a[1])) a[1] = b[1];
if (bounds_angle(b[0], a[1]) > bounds_angle(a[0], a[1])) a[0] = b[0];
} else {
merged.push(a = b);
}
}
// Finally, find the largest gap between the merged ranges.
// The final bounding box will be the inverse of this gap.
for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {
b = merged[i];
if ((delta = bounds_angle(a[1], b[0])) > deltaMax) deltaMax = delta, bounds_lambda0 = b[0], bounds_lambda1 = a[1];
}
}
bounds_ranges = bounds_range = null;
return bounds_lambda0 === Infinity || bounds_phi0 === Infinity
? [[NaN, NaN], [NaN, NaN]]
: [[bounds_lambda0, bounds_phi0], [bounds_lambda1, bounds_phi1]];
});
// CONCATENATED MODULE: ./node_modules/d3-geo/src/centroid.js
var centroid_W0, centroid_W1,
src_centroid_X0, src_centroid_Y0, src_centroid_Z0,
src_centroid_X1, src_centroid_Y1, src_centroid_Z1,
src_centroid_X2, src_centroid_Y2, src_centroid_Z2,
centroid_lambda00, centroid_phi00, // first point
src_centroid_x0, src_centroid_y0, centroid_z0; // previous point
var src_centroid_centroidStream = {
sphere: noop_noop,
point: src_centroid_centroidPoint,
lineStart: src_centroid_centroidLineStart,
lineEnd: src_centroid_centroidLineEnd,
polygonStart: function() {
src_centroid_centroidStream.lineStart = src_centroid_centroidRingStart;
src_centroid_centroidStream.lineEnd = src_centroid_centroidRingEnd;
},
polygonEnd: function() {
src_centroid_centroidStream.lineStart = src_centroid_centroidLineStart;
src_centroid_centroidStream.lineEnd = src_centroid_centroidLineEnd;
}
};
// Arithmetic mean of Cartesian vectors.
function src_centroid_centroidPoint(lambda, phi) {
lambda *= radians, phi *= radians;
var cosPhi = src_math_cos(phi);
centroid_centroidPointCartesian(cosPhi * src_math_cos(lambda), cosPhi * src_math_sin(lambda), src_math_sin(phi));
}
function centroid_centroidPointCartesian(x, y, z) {
++centroid_W0;
src_centroid_X0 += (x - src_centroid_X0) / centroid_W0;
src_centroid_Y0 += (y - src_centroid_Y0) / centroid_W0;
src_centroid_Z0 += (z - src_centroid_Z0) / centroid_W0;
}
function src_centroid_centroidLineStart() {
src_centroid_centroidStream.point = centroid_centroidLinePointFirst;
}
function centroid_centroidLinePointFirst(lambda, phi) {
lambda *= radians, phi *= radians;
var cosPhi = src_math_cos(phi);
src_centroid_x0 = cosPhi * src_math_cos(lambda);
src_centroid_y0 = cosPhi * src_math_sin(lambda);
centroid_z0 = src_math_sin(phi);
src_centroid_centroidStream.point = centroid_centroidLinePoint;
centroid_centroidPointCartesian(src_centroid_x0, src_centroid_y0, centroid_z0);
}
function centroid_centroidLinePoint(lambda, phi) {
lambda *= radians, phi *= radians;
var cosPhi = src_math_cos(phi),
x = cosPhi * src_math_cos(lambda),
y = cosPhi * src_math_sin(lambda),
z = src_math_sin(phi),
w = math_atan2(src_math_sqrt((w = src_centroid_y0 * z - centroid_z0 * y) * w + (w = centroid_z0 * x - src_centroid_x0 * z) * w + (w = src_centroid_x0 * y - src_centroid_y0 * x) * w), src_centroid_x0 * x + src_centroid_y0 * y + centroid_z0 * z);
centroid_W1 += w;
src_centroid_X1 += w * (src_centroid_x0 + (src_centroid_x0 = x));
src_centroid_Y1 += w * (src_centroid_y0 + (src_centroid_y0 = y));
src_centroid_Z1 += w * (centroid_z0 + (centroid_z0 = z));
centroid_centroidPointCartesian(src_centroid_x0, src_centroid_y0, centroid_z0);
}
function src_centroid_centroidLineEnd() {
src_centroid_centroidStream.point = src_centroid_centroidPoint;
}
// See J. E. Brock, The Inertia Tensor for a Spherical Triangle,
// J. Applied Mechanics 42, 239 (1975).
function src_centroid_centroidRingStart() {
src_centroid_centroidStream.point = centroid_centroidRingPointFirst;
}
function src_centroid_centroidRingEnd() {
centroid_centroidRingPoint(centroid_lambda00, centroid_phi00);
src_centroid_centroidStream.point = src_centroid_centroidPoint;
}
function centroid_centroidRingPointFirst(lambda, phi) {
centroid_lambda00 = lambda, centroid_phi00 = phi;
lambda *= radians, phi *= radians;
src_centroid_centroidStream.point = centroid_centroidRingPoint;
var cosPhi = src_math_cos(phi);
src_centroid_x0 = cosPhi * src_math_cos(lambda);
src_centroid_y0 = cosPhi * src_math_sin(lambda);
centroid_z0 = src_math_sin(phi);
centroid_centroidPointCartesian(src_centroid_x0, src_centroid_y0, centroid_z0);
}
function centroid_centroidRingPoint(lambda, phi) {
lambda *= radians, phi *= radians;
var cosPhi = src_math_cos(phi),
x = cosPhi * src_math_cos(lambda),
y = cosPhi * src_math_sin(lambda),
z = src_math_sin(phi),
cx = src_centroid_y0 * z - centroid_z0 * y,
cy = centroid_z0 * x - src_centroid_x0 * z,
cz = src_centroid_x0 * y - src_centroid_y0 * x,
m = src_math_sqrt(cx * cx + cy * cy + cz * cz),
w = math_asin(m), // line weight = angle
v = m && -w / m; // area weight multiplier
src_centroid_X2 += v * cx;
src_centroid_Y2 += v * cy;
src_centroid_Z2 += v * cz;
centroid_W1 += w;
src_centroid_X1 += w * (src_centroid_x0 + (src_centroid_x0 = x));
src_centroid_Y1 += w * (src_centroid_y0 + (src_centroid_y0 = y));
src_centroid_Z1 += w * (centroid_z0 + (centroid_z0 = z));
centroid_centroidPointCartesian(src_centroid_x0, src_centroid_y0, centroid_z0);
}
/* harmony default export */ var src_centroid = (function(object) {
centroid_W0 = centroid_W1 =
src_centroid_X0 = src_centroid_Y0 = src_centroid_Z0 =
src_centroid_X1 = src_centroid_Y1 = src_centroid_Z1 =
src_centroid_X2 = src_centroid_Y2 = src_centroid_Z2 = 0;
src_stream(object, src_centroid_centroidStream);
var x = src_centroid_X2,
y = src_centroid_Y2,
z = src_centroid_Z2,
m = x * x + y * y + z * z;
// If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.
if (m < math_epsilon2) {
x = src_centroid_X1, y = src_centroid_Y1, z = src_centroid_Z1;
// If the feature has zero length, fall back to arithmetic mean of point vectors.
if (centroid_W1 < src_math_epsilon) x = src_centroid_X0, y = src_centroid_Y0, z = src_centroid_Z0;
m = x * x + y * y + z * z;
// If the feature still has an undefined ccentroid, then return.
if (m < math_epsilon2) return [NaN, NaN];
}
return [math_atan2(y, x) * math_degrees, math_asin(z / src_math_sqrt(m)) * math_degrees];
});
// CONCATENATED MODULE: ./node_modules/vega-functions/src/geo.js
function geo_geoMethod(methodName, globalMethod) {
return function(projection, geojson, group) {
if (projection) {
// projection defined, use it
const p = scale_getScale(projection, (group || this).context);
return p && p.path[methodName](geojson);
} else {
// projection undefined, use global method
return globalMethod(geojson);
}
};
}
const geo_geoArea = geo_geoMethod('area', d3_geo_src_area);
const geo_geoBounds = geo_geoMethod('bounds', src_bounds);
const geo_geoCentroid = geo_geoMethod('centroid', src_centroid);
// CONCATENATED MODULE: ./node_modules/vega-functions/src/inscope.js
/* harmony default export */ var inscope = (function(item) {
let group = this.context.group,
value = false;
if (group) while (item) {
if (item === group) { value = true; break; }
item = item.mark.group;
}
return value;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/src/intersect.js
/* harmony default export */ var src_intersect = (function(b, opt, group) {
if (!b) return [];
const [u, v] = b,
box = new Bounds().set(u[0], u[1], v[0], v[1]),
scene = group || this.context.dataflow.scenegraph().root;
return intersect_intersect(scene, box, intersect_filter(opt));
});
function intersect_filter(opt) {
let p = null;
if (opt) {
const types = Object(vega_util["i" /* array */])(opt.marktype),
names = Object(vega_util["i" /* array */])(opt.markname);
p = _ => (!types.length || types.some(t => _.marktype === t))
&& (!names.length || names.some(s => _.name === s));
}
return p;
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/log.js
function src_log_log(df, method, args) {
try {
df[method].apply(df, ['EXPRESSION'].concat([].slice.call(args)));
} catch (err) {
df.warn(err);
}
return args[args.length-1];
}
function log_warn() {
return src_log_log(this.context.dataflow, 'warn', arguments);
}
function log_info() {
return src_log_log(this.context.dataflow, 'info', arguments);
}
function log_debug() {
return src_log_log(this.context.dataflow, 'debug', arguments);
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/merge.js
/* harmony default export */ var vega_functions_src_merge = (function() {
var args = [].slice.call(arguments);
args.unshift({});
return vega_util["o" /* extend */].apply(null, args);
});
// CONCATENATED MODULE: ./node_modules/vega-functions/src/modify.js
function modify_equal(a, b) {
return a === b || a !== a && b !== b ? true
: Object(vega_util["A" /* isArray */])(a) ? (
Object(vega_util["A" /* isArray */])(b) && a.length === b.length ? modify_equalArray(a, b) : false
)
: Object(vega_util["F" /* isObject */])(a) && Object(vega_util["F" /* isObject */])(b) ? modify_equalObject(a, b)
: false;
}
function modify_equalArray(a, b) {
for (let i=0, n=a.length; i<n; ++i) {
if (!modify_equal(a[i], b[i])) return false;
}
return true;
}
function modify_equalObject(a, b) {
for (let key in a) {
if (!modify_equal(a[key], b[key])) return false;
}
return true;
}
function modify_removePredicate(props) {
return _ => modify_equalObject(props, _);
}
/* harmony default export */ var src_modify = (function(name, insert, remove, toggle, modify, values) {
let df = this.context.dataflow,
data = this.context.data[name],
input = data.input,
changes = data.changes,
stamp = df.stamp(),
predicate, key;
if (df._trigger === false || !(input.value.length || insert || toggle)) {
// nothing to do!
return 0;
}
if (!changes || changes.stamp < stamp) {
data.changes = (changes = df.changeset());
changes.stamp = stamp;
df.runAfter(function() {
data.modified = true;
df.pulse(input, changes).run();
}, true, 1);
}
if (remove) {
predicate = remove === true ? vega_util["Ga" /* truthy */]
: (Object(vega_util["A" /* isArray */])(remove) || isTuple(remove)) ? remove
: modify_removePredicate(remove);
changes.remove(predicate);
}
if (insert) {
changes.insert(insert);
}
if (toggle) {
predicate = modify_removePredicate(toggle);
if (input.value.some(predicate)) {
changes.remove(predicate);
} else {
changes.insert(toggle);
}
}
if (modify) {
for (key in values) {
changes.modify(modify, key, values[key]);
}
}
return 1;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/src/pinch.js
function pinchDistance(event) {
const t = event.touches,
dx = t[0].clientX - t[1].clientX,
dy = t[0].clientY - t[1].clientY;
return Math.sqrt(dx * dx + dy * dy);
}
function pinchAngle(event) {
const t = event.touches;
return Math.atan2(
t[0].clientY - t[1].clientY,
t[0].clientX - t[1].clientX
);
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/scale-gradient.js
/* harmony default export */ var scale_gradient = (function(scale, p0, p1, count, group) {
scale = scale_getScale(scale, (group || this).context);
const gradient = Gradient(p0, p1);
let stops = scale.domain(),
min = stops[0],
max = Object(vega_util["U" /* peek */])(stops),
fraction = vega_util["x" /* identity */]
if (!(max - min)) {
// expand scale if domain has zero span, fix #1479
scale = (scale.interpolator
? node_modules_vega_scale_src_scales_scale('sequential')().interpolator(scale.interpolator())
: node_modules_vega_scale_src_scales_scale('linear')().interpolate(scale.interpolate()).range(scale.range())
).domain([min=0, max=1]);
} else {
fraction = node_modules_vega_scale_src_interpolate_scaleFraction(scale, min, max);
}
if (scale.ticks) {
stops = scale.ticks(+count || 15);
if (min !== stops[0]) stops.unshift(min);
if (max !== Object(vega_util["U" /* peek */])(stops)) stops.push(max);
}
stops.forEach(_ => gradient.stop(fraction(_), scale(_)));
return gradient;
});
// CONCATENATED MODULE: ./node_modules/vega-functions/src/shape.js
function shape_geoShape(projection, geojson, group) {
const p = scale_getScale(projection, (group || this).context);
return function(context) {
return p ? p.path.context(context)(geojson) : '';
}
}
function shape_pathShape(path) {
let p = null;
return function(context) {
return context
? path_render(context, (p = p || path_parse(path)))
: path;
};
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/tree.js
const tree_EMPTY = {};
function tree_datum(d) { return d.data; }
function tree_treeNodes(name, context) {
const tree = src_data_data.call(context, name);
return tree.root && tree.root.lookup || tree_EMPTY;
}
function tree_treePath(name, source, target) {
const nodes = tree_treeNodes(name, this),
s = nodes[source],
t = nodes[target];
return s && t ? s.path(t).map(tree_datum) : undefined;
}
function tree_treeAncestors(name, node) {
const n = tree_treeNodes(name, this)[node];
return n ? n.ancestors().map(tree_datum) : undefined;
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/window.js
const _window = (typeof window !== 'undefined' && window) || null;
function screen() {
return _window ? _window.screen : {};
}
function windowSize() {
return _window
? [_window.innerWidth, _window.innerHeight]
: [undefined, undefined];
}
function containerSize() {
const view = this.context.dataflow,
el = view.container && view.container();
return el
? [el.clientWidth, el.clientHeight]
: [undefined, undefined];
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/prefix.js
const prefix_DataPrefix = ':';
const prefix_IndexPrefix = '@';
const ScalePrefix = '%';
const SignalPrefix = '$';
// CONCATENATED MODULE: ./node_modules/vega-functions/src/visitors.js
function visitors_dataVisitor(name, args, scope, params) {
if (args[0].type !== Literal) {
Object(vega_util["n" /* error */])('First argument to data functions must be a string literal.');
}
const data = args[0].value,
dataName = prefix_DataPrefix + data;
if (!Object(vega_util["v" /* hasOwnProperty */])(dataName, params)) {
try {
params[dataName] = scope.getData(data).tuplesRef();
} catch (err) {
// if data set does not exist, there's nothing to track
}
}
}
function visitors_indataVisitor(name, args, scope, params) {
if (args[0].type !== Literal) Object(vega_util["n" /* error */])('First argument to indata must be a string literal.');
if (args[1].type !== Literal) Object(vega_util["n" /* error */])('Second argument to indata must be a string literal.');
const data = args[0].value,
field = args[1].value,
indexName = prefix_IndexPrefix + field;
if (!Object(vega_util["v" /* hasOwnProperty */])(indexName, params)) {
params[indexName] = scope.getData(data).indataRef(scope, field);
}
}
function visitors_scaleVisitor(name, args, scope, params) {
if (args[0].type === Literal) {
// add scale dependency
visitors_addScaleDependency(scope, params, args[0].value);
}
else if (args[0].type === ast_Identifier) {
// indirect scale lookup; add all scales as parameters
for (name in scope.scales) {
visitors_addScaleDependency(scope, params, name);
}
}
}
function visitors_addScaleDependency(scope, params, name) {
const scaleName = ScalePrefix + name;
if (!Object(vega_util["v" /* hasOwnProperty */])(params, scaleName)) {
try {
params[scaleName] = scope.scaleRef(name);
} catch (err) {
// TODO: error handling? warning?
}
}
}
// CONCATENATED MODULE: ./node_modules/vega-functions/src/codegen.js
// Expression function context object
const codegen_functionContext = {
random: function() { return random_random(); }, // override default
cumulativeNormal: normal_cumulativeNormal,
cumulativeLogNormal: lognormal_cumulativeLogNormal,
cumulativeUniform: uniform_cumulativeUniform,
densityNormal: normal_densityNormal,
densityLogNormal: lognormal_densityLogNormal,
densityUniform: uniform_densityUniform,
quantileNormal: normal_quantileNormal,
quantileLogNormal: lognormal_quantileLogNormal,
quantileUniform: uniform_quantileUniform,
sampleNormal: normal_sampleNormal,
sampleLogNormal: lognormal_sampleLogNormal,
sampleUniform: uniform_sampleUniform,
isArray: vega_util["A" /* isArray */],
isBoolean: vega_util["B" /* isBoolean */],
isDate: vega_util["C" /* isDate */],
isDefined: function(_) { return _ !== undefined; },
isNumber: vega_util["E" /* isNumber */],
isObject: vega_util["F" /* isObject */],
isRegExp: vega_util["G" /* isRegExp */],
isString: vega_util["H" /* isString */],
isTuple: isTuple,
isValid: function(_) { return _ != null && _ === _; },
toBoolean: vega_util["Aa" /* toBoolean */],
toDate: vega_util["Ba" /* toDate */],
toNumber: vega_util["Ca" /* toNumber */],
toString: vega_util["Ea" /* toString */],
flush: vega_util["u" /* flush */],
lerp: vega_util["J" /* lerp */],
merge: vega_functions_src_merge,
pad: vega_util["P" /* pad */],
peek: vega_util["U" /* peek */],
span: vega_util["X" /* span */],
inrange: vega_util["z" /* inrange */],
truncate: vega_util["Fa" /* truncate */],
rgb: color_rgb,
lab: lab_lab,
hcl: lab_hcl,
hsl: color_hsl,
luminance: luminance_luminance,
contrast: luminance_contrast,
sequence: src_range,
format: format_format,
utcFormat: src_format_utcFormat,
utcParse: format_utcParse,
utcOffset: interval_utcOffset,
utcSequence: interval_utcSequence,
timeFormat: src_format_timeFormat,
timeParse: format_timeParse,
timeOffset: interval_timeOffset,
timeSequence: interval_timeSequence,
timeUnitSpecifier: format_timeUnitSpecifier,
monthFormat: format_monthFormat,
monthAbbrevFormat: format_monthAbbrevFormat,
dayFormat: format_dayFormat,
dayAbbrevFormat: format_dayAbbrevFormat,
quarter: vega_util["V" /* quarter */],
utcquarter: vega_util["Ha" /* utcquarter */],
warn: log_warn,
info: log_info,
debug: log_debug,
extent: vega_util["p" /* extent */],
inScope: inscope,
intersect: src_intersect,
clampRange: vega_util["j" /* clampRange */],
pinchDistance: pinchDistance,
pinchAngle: pinchAngle,
screen: screen,
containerSize: containerSize,
windowSize: windowSize,
bandspace: scale_bandspace,
setdata: data_setdata,
pathShape: shape_pathShape,
panLinear: vega_util["Q" /* panLinear */],
panLog: vega_util["R" /* panLog */],
panPow: vega_util["S" /* panPow */],
panSymlog: vega_util["T" /* panSymlog */],
zoomLinear: vega_util["La" /* zoomLinear */],
zoomLog: vega_util["Ma" /* zoomLog */],
zoomPow: vega_util["Na" /* zoomPow */],
zoomSymlog: vega_util["Oa" /* zoomSymlog */],
encode: src_encode,
modify: src_modify
};
const codegen_eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'], // event functions
codegen_eventPrefix = 'event.vega.', // event function prefix
codegen_thisPrefix = 'this.', // function context prefix
codegen_astVisitors = {}; // AST visitors for dependency analysis
// Build expression function registry
function codegen_buildFunctions(codegen) {
const fn = src_functions(codegen);
codegen_eventFunctions.forEach(name => fn[name] = codegen_eventPrefix + name);
for (let name in codegen_functionContext) { fn[name] = codegen_thisPrefix + name; }
return fn;
}
// Register an expression function
function codegen_expressionFunction(name, fn, visitor) {
if (arguments.length === 1) {
return codegen_functionContext[name];
}
// register with the functionContext
codegen_functionContext[name] = fn;
// if there is an astVisitor register that, too
if (visitor) codegen_astVisitors[name] = visitor;
// if the code generator has already been initialized,
// we need to also register the function with it
if (codegen_codeGenerator) codegen_codeGenerator.functions[name] = codegen_thisPrefix + name;
return this;
}
// register expression functions with ast visitors
codegen_expressionFunction('bandwidth', scale_bandwidth, visitors_scaleVisitor);
codegen_expressionFunction('copy', scale_copy, visitors_scaleVisitor);
codegen_expressionFunction('domain', scale_domain, visitors_scaleVisitor);
codegen_expressionFunction('range', scale_range, visitors_scaleVisitor);
codegen_expressionFunction('invert', scale_invert, visitors_scaleVisitor);
codegen_expressionFunction('scale', scale_scale, visitors_scaleVisitor);
codegen_expressionFunction('gradient', scale_gradient, visitors_scaleVisitor);
codegen_expressionFunction('geoArea', geo_geoArea, visitors_scaleVisitor);
codegen_expressionFunction('geoBounds', geo_geoBounds, visitors_scaleVisitor);
codegen_expressionFunction('geoCentroid', geo_geoCentroid, visitors_scaleVisitor);
codegen_expressionFunction('geoShape', shape_geoShape, visitors_scaleVisitor);
codegen_expressionFunction('indata', data_indata, visitors_indataVisitor);
codegen_expressionFunction('data', src_data_data, visitors_dataVisitor);
codegen_expressionFunction('treePath', tree_treePath, visitors_dataVisitor);
codegen_expressionFunction('treeAncestors', tree_treeAncestors, visitors_dataVisitor);
// register Vega-Lite selection functions
codegen_expressionFunction('vlSelectionTest', selectionTest_selectionTest, selectionVisitor_selectionVisitor);
codegen_expressionFunction('vlSelectionResolve', selectionResolve_selectionResolve, selectionVisitor_selectionVisitor);
// Export code generator and parameters
const codegen_codegenParams = {
blacklist: ['_'],
whitelist: ['datum', 'event', 'item'],
fieldvar: 'datum',
globalvar: function(id) { return '_[' + Object(vega_util["Z" /* stringValue */])(SignalPrefix + id) + ']'; },
functions: codegen_buildFunctions,
constants: src_constants,
visitors: codegen_astVisitors
};
var codegen_codeGenerator = src_codegen(codegen_codegenParams);
// CONCATENATED MODULE: ./node_modules/vega-functions/node_modules/d3-format/src/index.js
// CONCATENATED MODULE: ./node_modules/d3-time-format/src/index.js
// CONCATENATED MODULE: ./node_modules/vega-functions/index.js
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/expression.js
/**
* Parse an expression given the argument signature and body code.
*/
function expression_expression(args, code, ctx) {
// wrap code in return statement if expression does not terminate
if (code[code.length-1] !== ';') {
code = 'return(' + code + ');';
}
var fn = Function.apply(null, args.concat(code));
return ctx && ctx.functions ? fn.bind(ctx.functions) : fn;
}
/**
* Parse an expression used to update an operator value.
*/
function operatorExpression(code, ctx) {
return expression_expression(['_'], code, ctx);
}
/**
* Parse an expression provided as an operator parameter value.
*/
function parameterExpression(code, ctx) {
return expression_expression(['datum', '_'], code, ctx);
}
/**
* Parse an expression applied to an event stream.
*/
function eventExpression(code, ctx) {
return expression_expression(['event'], code, ctx);
}
/**
* Parse an expression used to handle an event-driven operator update.
*/
function handlerExpression(code, ctx) {
return expression_expression(['_', 'event'], code, ctx);
}
/**
* Parse an expression that performs visual encoding.
*/
function encodeExpression(code, ctx) {
return expression_expression(['item', '_'], code, ctx);
}
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/parameters.js
/**
* Parse a set of operator parameters.
*/
function parameters_parseParameters(spec, ctx, params) {
params = params || {};
var key, value;
for (key in spec) {
value = spec[key];
params[key] = Object(vega_util["A" /* isArray */])(value)
? value.map(function(v) { return parameters_parseParameter(v, ctx, params); })
: parameters_parseParameter(value, ctx, params);
}
return params;
}
/**
* Parse a single parameter.
*/
function parameters_parseParameter(spec, ctx, params) {
if (!spec || !Object(vega_util["F" /* isObject */])(spec)) return spec;
for (var i=0, n=parameters_PARSERS.length, p; i<n; ++i) {
p = parameters_PARSERS[i];
if (Object(vega_util["v" /* hasOwnProperty */])(spec, p.key)) {
return p.parse(spec, ctx, params);
}
}
return spec;
}
/** Reference parsers. */
var parameters_PARSERS = [
{key: '$ref', parse: parameters_getOperator},
{key: '$key', parse: parameters_getKey},
{key: '$expr', parse: parameters_getExpression},
{key: '$field', parse: parameters_getField},
{key: '$encode', parse: parameters_getEncode},
{key: '$compare', parse: parameters_getCompare},
{key: '$context', parse: parameters_getContext},
{key: '$subflow', parse: parameters_getSubflow},
{key: '$tupleid', parse: parameters_getTupleId}
];
/**
* Resolve an operator reference.
*/
function parameters_getOperator(_, ctx) {
return ctx.get(_.$ref) || Object(vega_util["n" /* error */])('Operator not defined: ' + _.$ref);
}
/**
* Resolve an expression reference.
*/
function parameters_getExpression(_, ctx, params) {
if (_.$params) { // parse expression parameters
parameters_parseParameters(_.$params, ctx, params);
}
var k = 'e:' + _.$expr + '_' + _.$name;
return ctx.fn[k]
|| (ctx.fn[k] = Object(vega_util["f" /* accessor */])(parameterExpression(_.$expr, ctx), _.$fields, _.$name));
}
/**
* Resolve a key accessor reference.
*/
function parameters_getKey(_, ctx) {
var k = 'k:' + _.$key + '_' + (!!_.$flat);
return ctx.fn[k] || (ctx.fn[k] = Object(vega_util["I" /* key */])(_.$key, _.$flat));
}
/**
* Resolve a field accessor reference.
*/
function parameters_getField(_, ctx) {
if (!_.$field) return null;
var k = 'f:' + _.$field + '_' + _.$name;
return ctx.fn[k] || (ctx.fn[k] = Object(vega_util["t" /* field */])(_.$field, _.$name));
}
/**
* Resolve a comparator function reference.
*/
function parameters_getCompare(_, ctx) {
var k = 'c:' + _.$compare + '_' + _.$order,
c = Object(vega_util["i" /* array */])(_.$compare).map(function(_) {
return (_ && _.$tupleid) ? tupleid : _;
});
return ctx.fn[k] || (ctx.fn[k] = Object(vega_util["k" /* compare */])(c, _.$order));
}
/**
* Resolve an encode operator reference.
*/
function parameters_getEncode(_, ctx) {
var spec = _.$encode,
encode = {}, name, enc;
for (name in spec) {
enc = spec[name];
encode[name] = Object(vega_util["f" /* accessor */])(encodeExpression(enc.$expr, ctx), enc.$fields);
encode[name].output = enc.$output;
}
return encode;
}
/**
* Resolve a context reference.
*/
function parameters_getContext(_, ctx) {
return ctx;
}
/**
* Resolve a recursive subflow specification.
*/
function parameters_getSubflow(_, ctx) {
var spec = _.$subflow;
return function(dataflow, key, parent) {
var subctx = src_dataflow(spec, ctx.fork()),
op = subctx.get(spec.operators[0].id),
p = subctx.signals.parent;
if (p) p.set(parent);
return op;
};
}
/**
* Resolve a tuple id reference.
*/
function parameters_getTupleId() {
return tupleid;
}
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/util.js
function canonicalType(type) {
return (type + '').toLowerCase();
}
function isOperator(type) {
return canonicalType(type) === 'operator';
}
function isCollect(type) {
return canonicalType(type) === 'collect';
}
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/operator.js
/**
* Parse a dataflow operator.
*/
/* harmony default export */ var src_operator = (function(spec, ctx) {
if (isOperator(spec.type) || !spec.type) {
ctx.operator(spec,
spec.update ? operatorExpression(spec.update, ctx) : null);
} else {
ctx.transform(spec, spec.type);
}
});
/**
* Parse and assign operator parameters.
*/
function operator_parseOperatorParameters(spec, ctx) {
if (spec.params) {
var op = ctx.get(spec.id);
if (!op) Object(vega_util["n" /* error */])('Invalid operator id: ' + spec.id);
ctx.dataflow.connect(op, op.parameters(
parameters_parseParameters(spec.params, ctx),
spec.react,
spec.initonly
));
}
}
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/stream.js
/**
* Parse an event stream specification.
*/
/* harmony default export */ var vega_runtime_src_stream = (function(spec, ctx) {
var filter = spec.filter != null ? eventExpression(spec.filter, ctx) : undefined,
stream = spec.stream != null ? ctx.get(spec.stream) : undefined,
args;
if (spec.source) {
stream = ctx.events(spec.source, spec.type, filter);
}
else if (spec.merge) {
args = spec.merge.map(ctx.get.bind(ctx));
stream = args[0].merge.apply(args[0], args.slice(1));
}
if (spec.between) {
args = spec.between.map(ctx.get.bind(ctx));
stream = stream.between(args[0], args[1]);
}
if (spec.filter) {
stream = stream.filter(filter);
}
if (spec.throttle != null) {
stream = stream.throttle(+spec.throttle);
}
if (spec.debounce != null) {
stream = stream.debounce(+spec.debounce);
}
if (stream == null) {
Object(vega_util["n" /* error */])('Invalid stream definition: ' + JSON.stringify(spec));
}
if (spec.consume) stream.consume(true);
ctx.stream(spec, stream);
});
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/update.js
/**
* Parse an event-driven operator update.
*/
/* harmony default export */ var src_update = (function(spec, ctx) {
var srcid = Object(vega_util["F" /* isObject */])(srcid = spec.source) ? srcid.$ref : srcid,
source = ctx.get(srcid),
target = null,
update = spec.update,
params = undefined;
if (!source) Object(vega_util["n" /* error */])('Source not defined: ' + spec.source);
if (spec.target && spec.target.$expr) {
target = eventExpression(spec.target.$expr, ctx);
} else {
target = ctx.get(spec.target);
}
if (update && update.$expr) {
if (update.$params) {
params = parameters_parseParameters(update.$params, ctx);
}
update = handlerExpression(update.$expr, ctx);
}
ctx.update(spec, source, target, update, params);
});
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/dataflow.js
/**
* Parse a serialized dataflow specification.
*/
/* harmony default export */ var src_dataflow = (function(spec, ctx) {
var operators = spec.operators || [];
// parse background
if (spec.background) {
ctx.background = spec.background;
}
// parse event configuration
if (spec.eventConfig) {
ctx.eventConfig = spec.eventConfig;
}
// parse operators
operators.forEach(function(entry) {
src_operator(entry, ctx);
});
// parse operator parameters
operators.forEach(function(entry) {
operator_parseOperatorParameters(entry, ctx);
});
// parse streams
(spec.streams || []).forEach(function(entry) {
vega_runtime_src_stream(entry, ctx);
});
// parse updates
(spec.updates || []).forEach(function(entry) {
src_update(entry, ctx);
});
return ctx.resolve();
});
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/state.js
var state_SKIP = {skip: true};
function state_getState(options) {
var ctx = this,
state = {};
if (options.signals) {
var signals = (state.signals = {});
Object.keys(ctx.signals).forEach(function(key) {
var op = ctx.signals[key];
if (options.signals(key, op)) {
signals[key] = op.value;
}
});
}
if (options.data) {
var data = (state.data = {});
Object.keys(ctx.data).forEach(function(key) {
var dataset = ctx.data[key];
if (options.data(key, dataset)) {
data[key] = dataset.input.value;
}
});
}
if (ctx.subcontext && options.recurse !== false) {
state.subcontext = ctx.subcontext.map(function(ctx) {
return ctx.getState(options);
});
}
return state;
}
function state_setState(state) {
var ctx = this,
df = ctx.dataflow,
data = state.data,
signals = state.signals;
Object.keys(signals || {}).forEach(function(key) {
df.update(ctx.signals[key], signals[key], state_SKIP);
});
Object.keys(data || {}).forEach(function(key) {
df.pulse(
ctx.data[key].input,
df.changeset().remove(vega_util["Ga" /* truthy */]).insert(data[key])
);
});
(state.subcontext || []).forEach(function(substate, i) {
var subctx = ctx.subcontext[i];
if (subctx) subctx.setState(substate);
});
}
// CONCATENATED MODULE: ./node_modules/vega-runtime/src/context.js
/**
* Context objects store the current parse state.
* Enables lookup of parsed operators, event streams, accessors, etc.
* Provides a 'fork' method for creating child contexts for subflows.
*/
/* harmony default export */ var src_context = (function(df, transforms, functions) {
return new context_Context(df, transforms, functions);
});
function context_Context(df, transforms, functions) {
this.dataflow = df;
this.transforms = transforms;
this.events = df.events.bind(df);
this.signals = {};
this.scales = {};
this.nodes = {};
this.data = {};
this.fn = {};
if (functions) {
this.functions = Object.create(functions);
this.functions.context = this;
}
}
function context_ContextFork(ctx) {
this.dataflow = ctx.dataflow;
this.transforms = ctx.transforms;
this.functions = ctx.functions;
this.events = ctx.events;
this.signals = Object.create(ctx.signals);
this.scales = Object.create(ctx.scales);
this.nodes = Object.create(ctx.nodes);
this.data = Object.create(ctx.data);
this.fn = Object.create(ctx.fn);
if (ctx.functions) {
this.functions = Object.create(ctx.functions);
this.functions.context = this;
}
}
context_Context.prototype = context_ContextFork.prototype = {
fork: function() {
var ctx = new context_ContextFork(this);
(this.subcontext || (this.subcontext = [])).push(ctx);
return ctx;
},
get: function(id) {
return this.nodes[id];
},
set: function(id, node) {
return this.nodes[id] = node;
},
add: function(spec, op) {
var ctx = this,
df = ctx.dataflow,
data;
ctx.set(spec.id, op);
if (isCollect(spec.type) && (data = spec.value)) {
if (data.$ingest) {
df.ingest(op, data.$ingest, data.$format);
} else if (data.$request) {
df.preload(op, data.$request, data.$format);
} else {
df.pulse(op, df.changeset().insert(data));
}
}
if (spec.root) {
ctx.root = op;
}
if (spec.parent) {
var p = ctx.get(spec.parent.$ref);
if (p) {
df.connect(p, [op]);
op.targets().add(p);
} else {
(ctx.unresolved = ctx.unresolved || []).push(function() {
p = ctx.get(spec.parent.$ref);
df.connect(p, [op]);
op.targets().add(p);
});
}
}
if (spec.signal) {
ctx.signals[spec.signal] = op;
}
if (spec.scale) {
ctx.scales[spec.scale] = op;
}
if (spec.data) {
for (var name in spec.data) {
data = ctx.data[name] || (ctx.data[name] = {});
spec.data[name].forEach(function(role) { data[role] = op; });
}
}
},
resolve: function() {
(this.unresolved || []).forEach(function(fn) { fn(); });
delete this.unresolved;
return this;
},
operator: function(spec, update) {
this.add(spec, this.dataflow.add(spec.value, update));
},
transform: function(spec, type) {
this.add(spec, this.dataflow.add(this.transforms[canonicalType(type)]));
},
stream: function(spec, stream) {
this.set(spec.id, stream);
},
update: function(spec, stream, target, update, params) {
this.dataflow.on(stream, target, update, params, spec.options);
},
getState: state_getState,
setState: state_setState
};
// CONCATENATED MODULE: ./node_modules/vega-runtime/index.js
// CONCATENATED MODULE: ./node_modules/vega-view/src/runtime.js
/* harmony default export */ var src_runtime = (function(view, spec, functions) {
var fn = functions || codegen_functionContext;
return src_dataflow(spec, src_context(view, register_transforms, fn));
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/scale.js
function src_scale_scale(name) {
var scales = this._runtime.scales;
if (!Object(vega_util["v" /* hasOwnProperty */])(scales, name)) {
Object(vega_util["n" /* error */])('Unrecognized scale or projection: ' + name);
}
return scales[name].value;
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/size.js
var Width = 'width',
Height = 'height',
size_Padding = 'padding',
size_Skip = {skip: true};
function size_viewWidth(view, width) {
var a = view.autosize(),
p = view.padding();
return width - (a && a.contains === size_Padding ? p.left + p.right : 0);
}
function size_viewHeight(view, height) {
var a = view.autosize(),
p = view.padding();
return height - (a && a.contains === size_Padding ? p.top + p.bottom : 0);
}
function initializeResize(view) {
var s = view._signals,
w = s[Width],
h = s[Height],
p = s[size_Padding];
function resetSize() {
view._autosize = view._resize = 1;
}
// respond to width signal
view._resizeWidth = view.add(null,
function(_) {
view._width = _.size;
view._viewWidth = size_viewWidth(view, _.size);
resetSize();
},
{size: w}
);
// respond to height signal
view._resizeHeight = view.add(null,
function(_) {
view._height = _.size;
view._viewHeight = size_viewHeight(view, _.size);
resetSize();
},
{size: h}
);
// respond to padding signal
var resizePadding = view.add(null, resetSize, {pad: p});
// set rank to run immediately after source signal
view._resizeWidth.rank = w.rank + 1;
view._resizeHeight.rank = h.rank + 1;
resizePadding.rank = p.rank + 1;
}
function resizeView(viewWidth, viewHeight, width, height, origin, auto) {
this.runAfter(function(view) {
var rerun = 0;
// reset autosize flag
view._autosize = 0;
// width value changed: update signal, skip resize op
if (view.width() !== width) {
rerun = 1;
view.signal(Width, width, size_Skip); // set width, skip update calc
view._resizeWidth.skip(true); // skip width resize handler
}
// height value changed: update signal, skip resize op
if (view.height() !== height) {
rerun = 1;
view.signal(Height, height, size_Skip); // set height, skip update calc
view._resizeHeight.skip(true); // skip height resize handler
}
// view width changed: update view property, set resize flag
if (view._viewWidth !== viewWidth) {
view._resize = 1;
view._viewWidth = viewWidth;
}
// view height changed: update view property, set resize flag
if (view._viewHeight !== viewHeight) {
view._resize = 1;
view._viewHeight = viewHeight;
}
// origin changed: update view property, set resize flag
if (view._origin[0] !== origin[0] || view._origin[1] !== origin[1]) {
view._resize = 1;
view._origin = origin;
}
// run dataflow on width/height signal change
if (rerun) view.run('enter');
if (auto) view.runAfter(v => v.resize());
}, false, 1);
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/state.js
/**
* Get the current view state, consisting of signal values and/or data sets.
* @param {object} [options] - Options flags indicating which state to export.
* If unspecified, all signals and data sets will be exported.
* @param {function(string, Operator):boolean} [options.signals] - Optional
* predicate function for testing if a signal should be included in the
* exported state. If unspecified, all signals will be included, except for
* those named 'parent' or those which refer to a Transform value.
* @param {function(string, object):boolean} [options.data] - Optional
* predicate function for testing if a data set's input should be included
* in the exported state. If unspecified, all data sets that have been
* explicitly modified will be included.
* @param {boolean} [options.recurse=true] - Flag indicating if the exported
* state should recursively include state from group mark sub-contexts.
* @return {object} - An object containing the exported state values.
*/
function src_state_getState(options) {
return this._runtime.getState(options || {
data: state_dataTest,
signals: state_signalTest,
recurse: true
});
}
function state_dataTest(name, data) {
return data.modified
&& Object(vega_util["A" /* isArray */])(data.input.value)
&& name.indexOf('_:vega:_');
}
function state_signalTest(name, op) {
return !(name === 'parent' || op instanceof register_transforms.proxy);
}
/**
* Sets the current view state and updates the view by invoking run.
* @param {object} state - A state object containing signal and/or
* data set values, following the format used by the getState method.
* @return {View} - This view instance.
*/
function src_state_setState(state) {
this.runAsync(null,
v => { v._trigger = false; v._runtime.setState(state); },
v => { v._trigger = true; }
);
return this;
}
// CONCATENATED MODULE: ./node_modules/d3-timer/src/interval.js
/* harmony default export */ var src_interval = (function(callback, delay, time) {
var t = new timer_Timer, total = delay;
if (delay == null) return t.restart(callback, delay, time), t;
delay = +delay, time = time == null ? now() : +time;
t.restart(function tick(elapsed) {
elapsed += total;
t.restart(tick, total += delay, time);
callback(elapsed);
}, delay, time);
return t;
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/timer.js
/* harmony default export */ var src_timer = (function(callback, delay) {
function tick(elapsed) {
callback({timestamp: Date.now(), elapsed: elapsed});
}
this._timers.push(src_interval(tick, delay));
});
// CONCATENATED MODULE: ./node_modules/vega-view/src/tooltip.js
/* harmony default export */ var src_tooltip = (function(handler, event, item, value) {
var el = handler.element();
if (el) el.setAttribute('title', tooltip_formatTooltip(value));
});
function tooltip_formatTooltip(value) {
return value == null ? ''
: Object(vega_util["A" /* isArray */])(value) ? tooltip_formatArray(value)
: Object(vega_util["F" /* isObject */])(value) && !Object(vega_util["C" /* isDate */])(value) ? tooltip_formatObject(value)
: value + '';
}
function tooltip_formatObject(obj) {
return Object.keys(obj).map(function(key) {
var v = obj[key];
return key + ': ' + (Object(vega_util["A" /* isArray */])(v) ? tooltip_formatArray(v) : tooltip_formatValue(v));
}).join('\n');
}
function tooltip_formatArray(value) {
return '[' + value.map(tooltip_formatValue).join(', ') + ']';
}
function tooltip_formatValue(value) {
return Object(vega_util["A" /* isArray */])(value) ? '[\u2026]'
: Object(vega_util["F" /* isObject */])(value) && !Object(vega_util["C" /* isDate */])(value) ? '{\u2026}'
: value;
}
// CONCATENATED MODULE: ./node_modules/vega-view/src/View.js
/**
* Create a new View instance from a Vega dataflow runtime specification.
* The generated View will not immediately be ready for display. Callers
* should also invoke the initialize method (e.g., to set the parent
* DOM element in browser-based deployment) and then invoke the run
* method to evaluate the dataflow graph. Rendering will automatically
* be peformed upon dataflow runs.
* @constructor
* @param {object} spec - The Vega dataflow runtime specification.
*/
function View_View(spec, options) {
var view = this;
options = options || {};
Dataflow_Dataflow.call(view);
if (options.loader) view.loader(options.loader);
if (options.logger) view.logger(options.logger);
if (options.logLevel != null) view.logLevel(options.logLevel);
view._el = null;
view._elBind = null;
view._renderType = options.renderer || modules_RenderType.Canvas;
view._scenegraph = new Scenegraph_Scenegraph();
var root = view._scenegraph.root;
// initialize renderer, handler and event management
view._renderer = null;
view._tooltip = options.tooltip || src_tooltip,
view._redraw = true;
view._handler = new CanvasHandler_CanvasHandler().scene(root);
view._preventDefault = false;
view._timers = [];
view._eventListeners = [];
view._resizeListeners = [];
// initialize event configuration
view._eventConfig = events_initializeEventConfig(spec.eventConfig);
// initialize dataflow graph
var ctx = src_runtime(view, spec, options.functions);
view._runtime = ctx;
view._signals = ctx.signals;
view._bind = (spec.bindings || []).map(function(_) {
return {
state: null,
param: Object(vega_util["o" /* extend */])({}, _)
};
});
// initialize scenegraph
if (ctx.root) ctx.root.set(root);
root.source = ctx.data.root.input;
view.pulse(
ctx.data.root.input,
view.changeset().insert(root.items)
);
// initialize view size
view._width = view.width();
view._height = view.height();
view._viewWidth = size_viewWidth(view, view._width);
view._viewHeight = size_viewHeight(view, view._height);
view._origin = [0, 0];
view._resize = 0;
view._autosize = 1;
initializeResize(view);
// initialize background color
src_background(view);
// initialize cursor
src_cursor(view);
// initialize view description
view.description(spec.description);
// initialize hover proessing, if requested
if (options.hover) view.hover();
// initialize DOM container(s) and renderer
if (options.container) view.initialize(options.container, options.bind);
}
var View_prototype = Object(vega_util["y" /* inherits */])(View_View, Dataflow_Dataflow);
// -- DATAFLOW / RENDERING ----
View_prototype.evaluate = async function(encode, prerun, postrun) {
// evaluate dataflow and prerun
await Dataflow_Dataflow.prototype.evaluate.call(this, encode, prerun);
// render as needed
if (this._redraw || this._resize) {
try {
if (this._renderer) {
if (this._resize) {
this._resize = 0;
resizeRenderer(this);
}
await this._renderer.renderAsync(this._scenegraph.root);
}
this._redraw = false;
} catch (e) {
this.error(e);
}
}
// evaluate postrun
if (postrun) asyncCallback(this, postrun);
return this;
};
View_prototype.dirty = function(item) {
this._redraw = true;
this._renderer && this._renderer.dirty(item);
};
// -- GET / SET ----
View_prototype.description = function(text) {
if (arguments.length) {
const desc = text != null ? (text + '') : null;
if (desc !== this._desc) ariaLabel(this._el, this._desc = desc);
return this;
}
return this._desc;
};
View_prototype.container = function() {
return this._el;
};
View_prototype.scenegraph = function() {
return this._scenegraph;
};
View_prototype.origin = function() {
return this._origin.slice();
};
function View_lookupSignal(view, name) {
return Object(vega_util["v" /* hasOwnProperty */])(view._signals, name)
? view._signals[name]
: Object(vega_util["n" /* error */])('Unrecognized signal name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
View_prototype.signal = function(name, value, options) {
var op = View_lookupSignal(this, name);
return arguments.length === 1
? op.value
: this.update(op, value, options);
};
View_prototype.width = function(_) {
return arguments.length ? this.signal('width', _) : this.signal('width');
};
View_prototype.height = function(_) {
return arguments.length ? this.signal('height', _) : this.signal('height');
};
View_prototype.padding = function(_) {
return arguments.length
? this.signal('padding', src_padding(_))
: src_padding(this.signal('padding'));
};
View_prototype.autosize = function(_) {
return arguments.length ? this.signal('autosize', _) : this.signal('autosize');
};
View_prototype.background = function(_) {
return arguments.length ? this.signal('background', _) : this.signal('background');
};
View_prototype.renderer = function(type) {
if (!arguments.length) return this._renderType;
if (!modules_renderModule(type)) Object(vega_util["n" /* error */])('Unrecognized renderer type: ' + type);
if (type !== this._renderType) {
this._renderType = type;
this._resetRenderer();
}
return this;
};
View_prototype.tooltip = function(handler) {
if (!arguments.length) return this._tooltip;
if (handler !== this._tooltip) {
this._tooltip = handler;
this._resetRenderer();
}
return this;
};
View_prototype.loader = function(loader) {
if (!arguments.length) return this._loader;
if (loader !== this._loader) {
Dataflow_Dataflow.prototype.loader.call(this, loader);
this._resetRenderer();
}
return this;
};
View_prototype.resize = function() {
// set flag to perform autosize
this._autosize = 1;
// touch autosize signal to ensure top-level ViewLayout runs
return this.touch(View_lookupSignal(this, 'autosize'));
};
View_prototype._resetRenderer = function() {
if (this._renderer) {
this._renderer = null;
this.initialize(this._el, this._elBind);
}
};
// -- SIZING ----
View_prototype._resizeView = resizeView;
// -- EVENT HANDLING ----
View_prototype.addEventListener = function(type, handler, options) {
var callback = handler;
if (!(options && options.trap === false)) {
// wrap callback in error handler
callback = trap(this, handler);
callback.raw = handler;
}
this._handler.on(type, callback);
return this;
};
View_prototype.removeEventListener = function(type, handler) {
var handlers = this._handler.handlers(type),
i = handlers.length, h, t;
// search registered handlers, remove if match found
while (--i >= 0) {
t = handlers[i].type;
h = handlers[i].handler;
if (type === t && (handler === h || handler === h.raw)) {
this._handler.off(t, h);
break;
}
}
return this;
};
View_prototype.addResizeListener = function(handler) {
var l = this._resizeListeners;
if (l.indexOf(handler) < 0) {
// add handler if it isn't already registered
// note: error trapping handled elsewhere, so
// no need to wrap handlers here
l.push(handler);
}
return this;
};
View_prototype.removeResizeListener = function(handler) {
var l = this._resizeListeners,
i = l.indexOf(handler);
if (i >= 0) {
l.splice(i, 1);
}
return this;
};
function View_findOperatorHandler(op, handler) {
var t = op._targets || [],
h = t.filter(function(op) {
var u = op._update;
return u && u.handler === handler;
});
return h.length ? h[0] : null;
}
function View_addOperatorListener(view, name, op, handler) {
var h = View_findOperatorHandler(op, handler);
if (!h) {
h = trap(this, function() { handler(name, op.value); });
h.handler = handler;
view.on(op, null, h);
}
return view;
}
function View_removeOperatorListener(view, op, handler) {
var h = View_findOperatorHandler(op, handler);
if (h) op._targets.remove(h);
return view;
}
View_prototype.addSignalListener = function(name, handler) {
return View_addOperatorListener(this, name, View_lookupSignal(this, name), handler);
};
View_prototype.removeSignalListener = function(name, handler) {
return View_removeOperatorListener(this, View_lookupSignal(this, name), handler);
};
View_prototype.addDataListener = function(name, handler) {
return View_addOperatorListener(this, name, data_dataref(this, name).values, handler);
};
View_prototype.removeDataListener = function(name, handler) {
return View_removeOperatorListener(this, data_dataref(this, name).values, handler);
};
View_prototype.preventDefault = function(_) {
if (arguments.length) {
this._preventDefault = _;
return this;
} else {
return this._preventDefault;
}
};
View_prototype.timer = src_timer;
View_prototype.events = events_events;
View_prototype.finalize = finalize;
View_prototype.hover = src_hover;
// -- DATA ----
View_prototype.data = data_data;
View_prototype.change = data_change;
View_prototype.insert = data_insert;
View_prototype.remove = data_remove;
// -- SCALES --
View_prototype.scale = src_scale_scale;
// -- INITIALIZATION ----
View_prototype.initialize = src_initialize;
// -- HEADLESS RENDERING ----
View_prototype.toImageURL = render_to_image_url;
View_prototype.toCanvas = render_to_canvas;
View_prototype.toSVG = render_to_svg;
// -- SAVE / RESTORE STATE ----
View_prototype.getState = src_state_getState;
View_prototype.setState = src_state_setState;
// CONCATENATED MODULE: ./node_modules/vega-view/index.js
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/autosize.js
/* harmony default export */ var parsers_autosize = (function(spec) {
return Object(vega_util["F" /* isObject */])(spec) ? spec : {type: spec || 'pad'};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/padding.js
const parsers_padding_number = _ => +_ || 0;
const parsers_padding_paddingObject = _ => ({top: _, bottom: _, left: _, right: _});
/* harmony default export */ var parsers_padding = (function(spec) {
return !Object(vega_util["F" /* isObject */])(spec) ? parsers_padding_paddingObject(parsers_padding_number(spec))
: spec.signal ? spec
: {
top: parsers_padding_number(spec.top),
bottom: parsers_padding_number(spec.bottom),
left: parsers_padding_number(spec.left),
right: parsers_padding_number(spec.right)
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/signal.js
var signal_OUTER = 'outer',
signal_OUTER_INVALID = ['value', 'update', 'init', 'react', 'bind'];
function signal_outerError(prefix, name) {
Object(vega_util["n" /* error */])(prefix + ' for "outer" push: ' + Object(vega_util["Z" /* stringValue */])(name));
}
/* harmony default export */ var parsers_signal = (function(signal, scope) {
var name = signal.name;
if (signal.push === signal_OUTER) {
// signal must already be defined, raise error if not
if (!scope.signals[name]) signal_outerError('No prior signal definition', name);
// signal push must not use properties reserved for standard definition
signal_OUTER_INVALID.forEach(function(prop) {
if (signal[prop] !== undefined) signal_outerError('Invalid property ', prop);
});
} else {
// define a new signal in the current scope
var op = scope.addSignal(name, signal.value);
if (signal.react === false) op.react = false;
if (signal.bind) scope.addBinding(name, signal.bind);
}
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/expression.js
/* harmony default export */ var parsers_expression = (function(expr, scope, preamble) {
var params = {}, ast, gen;
// parse the expression to an abstract syntax tree (ast)
try {
expr = Object(vega_util["H" /* isString */])(expr) ? expr : (Object(vega_util["Z" /* stringValue */])(expr) + '');
ast = parser(expr);
} catch (err) {
Object(vega_util["n" /* error */])('Expression parse error: ' + expr);
}
// analyze ast function calls for dependencies
ast.visit(function visitor(node) {
if (node.type !== CallExpression) return;
var name = node.callee.name,
visit = codegen_codegenParams.visitors[name];
if (visit) visit(name, node.arguments, scope, params);
});
// perform code generation
gen = codegen_codeGenerator(ast);
// collect signal dependencies
gen.globals.forEach(function(name) {
var signalName = SignalPrefix + name;
if (!Object(vega_util["v" /* hasOwnProperty */])(params, signalName) && scope.getSignal(name)) {
params[signalName] = scope.signalRef(name);
}
});
// return generated expression code and dependencies
return {
$expr: preamble ? preamble + 'return(' + gen.code + ');' : gen.code,
$fields: gen.fields,
$params: params
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/util.js
function util_Entry(type, value, params, parent) {
this.id = -1;
this.type = type;
this.value = value;
this.params = params;
if (parent) this.parent = parent;
}
function util_entry(type, value, params, parent) {
return new util_Entry(type, value, params, parent);
}
function util_operator(value, params) {
return util_entry('operator', value, params);
}
// -----
function util_ref(op) {
var ref = {$ref: op.id};
// if operator not yet registered, cache ref to resolve later
if (op.id < 0) (op.refs = op.refs || []).push(ref);
return ref;
}
var util_tupleidRef = {
$tupleid: 1,
toString: function() { return ':_tupleid_:'; }
};
function util_fieldRef(field, name) {
return name ? {$field: field, $name: name} : {$field: field};
}
var util_keyFieldRef = util_fieldRef('key');
function util_compareRef(fields, orders) {
return {$compare: fields, $order: orders};
}
function util_keyRef(fields, flat) {
var ref = {$key: fields};
if (flat) ref.$flat = true;
return ref;
}
// -----
var util_Ascending = 'ascending';
var util_Descending = 'descending';
function util_sortKey(sort) {
return !Object(vega_util["F" /* isObject */])(sort) ? ''
: (sort.order === util_Descending ? '-' : '+')
+ util_aggrField(sort.op, sort.field);
}
function util_aggrField(op, field) {
return (op && op.signal ? '$' + op.signal : op || '')
+ (op && field ? '_' : '')
+ (field && field.signal ? '$' + field.signal : field || '');
}
// -----
var util_Scope = 'scope';
var util_View = 'view';
function util_isSignal(_) {
return _ && _.signal;
}
function util_isExpr(_) {
return _ && _.expr;
}
function util_hasSignal(_) {
if (util_isSignal(_)) return true;
if (Object(vega_util["F" /* isObject */])(_)) for (var key in _) {
if (util_hasSignal(_[key])) return true;
}
return false;
}
function util_value(specValue, defaultValue) {
return specValue != null ? specValue : defaultValue;
}
function util_deref(v) {
return v && v.signal || v;
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/stream.js
var stream_Timer = 'timer';
function stream_parseStream(stream, scope) {
var method = stream.merge ? stream_mergeStream
: stream.stream ? stream_nestedStream
: stream.type ? stream_eventStream
: Object(vega_util["n" /* error */])('Invalid stream specification: ' + Object(vega_util["Z" /* stringValue */])(stream));
return method(stream, scope);
}
function stream_eventSource(source) {
return source === util_Scope ? util_View : (source || util_View);
}
function stream_mergeStream(stream, scope) {
var list = stream.merge.map(s => stream_parseStream(s, scope)),
entry = stream_streamParameters({merge: list}, stream, scope);
return scope.addStream(entry).id;
}
function stream_nestedStream(stream, scope) {
var id = stream_parseStream(stream.stream, scope),
entry = stream_streamParameters({stream: id}, stream, scope);
return scope.addStream(entry).id;
}
function stream_eventStream(stream, scope) {
var id, entry;
if (stream.type === stream_Timer) {
id = scope.event(stream_Timer, stream.throttle);
stream = {between: stream.between, filter: stream.filter};
} else {
id = scope.event(stream_eventSource(stream.source), stream.type);
}
entry = stream_streamParameters({stream: id}, stream, scope);
return Object.keys(entry).length === 1
? id
: scope.addStream(entry).id;
}
function stream_streamParameters(entry, stream, scope) {
var param = stream.between;
if (param) {
if (param.length !== 2) {
Object(vega_util["n" /* error */])('Stream "between" parameter must have 2 entries: ' + Object(vega_util["Z" /* stringValue */])(stream));
}
entry.between = [
stream_parseStream(param[0], scope),
stream_parseStream(param[1], scope)
];
}
param = stream.filter ? [].concat(stream.filter) : [];
if (stream.marktype || stream.markname || stream.markrole) {
// add filter for mark type, name and/or role
param.push(stream_filterMark(stream.marktype, stream.markname, stream.markrole));
}
if (stream.source === util_Scope) {
// add filter to limit events from sub-scope only
param.push('inScope(event.item)');
}
if (param.length) {
entry.filter = parsers_expression('(' + param.join(')&&(') + ')').$expr;
}
if ((param = stream.throttle) != null) {
entry.throttle = +param;
}
if ((param = stream.debounce) != null) {
entry.debounce = +param;
}
if (stream.consume) {
entry.consume = true;
}
return entry;
}
function stream_filterMark(type, name, role) {
var item = 'event.item';
return item
+ (type && type !== '*' ? '&&' + item + '.mark.marktype===\'' + type + '\'' : '')
+ (role ? '&&' + item + '.mark.role===\'' + role + '\'' : '')
+ (name ? '&&' + item + '.mark.name===\'' + name + '\'' : '');
}
// CONCATENATED MODULE: ./node_modules/vega-event-selector/src/event-selector.js
/**
* Parse an event selector string.
* Returns an array of event stream definitions.
*/
/* harmony default export */ var event_selector = (function(selector, source, marks) {
DEFAULT_SOURCE = source || event_selector_VIEW;
MARKS = marks || DEFAULT_MARKS;
return parseMerge(selector.trim()).map(parseSelector);
});
var event_selector_VIEW = 'view',
LBRACK = '[',
RBRACK = ']',
LBRACE = '{',
RBRACE = '}',
COLON = ':',
COMMA = ',',
NAME = '@',
GT = '>',
event_selector_ILLEGAL = /[[\]{}]/,
DEFAULT_SOURCE,
MARKS,
DEFAULT_MARKS = {
'*': 1,
arc: 1,
area: 1,
group: 1,
image: 1,
line: 1,
path: 1,
rect: 1,
rule: 1,
shape: 1,
symbol: 1,
text: 1,
trail: 1
};
function isMarkType(type) {
return MARKS[type];
}
function event_selector_find(s, i, endChar, pushChar, popChar) {
var count = 0,
n = s.length,
c;
for (; i<n; ++i) {
c = s[i];
if (!count && c === endChar) return i;
else if (popChar && popChar.indexOf(c) >= 0) --count;
else if (pushChar && pushChar.indexOf(c) >= 0) ++count;
}
return i;
}
function parseMerge(s) {
var output = [],
start = 0,
n = s.length,
i = 0;
while (i < n) {
i = event_selector_find(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE);
output.push(s.substring(start, i).trim());
start = ++i;
}
if (output.length === 0) {
throw 'Empty event selector: ' + s;
}
return output;
}
function parseSelector(s) {
return s[0] === '['
? parseBetween(s)
: event_selector_parseStream(s);
}
function parseBetween(s) {
var n = s.length,
i = 1,
b, stream;
i = event_selector_find(s, i, RBRACK, LBRACK, RBRACK);
if (i === n) {
throw 'Empty between selector: ' + s;
}
b = parseMerge(s.substring(1, i));
if (b.length !== 2) {
throw 'Between selector must have two elements: ' + s;
}
s = s.slice(i + 1).trim();
if (s[0] !== GT) {
throw 'Expected \'>\' after between selector: ' + s;
}
b = b.map(parseSelector);
stream = parseSelector(s.slice(1).trim());
if (stream.between) {
return {
between: b,
stream: stream
};
} else {
stream.between = b;
}
return stream;
}
function event_selector_parseStream(s) {
var stream = {source: DEFAULT_SOURCE},
source = [],
throttle = [0, 0],
markname = 0,
start = 0,
n = s.length,
i = 0, j,
filter;
// extract throttle from end
if (s[n-1] === RBRACE) {
i = s.lastIndexOf(LBRACE);
if (i >= 0) {
try {
throttle = parseThrottle(s.substring(i+1, n-1));
} catch (e) {
throw 'Invalid throttle specification: ' + s;
}
s = s.slice(0, i).trim();
n = s.length;
} else throw 'Unmatched right brace: ' + s;
i = 0;
}
if (!n) throw s;
// set name flag based on first char
if (s[0] === NAME) markname = ++i;
// extract first part of multi-part stream selector
j = event_selector_find(s, i, COLON);
if (j < n) {
source.push(s.substring(start, j).trim());
start = i = ++j;
}
// extract remaining part of stream selector
i = event_selector_find(s, i, LBRACK);
if (i === n) {
source.push(s.substring(start, n).trim());
} else {
source.push(s.substring(start, i).trim());
filter = [];
start = ++i;
if (start === n) throw 'Unmatched left bracket: ' + s;
}
// extract filters
while (i < n) {
i = event_selector_find(s, i, RBRACK);
if (i === n) throw 'Unmatched left bracket: ' + s;
filter.push(s.substring(start, i).trim());
if (i < n-1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s;
start = ++i;
}
// marshall event stream specification
if (!(n = source.length) || event_selector_ILLEGAL.test(source[n-1])) {
throw 'Invalid event selector: ' + s;
}
if (n > 1) {
stream.type = source[1];
if (markname) {
stream.markname = source[0].slice(1);
} else if (isMarkType(source[0])) {
stream.marktype = source[0];
} else {
stream.source = source[0];
}
} else {
stream.type = source[0];
}
if (stream.type.slice(-1) === '!') {
stream.consume = true;
stream.type = stream.type.slice(0, -1)
}
if (filter != null) stream.filter = filter;
if (throttle[0]) stream.throttle = throttle[0];
if (throttle[1]) stream.debounce = throttle[1];
return stream;
}
function parseThrottle(s) {
var a = s.split(COMMA);
if (!s.length || a.length > 2) throw s;
return a.map(function(_) {
var x = +_;
if (x !== x) throw s;
return x;
});
}
// CONCATENATED MODULE: ./node_modules/vega-event-selector/index.js
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/update.js
var update_preamble = 'var datum=event.item&&event.item.datum;';
/* harmony default export */ var parsers_update = (function(spec, scope, target) {
var events = spec.events,
update = spec.update,
encode = spec.encode,
sources = [],
entry = {target: target};
if (!events) {
Object(vega_util["n" /* error */])('Signal update missing events specification.');
}
// interpret as an event selector string
if (Object(vega_util["H" /* isString */])(events)) {
events = event_selector(events, scope.isSubscope() ? util_Scope : util_View);
}
// separate event streams from signal updates
events = Object(vega_util["i" /* array */])(events)
.filter(s => s.signal || s.scale ? (sources.push(s), 0) : 1);
// merge internal operator listeners
if (sources.length > 1) {
sources = [update_mergeSources(sources)];
}
// merge event streams, include as source
if (events.length) {
sources.push(events.length > 1 ? {merge: events} : events[0]);
}
if (encode != null) {
if (update) Object(vega_util["n" /* error */])('Signal encode and update are mutually exclusive.');
update = 'encode(item(),' + Object(vega_util["Z" /* stringValue */])(encode) + ')';
}
// resolve update value
entry.update = Object(vega_util["H" /* isString */])(update) ? parsers_expression(update, scope, update_preamble)
: update.expr != null ? parsers_expression(update.expr, scope, update_preamble)
: update.value != null ? update.value
: update.signal != null ? {
$expr: '_.value',
$params: {value: scope.signalRef(update.signal)}
}
: Object(vega_util["n" /* error */])('Invalid signal update specification.');
if (spec.force) {
entry.options = {force: true};
}
sources.forEach(function(source) {
scope.addUpdate(Object(vega_util["o" /* extend */])(update_streamSource(source, scope), entry));
});
});
function update_streamSource(stream, scope) {
return {
source: stream.signal ? scope.signalRef(stream.signal)
: stream.scale ? scope.scaleRef(stream.scale)
: stream_parseStream(stream, scope)
};
}
function update_mergeSources(sources) {
return {
signal: '['
+ sources.map(s => s.scale ? 'scale("' + s.scale + '")' : s.signal)
+ ']'
};
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/signal-updates.js
/* harmony default export */ var signal_updates = (function(signal, scope) {
var op = scope.getSignal(signal.name),
expr = signal.update;
if (signal.init) {
if (expr) {
Object(vega_util["n" /* error */])('Signals can not include both init and update expressions.');
} else {
expr = signal.init;
op.initonly = true;
}
}
if (expr) {
expr = parsers_expression(expr, scope);
op.update = expr.$expr;
op.params = expr.$params;
}
if (signal.on) {
signal.on.forEach(function(_) {
parsers_update(_, scope, op.id);
});
}
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/transforms.js
function transforms_transform(name) {
return function(params, value, parent) {
return util_entry(name, value, params || undefined, parent);
};
}
var transforms_Aggregate = transforms_transform('aggregate');
var transforms_AxisTicks = transforms_transform('axisticks');
var transforms_Bound = transforms_transform('bound');
var transforms_Collect = transforms_transform('collect');
var transforms_Compare = transforms_transform('compare');
var transforms_DataJoin = transforms_transform('datajoin');
var transforms_Encode = transforms_transform('encode');
var transforms_Expression = transforms_transform('expression');
var transforms_Extent = transforms_transform('extent');
var transforms_Facet = transforms_transform('facet');
var transforms_Field = transforms_transform('field');
var transforms_Key = transforms_transform('key');
var transforms_LegendEntries = transforms_transform('legendentries');
var transforms_Load = transforms_transform('load');
var transforms_Mark = transforms_transform('mark');
var transforms_MultiExtent = transforms_transform('multiextent');
var transforms_MultiValues = transforms_transform('multivalues');
var transforms_Overlap = transforms_transform('overlap');
var transforms_Params = transforms_transform('params');
var transforms_PreFacet = transforms_transform('prefacet');
var transforms_Projection = transforms_transform('projection');
var transforms_Proxy = transforms_transform('proxy');
var transforms_Relay = transforms_transform('relay');
var transforms_Render = transforms_transform('render');
var transforms_Scale = transforms_transform('scale');
var transforms_Sieve = transforms_transform('sieve');
var transforms_SortItems = transforms_transform('sortitems');
var transforms_ViewLayout = transforms_transform('viewlayout');
var transforms_Values = transforms_transform('values');
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/bandSpace.js
/* harmony default export */ var node_modules_vega_scale_src_scales_bandSpace = (function(count, paddingInner, paddingOuter) {
var space = count - paddingInner + paddingOuter * 2;
return count ? (space > 0 ? space : 1) : 0;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/types.js
const vega_scale_src_scales_types_Identity = 'identity';
const node_modules_vega_scale_src_scales_types_Linear = 'linear';
const vega_scale_src_scales_types_Log = 'log';
const vega_scale_src_scales_types_Pow = 'pow';
const vega_scale_src_scales_types_Sqrt = 'sqrt';
const vega_scale_src_scales_types_Symlog = 'symlog';
const vega_scale_src_scales_types_Time = 'time';
const vega_scale_src_scales_types_UTC = 'utc';
const vega_scale_src_scales_types_Sequential = 'sequential';
const vega_scale_src_scales_types_Diverging = 'diverging';
const node_modules_vega_scale_src_scales_types_Quantile = 'quantile';
const vega_scale_src_scales_types_Quantize = 'quantize';
const vega_scale_src_scales_types_Threshold = 'threshold';
const vega_scale_src_scales_types_Ordinal = 'ordinal';
const vega_scale_src_scales_types_Point = 'point';
const vega_scale_src_scales_types_Band = 'band';
const vega_scale_src_scales_types_BinOrdinal = 'bin-ordinal';
// categories
const src_scales_types_Continuous = 'continuous';
const src_scales_types_Discrete = 'discrete';
const src_scales_types_Discretizing = 'discretizing';
const src_scales_types_Interpolating = 'interpolating';
const src_scales_types_Temporal = 'temporal';
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/invertRange.js
/* harmony default export */ var node_modules_vega_scale_src_scales_invertRange = (function(scale) {
return function(_) {
var lo = _[0],
hi = _[1],
t;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
return [
scale.invert(lo),
scale.invert(hi)
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/invertRangeExtent.js
/* harmony default export */ var node_modules_vega_scale_src_scales_invertRangeExtent = (function(scale) {
return function(_) {
var range = scale.range(),
lo = _[0],
hi = _[1],
min = -1, max, t, i, n;
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
for (i=0, n=range.length; i<n; ++i) {
if (range[i] >= lo && range[i] <= hi) {
if (min < 0) min = i;
max = i;
}
}
if (min < 0) return undefined;
lo = scale.invertExtent(range[min]);
hi = scale.invertExtent(range[max]);
return [
lo[0] === undefined ? lo[1] : lo[0],
hi[1] === undefined ? hi[0] : hi[1]
];
}
});
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/scaleBand.js
function node_modules_vega_scale_src_scales_scaleBand_band() {
var scale = ordinal_ordinal().unknown(undefined),
domain = scale.domain,
ordinalRange = scale.range,
range = [0, 1],
step,
bandwidth,
round = false,
paddingInner = 0,
paddingOuter = 0,
align = 0.5;
delete scale.unknown;
function rescale() {
var n = domain().length,
reverse = range[1] < range[0],
start = range[reverse - 0],
stop = range[1 - reverse],
space = node_modules_vega_scale_src_scales_bandSpace(n, paddingInner, paddingOuter);
step = (stop - start) / (space || 1);
if (round) {
step = Math.floor(step);
}
start += (stop - start - step * (n - paddingInner)) * align;
bandwidth = step * (1 - paddingInner);
if (round) {
start = Math.round(start);
bandwidth = Math.round(bandwidth);
}
var values = src_range(n).map(function(i) { return start + step * i; });
return ordinalRange(reverse ? values.reverse() : values);
}
scale.domain = function(_) {
if (arguments.length) {
domain(_);
return rescale();
} else {
return domain();
}
};
scale.range = function(_) {
if (arguments.length) {
range = [+_[0], +_[1]];
return rescale();
} else {
return range.slice();
}
};
scale.rangeRound = function(_) {
range = [+_[0], +_[1]];
round = true;
return rescale();
};
scale.bandwidth = function() {
return bandwidth;
};
scale.step = function() {
return step;
};
scale.round = function(_) {
if (arguments.length) {
round = !!_;
return rescale();
} else {
return round;
}
};
scale.padding = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
paddingInner = paddingOuter;
return rescale();
} else {
return paddingInner;
}
};
scale.paddingInner = function(_) {
if (arguments.length) {
paddingInner = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingInner;
}
};
scale.paddingOuter = function(_) {
if (arguments.length) {
paddingOuter = Math.max(0, Math.min(1, _));
return rescale();
} else {
return paddingOuter;
}
};
scale.align = function(_) {
if (arguments.length) {
align = Math.max(0, Math.min(1, _));
return rescale();
} else {
return align;
}
};
scale.invertRange = function(_) {
// bail if range has null or undefined values
if (_[0] == null || _[1] == null) return;
var lo = +_[0],
hi = +_[1],
reverse = range[1] < range[0],
values = reverse ? ordinalRange().reverse() : ordinalRange(),
n = values.length - 1, a, b, t;
// bail if either range endpoint is invalid
if (lo !== lo || hi !== hi) return;
// order range inputs, bail if outside of scale range
if (hi < lo) {
t = lo;
lo = hi;
hi = t;
}
if (hi < values[0] || lo > range[1-reverse]) return;
// binary search to index into scale range
a = Math.max(0, bisect_bisectRight(values, lo) - 1);
b = lo===hi ? a : bisect_bisectRight(values, hi) - 1;
// increment index a if lo is within padding gap
if (lo - values[a] > bandwidth + 1e-10) ++a;
if (reverse) {
// map + swap
t = a;
a = n - b;
b = n - t;
}
return (a > b) ? undefined : domain().slice(a, b+1);
};
scale.invert = function(_) {
var value = scale.invertRange([_, _]);
return value ? value[0] : value;
};
scale.copy = function() {
return node_modules_vega_scale_src_scales_scaleBand_band()
.domain(domain())
.range(range)
.round(round)
.paddingInner(paddingInner)
.paddingOuter(paddingOuter)
.align(align);
};
return rescale();
}
function node_modules_vega_scale_src_scales_scaleBand_pointish(scale) {
var copy = scale.copy;
scale.padding = scale.paddingOuter;
delete scale.paddingInner;
scale.copy = function() {
return node_modules_vega_scale_src_scales_scaleBand_pointish(copy());
};
return scale;
}
function node_modules_vega_scale_src_scales_scaleBand_point() {
return node_modules_vega_scale_src_scales_scaleBand_pointish(node_modules_vega_scale_src_scales_scaleBand_band().paddingInner(1));
}
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/numbers.js
var node_modules_vega_scale_src_scales_numbers_map = Array.prototype.map;
function node_modules_vega_scale_src_scales_numbers_numbers(_) {
return node_modules_vega_scale_src_scales_numbers_map.call(_, function(x) { return +x; });
}
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/slice.js
var vega_scale_src_scales_slice_slice = Array.prototype.slice;
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales/scaleBinOrdinal.js
function node_modules_vega_scale_src_scales_scaleBinOrdinal_scaleBinOrdinal() {
var domain = [],
range = [];
function scale(x) {
return x == null || x !== x
? undefined
: range[(d3_array_src_bisect(domain, x) - 1) % range.length];
}
scale.domain = function(_) {
if (arguments.length) {
domain = node_modules_vega_scale_src_scales_numbers_numbers(_);
return scale;
} else {
return domain.slice();
}
};
scale.range = function(_) {
if (arguments.length) {
range = vega_scale_src_scales_slice_slice.call(_);
return scale;
} else {
return range.slice();
}
};
scale.tickFormat = function(count, specifier) {
return src_tickFormat(domain[0], Object(vega_util["U" /* peek */])(domain), count == null ? 10 : count, specifier);
};
scale.copy = function() {
return node_modules_vega_scale_src_scales_scaleBinOrdinal_scaleBinOrdinal().domain(scale.domain()).range(scale.range());
};
return scale;
}
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/scales.js
// scale registry
const vega_parser_node_modules_vega_scale_src_scales_scales = {};
/**
* Augment scales with their type and needed inverse methods.
*/
function vega_parser_node_modules_vega_scale_src_scales_create(type, constructor, metadata) {
const ctr = function scale() {
var s = constructor();
if (!s.invertRange) {
s.invertRange = s.invert ? node_modules_vega_scale_src_scales_invertRange(s)
: s.invertExtent ? node_modules_vega_scale_src_scales_invertRangeExtent(s)
: undefined;
}
s.type = type;
return s;
};
ctr.metadata = Object(vega_util["Da" /* toSet */])(Object(vega_util["i" /* array */])(metadata));
return ctr;
}
function vega_parser_node_modules_vega_scale_src_scales_scale(type, scale, metadata) {
if (arguments.length > 1) {
vega_parser_node_modules_vega_scale_src_scales_scales[type] = vega_parser_node_modules_vega_scale_src_scales_create(type, scale, metadata);
return this;
} else {
return node_modules_vega_scale_src_scales_isValidScaleType(type) ? vega_parser_node_modules_vega_scale_src_scales_scales[type] : undefined;
}
}
// identity scale
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Identity, identity_identity);
// continuous scales
vega_parser_node_modules_vega_scale_src_scales_scale(node_modules_vega_scale_src_scales_types_Linear, linear_linear, src_scales_types_Continuous);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Log, log_log, [src_scales_types_Continuous, vega_scale_src_scales_types_Log]);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Pow, pow_pow, src_scales_types_Continuous);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Sqrt, pow_sqrt, src_scales_types_Continuous);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Symlog, symlog_symlog, src_scales_types_Continuous);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Time, src_time, [src_scales_types_Continuous, src_scales_types_Temporal]);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_UTC, utcTime, [src_scales_types_Continuous, src_scales_types_Temporal]);
// sequential scales
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Sequential, sequential_sequential, [src_scales_types_Continuous, src_scales_types_Interpolating]); // backwards compat
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Sequential}-${node_modules_vega_scale_src_scales_types_Linear}`, sequential_sequential, [src_scales_types_Continuous, src_scales_types_Interpolating]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Sequential}-${vega_scale_src_scales_types_Log}`, sequential_sequentialLog, [src_scales_types_Continuous, src_scales_types_Interpolating, vega_scale_src_scales_types_Log]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Sequential}-${vega_scale_src_scales_types_Pow}`, sequential_sequentialPow, [src_scales_types_Continuous, src_scales_types_Interpolating]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Sequential}-${vega_scale_src_scales_types_Sqrt}`, sequential_sequentialSqrt, [src_scales_types_Continuous, src_scales_types_Interpolating]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Sequential}-${vega_scale_src_scales_types_Symlog}`, sequential_sequentialSymlog, [src_scales_types_Continuous, src_scales_types_Interpolating]);
// diverging scales
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Diverging}-${node_modules_vega_scale_src_scales_types_Linear}`, diverging_diverging, [src_scales_types_Continuous, src_scales_types_Interpolating]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Diverging}-${vega_scale_src_scales_types_Log}`, diverging_divergingLog, [src_scales_types_Continuous, src_scales_types_Interpolating, vega_scale_src_scales_types_Log]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Diverging}-${vega_scale_src_scales_types_Pow}`, diverging_divergingPow, [src_scales_types_Continuous, src_scales_types_Interpolating]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Diverging}-${vega_scale_src_scales_types_Sqrt}`, diverging_divergingSqrt, [src_scales_types_Continuous, src_scales_types_Interpolating]);
vega_parser_node_modules_vega_scale_src_scales_scale(`${vega_scale_src_scales_types_Diverging}-${vega_scale_src_scales_types_Symlog}`, diverging_divergingSymlog, [src_scales_types_Continuous, src_scales_types_Interpolating]);
// discretizing scales
vega_parser_node_modules_vega_scale_src_scales_scale(node_modules_vega_scale_src_scales_types_Quantile, src_quantile_quantile, [src_scales_types_Discretizing, node_modules_vega_scale_src_scales_types_Quantile]);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Quantize, quantize_quantize, src_scales_types_Discretizing);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Threshold, threshold_threshold, src_scales_types_Discretizing);
// discrete scales
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_BinOrdinal, node_modules_vega_scale_src_scales_scaleBinOrdinal_scaleBinOrdinal, [src_scales_types_Discrete, src_scales_types_Discretizing]);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Ordinal, ordinal_ordinal, src_scales_types_Discrete);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Band, node_modules_vega_scale_src_scales_scaleBand_band, src_scales_types_Discrete);
vega_parser_node_modules_vega_scale_src_scales_scale(vega_scale_src_scales_types_Point, node_modules_vega_scale_src_scales_scaleBand_point, src_scales_types_Discrete);
function node_modules_vega_scale_src_scales_isValidScaleType(type) {
return Object(vega_util["v" /* hasOwnProperty */])(vega_parser_node_modules_vega_scale_src_scales_scales, type);
}
function node_modules_vega_scale_src_scales_hasType(key, type) {
const s = vega_parser_node_modules_vega_scale_src_scales_scales[key];
return s && s.metadata[type];
}
function node_modules_vega_scale_src_scales_isContinuous(key) {
return node_modules_vega_scale_src_scales_hasType(key, src_scales_types_Continuous);
}
function node_modules_vega_scale_src_scales_isDiscrete(key) {
return node_modules_vega_scale_src_scales_hasType(key, src_scales_types_Discrete);
}
function node_modules_vega_scale_src_scales_isDiscretizing(key) {
return node_modules_vega_scale_src_scales_hasType(key, src_scales_types_Discretizing);
}
function node_modules_vega_scale_src_scales_isLogarithmic(key) {
return node_modules_vega_scale_src_scales_hasType(key, vega_scale_src_scales_types_Log);
}
function node_modules_vega_scale_src_scales_isTemporal(key) {
return node_modules_vega_scale_src_scales_hasType(key, src_scales_types_Temporal);
}
function node_modules_vega_scale_src_scales_isInterpolating(key) {
return node_modules_vega_scale_src_scales_hasType(key, src_scales_types_Interpolating);
}
function node_modules_vega_scale_src_scales_isQuantile(key) {
return node_modules_vega_scale_src_scales_hasType(key, node_modules_vega_scale_src_scales_types_Quantile);
}
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/interpolate.js
const vega_parser_node_modules_vega_scale_src_interpolate_scaleProps = ['clamp', 'base', 'constant', 'exponent'];
function vega_parser_node_modules_vega_scale_src_interpolate_interpolateRange(interpolator, range) {
var start = range[0],
span = Object(vega_util["U" /* peek */])(range) - start;
return function(i) { return interpolator(start + i * span); };
}
function vega_parser_node_modules_vega_scale_src_interpolate_interpolateColors(colors, type, gamma) {
return piecewise_piecewise(vega_parser_node_modules_vega_scale_src_interpolate_interpolate(type || 'rgb', gamma), colors);
}
function vega_parser_node_modules_vega_scale_src_interpolate_quantizeInterpolator(interpolator, count) {
var samples = new Array(count),
n = count + 1;
for (var i = 0; i < count;) samples[i] = interpolator(++i / n);
return samples;
}
function vega_parser_node_modules_vega_scale_src_interpolate_scaleCopy(scale) {
const t = scale.type,
s = scale.copy();
s.type = t;
return s;
}
function vega_parser_node_modules_vega_scale_src_interpolate_scaleFraction(scale, min, max) {
var delta = max - min, i, t, s;
if (!delta || !Number.isFinite(delta)) {
return Object(vega_util["l" /* constant */])(0.5);
} else {
i = (t = scale.type).indexOf('-');
t = i < 0 ? t : t.slice(i + 1);
s = vega_parser_node_modules_vega_scale_src_scales_scale(t)().domain([min, max]).range([0, 1]);
vega_parser_node_modules_vega_scale_src_interpolate_scaleProps.forEach(m => scale[m] ? s[m](scale[m]()) : 0);
return s;
}
}
function vega_parser_node_modules_vega_scale_src_interpolate_interpolate(type, gamma) {
var interp = d3_interpolate_src_namespaceObject[vega_parser_node_modules_vega_scale_src_interpolate_method(type)];
return (gamma != null && interp && interp.gamma)
? interp.gamma(gamma)
: interp;
}
function vega_parser_node_modules_vega_scale_src_interpolate_method(type) {
return 'interpolate' + type.toLowerCase()
.split('-')
.map(function(s) { return s[0].toUpperCase() + s.slice(1); })
.join('');
}
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/palettes.js
const vega_parser_node_modules_vega_scale_src_palettes_continuous = {
blues: 'cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90',
greens: 'd3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429',
greys: 'e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e',
oranges: 'fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303',
purples: 'e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c',
reds: 'fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13',
blueGreen: 'd5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429',
bluePurple: 'ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71',
greenBlue: 'd3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1',
orangeRed: 'fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403',
purpleBlue: 'dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281',
purpleBlueGreen: 'dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353',
purpleRed: 'dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a',
redPurple: 'fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174',
yellowGreen: 'e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034',
yellowOrangeBrown: 'feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204',
yellowOrangeRed: 'fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225',
blueOrange: '134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07',
brownBlueGreen: '704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147',
purpleGreen: '5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29',
purpleOrange: '4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07',
redBlue: '8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85',
redGrey: '8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434',
yellowGreenBlue: 'eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185',
redYellowBlue: 'a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695',
redYellowGreen: 'a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837',
pinkYellowGreen: '8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419',
spectral: '9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2',
viridis: '440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725',
magma: '0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf',
inferno: '0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4',
plasma: '0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921',
rainbow: '6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa',
sinebow: 'ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040',
browns: 'eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632',
tealBlues: 'bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985',
teals: 'bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667',
warmGreys: 'dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e',
goldGreen: 'f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36',
goldOrange: 'f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26',
goldRed: 'f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e',
lightGreyRed: 'efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b',
lightGreyTeal: 'e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc',
lightMulti: 'e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c',
lightOrange: 'f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b',
lightTealBlue: 'e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988',
darkBlue: '3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff',
darkGold: '3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff',
darkGreen: '3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa',
darkMulti: '3737371f5287197d8c29a86995ce3fffe800ffffff',
darkRed: '3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c'
};
const vega_parser_node_modules_vega_scale_src_palettes_discrete = {
category10: '1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf',
category20: '1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5',
category20b: '393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6',
category20c: '3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9',
tableau10: '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac',
tableau20: '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5',
accent: '7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666',
dark2: '1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666',
paired: 'a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928',
pastel1: 'fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2',
pastel2: 'b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc',
set1: 'e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999',
set2: '66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3',
set3: '8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f'
};
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/src/schemes.js
function vega_parser_node_modules_vega_scale_src_schemes_colors(palette) {
var n = palette.length / 6 | 0, c = new Array(n), i = 0;
while (i < n) c[i] = '#' + palette.slice(i * 6, ++i * 6);
return c;
}
function vega_parser_node_modules_vega_scale_src_schemes_apply(_, f) {
for (let k in _) vega_parser_node_modules_vega_scale_src_schemes_scheme(k, f(_[k]));
}
const vega_parser_node_modules_vega_scale_src_schemes_schemes = {};
vega_parser_node_modules_vega_scale_src_schemes_apply(vega_parser_node_modules_vega_scale_src_palettes_discrete, vega_parser_node_modules_vega_scale_src_schemes_colors);
vega_parser_node_modules_vega_scale_src_schemes_apply(vega_parser_node_modules_vega_scale_src_palettes_continuous, _ => vega_parser_node_modules_vega_scale_src_interpolate_interpolateColors(vega_parser_node_modules_vega_scale_src_schemes_colors(_)));
function vega_parser_node_modules_vega_scale_src_schemes_scheme(name, scheme) {
name = name && name.toLowerCase();
if (arguments.length > 1) {
vega_parser_node_modules_vega_scale_src_schemes_schemes[name] = scheme;
return this;
} else {
return vega_parser_node_modules_vega_scale_src_schemes_schemes[name];
}
}
// CONCATENATED MODULE: ./node_modules/vega-parser/node_modules/vega-scale/index.js
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/scale.js
var scale_FIELD_REF_ID = 0;
var scale_MULTIDOMAIN_SORT_OPS = {min: 'min', max: 'max', count: 'sum'};
function scale_initScale(spec, scope) {
var type = spec.type || 'linear';
if (!node_modules_vega_scale_src_scales_isValidScaleType(type)) {
Object(vega_util["n" /* error */])('Unrecognized scale type: ' + Object(vega_util["Z" /* stringValue */])(type));
}
scope.addScale(spec.name, {
type: type,
domain: undefined
});
}
function scale_parseScale(spec, scope) {
var params = scope.getScale(spec.name).params,
key;
params.domain = scale_parseScaleDomain(spec.domain, spec, scope);
if (spec.range != null) {
params.range = scale_parseScaleRange(spec, scope, params);
}
if (spec.interpolate != null) {
scale_parseScaleInterpolate(spec.interpolate, params);
}
if (spec.nice != null) {
params.nice = scale_parseScaleNice(spec.nice);
}
if (spec.bins != null) {
params.bins = scale_parseScaleBins(spec.bins, scope);
}
for (key in spec) {
if (Object(vega_util["v" /* hasOwnProperty */])(params, key) || key === 'name') continue;
params[key] = scale_parseLiteral(spec[key], scope);
}
}
function scale_parseLiteral(v, scope) {
return !Object(vega_util["F" /* isObject */])(v) ? v
: v.signal ? scope.signalRef(v.signal)
: Object(vega_util["n" /* error */])('Unsupported object: ' + Object(vega_util["Z" /* stringValue */])(v));
}
function scale_parseArray(v, scope) {
return v.signal
? scope.signalRef(v.signal)
: v.map(v => scale_parseLiteral(v, scope));
}
function scale_dataLookupError(name) {
Object(vega_util["n" /* error */])('Can not find data set: ' + Object(vega_util["Z" /* stringValue */])(name));
}
// -- SCALE DOMAIN ----
function scale_parseScaleDomain(domain, spec, scope) {
if (!domain) {
if (spec.domainMin != null || spec.domainMax != null) {
Object(vega_util["n" /* error */])('No scale domain defined for domainMin/domainMax to override.');
}
return; // default domain
}
return domain.signal ? scope.signalRef(domain.signal)
: (Object(vega_util["A" /* isArray */])(domain) ? scale_explicitDomain
: domain.fields ? scale_multipleDomain
: scale_singularDomain)(domain, spec, scope);
}
function scale_explicitDomain(domain, spec, scope) {
return domain.map(function(v) {
return scale_parseLiteral(v, scope);
});
}
function scale_singularDomain(domain, spec, scope) {
var data = scope.getData(domain.data);
if (!data) scale_dataLookupError(domain.data);
return node_modules_vega_scale_src_scales_isDiscrete(spec.type)
? data.valuesRef(scope, domain.field, scale_parseSort(domain.sort, false))
: node_modules_vega_scale_src_scales_isQuantile(spec.type) ? data.domainRef(scope, domain.field)
: data.extentRef(scope, domain.field);
}
function scale_multipleDomain(domain, spec, scope) {
var data = domain.data,
fields = domain.fields.reduce(function(dom, d) {
d = Object(vega_util["H" /* isString */])(d) ? {data: data, field: d}
: (Object(vega_util["A" /* isArray */])(d) || d.signal) ? scale_fieldRef(d, scope)
: d;
dom.push(d);
return dom;
}, []);
return (node_modules_vega_scale_src_scales_isDiscrete(spec.type) ? scale_ordinalMultipleDomain
: node_modules_vega_scale_src_scales_isQuantile(spec.type) ? scale_quantileMultipleDomain
: scale_numericMultipleDomain)(domain, scope, fields);
}
function scale_fieldRef(data, scope) {
var name = '_:vega:_' + (scale_FIELD_REF_ID++),
coll = transforms_Collect({});
if (Object(vega_util["A" /* isArray */])(data)) {
coll.value = {$ingest: data};
} else if (data.signal) {
var code = 'setdata(' + Object(vega_util["Z" /* stringValue */])(name) + ',' + data.signal + ')';
coll.params.input = scope.signalRef(code);
}
scope.addDataPipeline(name, [coll, transforms_Sieve({})]);
return {data: name, field: 'data'};
}
function scale_ordinalMultipleDomain(domain, scope, fields) {
var sort = scale_parseSort(domain.sort, true),
counts, p, a, c, v;
// get value counts for each domain field
counts = fields.map(function(f) {
var data = scope.getData(f.data);
if (!data) scale_dataLookupError(f.data);
return data.countsRef(scope, f.field, sort);
});
// aggregate the results from each domain field
p = {groupby: util_keyFieldRef, pulse: counts};
if (sort) {
a = sort.op || 'count';
v = sort.field ? util_aggrField(a, sort.field) : 'count';
p.ops = [scale_MULTIDOMAIN_SORT_OPS[a]];
p.fields = [scope.fieldRef(v)];
p.as = [v];
}
a = scope.add(transforms_Aggregate(p));
// collect aggregate output
c = scope.add(transforms_Collect({pulse: util_ref(a)}));
// extract values for combined domain
v = scope.add(transforms_Values({
field: util_keyFieldRef,
sort: scope.sortRef(sort),
pulse: util_ref(c)
}));
return util_ref(v);
}
function scale_parseSort(sort, multidomain) {
if (sort) {
if (!sort.field && !sort.op) {
if (Object(vega_util["F" /* isObject */])(sort)) sort.field = 'key';
else sort = {field: 'key'};
} else if (!sort.field && sort.op !== 'count') {
Object(vega_util["n" /* error */])('No field provided for sort aggregate op: ' + sort.op);
} else if (multidomain && sort.field) {
if (sort.op && !scale_MULTIDOMAIN_SORT_OPS[sort.op]) {
Object(vega_util["n" /* error */])('Multiple domain scales can not be sorted using ' + sort.op);
}
}
}
return sort;
}
function scale_quantileMultipleDomain(domain, scope, fields) {
// get value arrays for each domain field
var values = fields.map(function(f) {
var data = scope.getData(f.data);
if (!data) scale_dataLookupError(f.data);
return data.domainRef(scope, f.field);
});
// combine value arrays
return util_ref(scope.add(transforms_MultiValues({values: values})));
}
function scale_numericMultipleDomain(domain, scope, fields) {
// get extents for each domain field
var extents = fields.map(function(f) {
var data = scope.getData(f.data);
if (!data) scale_dataLookupError(f.data);
return data.extentRef(scope, f.field);
});
// combine extents
return util_ref(scope.add(transforms_MultiExtent({extents: extents})));
}
// -- SCALE BINS -----
function scale_parseScaleBins(v, scope) {
return v.signal || Object(vega_util["A" /* isArray */])(v)
? scale_parseArray(v, scope)
: scope.objectProperty(v);
}
// -- SCALE NICE -----
function scale_parseScaleNice(nice) {
return Object(vega_util["F" /* isObject */])(nice)
? {
interval: scale_parseLiteral(nice.interval),
step: scale_parseLiteral(nice.step)
}
: scale_parseLiteral(nice);
}
// -- SCALE INTERPOLATION -----
function scale_parseScaleInterpolate(interpolate, params) {
params.interpolate = scale_parseLiteral(interpolate.type || interpolate);
if (interpolate.gamma != null) {
params.interpolateGamma = scale_parseLiteral(interpolate.gamma);
}
}
// -- SCALE RANGE -----
function scale_parseScaleRange(spec, scope, params) {
var range = spec.range,
config = scope.config.range;
if (range.signal) {
return scope.signalRef(range.signal);
} else if (Object(vega_util["H" /* isString */])(range)) {
if (config && Object(vega_util["v" /* hasOwnProperty */])(config, range)) {
spec = Object(vega_util["o" /* extend */])({}, spec, {range: config[range]});
return scale_parseScaleRange(spec, scope, params);
} else if (range === 'width') {
range = [0, {signal: 'width'}]
} else if (range === 'height') {
range = node_modules_vega_scale_src_scales_isDiscrete(spec.type)
? [0, {signal: 'height'}]
: [{signal: 'height'}, 0]
} else {
Object(vega_util["n" /* error */])('Unrecognized scale range value: ' + Object(vega_util["Z" /* stringValue */])(range));
}
} else if (range.scheme) {
params.scheme = Object(vega_util["A" /* isArray */])(range.scheme)
? scale_parseArray(range.scheme, scope)
: scale_parseLiteral(range.scheme, scope);
if (range.extent) params.schemeExtent = scale_parseArray(range.extent, scope);
if (range.count) params.schemeCount = scale_parseLiteral(range.count, scope);
return;
} else if (range.step) {
params.rangeStep = scale_parseLiteral(range.step, scope);
return;
} else if (node_modules_vega_scale_src_scales_isDiscrete(spec.type) && !Object(vega_util["A" /* isArray */])(range)) {
return scale_parseScaleDomain(range, spec, scope);
} else if (!Object(vega_util["A" /* isArray */])(range)) {
Object(vega_util["n" /* error */])('Unsupported range type: ' + Object(vega_util["Z" /* stringValue */])(range));
}
return range.map(v => (Object(vega_util["A" /* isArray */])(v) ? scale_parseArray : scale_parseLiteral)(v, scope));
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/projection.js
/* harmony default export */ var parsers_projection = (function(proj, scope) {
var config = scope.config.projection || {},
params = {};
for (var name in proj) {
if (name === 'name') continue;
params[name] = projection_parseParameter(proj[name], name, scope);
}
// apply projection defaults from config
for (name in config) {
if (params[name] == null) {
params[name] = projection_parseParameter(config[name], name, scope);
}
}
scope.addProjection(proj.name, params);
});
function projection_parseParameter(_, name, scope) {
return Object(vega_util["A" /* isArray */])(_) ? _.map(function(_) { return projection_parseParameter(_, name, scope); })
: !Object(vega_util["F" /* isObject */])(_) ? _
: _.signal ? scope.signalRef(_.signal)
: name === 'fit' ? _
: Object(vega_util["n" /* error */])('Unsupported parameter object: ' + Object(vega_util["Z" /* stringValue */])(_));
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/constants.js
const constants_Top = 'top';
const constants_Left = 'left';
const constants_Right = 'right';
const constants_Bottom = 'bottom';
const constants_Center = 'center';
const Vertical = 'vertical';
const constants_Start = 'start';
const constants_Middle = 'middle';
const constants_End = 'end';
const Index = 'index';
const Label = 'label';
const Offset = 'offset';
const Perc = 'perc';
const Perc2 = 'perc2';
const Size = 'size';
const Value = 'value';
const GuideLabelStyle = 'guide-label';
const GuideTitleStyle = 'guide-title';
const GroupTitleStyle = 'group-title';
const GroupSubtitleStyle = 'group-subtitle';
const constants_Symbols = 'symbol';
const constants_Gradient = 'gradient';
const constants_Discrete = 'discrete';
// Encoding channels supported by legends
// In priority order of 'canonical' scale
const LegendScales = [
'size',
'shape',
'fill',
'stroke',
'strokeWidth',
'strokeDash',
'opacity'
];
const constants_Skip = {
name: 1,
style: 1,
interactive: 1
};
const constants_zero = {value: 0};
const constants_one = {value: 1};
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/adjust-spatial.js
var adjust_spatial_Skip = Object(vega_util["Da" /* toSet */])(['rule']),
adjust_spatial_Swap = Object(vega_util["Da" /* toSet */])(['group', 'image', 'rect']);
/* harmony default export */ var adjust_spatial = (function(encode, marktype) {
var code = '';
if (adjust_spatial_Skip[marktype]) return code;
if (encode.x2) {
if (encode.x) {
if (adjust_spatial_Swap[marktype]) {
code += 'if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;';
}
code += 'o.width=o.x2-o.x;';
} else {
code += 'o.x=o.x2-(o.width||0);';
}
}
if (encode.xc) {
code += 'o.x=o.xc-(o.width||0)/2;';
}
if (encode.y2) {
if (encode.y) {
if (adjust_spatial_Swap[marktype]) {
code += 'if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;';
}
code += 'o.height=o.y2-o.y;';
} else {
code += 'o.y=o.y2-(o.height||0);';
}
}
if (encode.yc) {
code += 'o.y=o.yc-(o.height||0)/2;';
}
return code;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/color.js
/* harmony default export */ var encode_color = (function(enc, scope, params, fields) {
function color(type, x, y, z) {
var a = encode_entry(null, x, scope, params, fields),
b = encode_entry(null, y, scope, params, fields),
c = encode_entry(null, z, scope, params, fields);
return 'this.' + type + '(' + [a, b, c].join(',') + ').toString()';
}
return (enc.c) ? color('hcl', enc.h, enc.c, enc.l)
: (enc.h || enc.s) ? color('hsl', enc.h, enc.s, enc.l)
: (enc.l || enc.a) ? color('lab', enc.l, enc.a, enc.b)
: (enc.r || enc.g || enc.b) ? color('rgb', enc.r, enc.g, enc.b)
: null;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/expression.js
/* harmony default export */ var encode_expression = (function(code, scope, params, fields) {
var expr = parsers_expression(code, scope);
expr.$fields.forEach(function(name) { fields[name] = 1; });
Object(vega_util["o" /* extend */])(params, expr.$params);
return expr.$expr;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/field.js
/* harmony default export */ var encode_field = (function(ref, scope, params, fields) {
return field_resolve(Object(vega_util["F" /* isObject */])(ref) ? ref : {datum: ref}, scope, params, fields);
});
function field_resolve(ref, scope, params, fields) {
var object, level, field;
if (ref.signal) {
object = 'datum';
field = encode_expression(ref.signal, scope, params, fields);
} else if (ref.group || ref.parent) {
level = Math.max(1, ref.level || 1);
object = 'item';
while (level-- > 0) {
object += '.mark.group';
}
if (ref.parent) {
field = ref.parent;
object += '.datum';
} else {
field = ref.group;
}
} else if (ref.datum) {
object = 'datum';
field = ref.datum;
} else {
Object(vega_util["n" /* error */])('Invalid field reference: ' + Object(vega_util["Z" /* stringValue */])(ref));
}
if (!ref.signal) {
if (Object(vega_util["H" /* isString */])(field)) {
fields[field] = 1; // TODO review field tracking?
field = Object(vega_util["Y" /* splitAccessPath */])(field).map(vega_util["Z" /* stringValue */]).join('][');
} else {
field = field_resolve(field, scope, params, fields);
}
}
return object + '[' + field + ']';
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/property.js
/* harmony default export */ var encode_property = (function(property, scope, params, fields) {
return Object(vega_util["F" /* isObject */])(property)
? '(' + encode_entry(null, property, scope, params, fields) + ')'
: property;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/scale.js
/* harmony default export */ var encode_scale = (function(enc, value, scope, params, fields) {
var scale = encode_scale_getScale(enc.scale, scope, params, fields),
interp, func, flag;
if (enc.range != null) {
// pull value from scale range
interp = +enc.range;
func = scale + '.range()';
value = (interp === 0) ? (func + '[0]')
: '($=' + func + ',' + ((interp === 1) ? '$[$.length-1]'
: '$[0]+' + interp + '*($[$.length-1]-$[0])') + ')';
} else {
// run value through scale and/or pull scale bandwidth
if (value !== undefined) value = scale + '(' + value + ')';
if (enc.band && (flag = scale_hasBandwidth(enc.scale, scope))) {
func = scale + '.bandwidth';
if (enc.band.signal) {
interp = func + '()*' + encode_property(enc.band, scope, params, fields);
} else {
interp = +enc.band;
interp = func + '()' + (interp===1 ? '' : '*' + interp);
}
// if we don't know the scale type, check for bandwidth
if (flag < 0) interp = '(' + func + '?' + interp + ':0)';
value = (value ? value + '+' : '') + interp;
if (enc.extra) {
// include logic to handle extraneous elements
value = '(datum.extra?' + scale + '(datum.extra.value):' + value + ')';
}
}
if (value == null) value = '0';
}
return value;
});
function scale_hasBandwidth(name, scope) {
if (!Object(vega_util["H" /* isString */])(name)) return -1;
var type = scope.scaleType(name);
return type === 'band' || type === 'point' ? 1 : 0;
}
function encode_scale_getScale(name, scope, params, fields) {
var scaleName;
if (Object(vega_util["H" /* isString */])(name)) {
// direct scale lookup; add scale as parameter
scaleName = ScalePrefix + name;
if (!Object(vega_util["v" /* hasOwnProperty */])(params, scaleName)) {
params[scaleName] = scope.scaleRef(name);
}
scaleName = Object(vega_util["Z" /* stringValue */])(scaleName);
} else {
// indirect scale lookup; add all scales as parameters
for (scaleName in scope.scales) {
params[ScalePrefix + scaleName] = scope.scaleRef(scaleName);
}
scaleName = Object(vega_util["Z" /* stringValue */])(ScalePrefix) + '+'
+ (name.signal
? '(' + encode_expression(name.signal, scope, params, fields) + ')'
: encode_field(name, scope, params, fields));
}
return '_[' + scaleName + ']';
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/gradient.js
/* harmony default export */ var encode_gradient = (function(enc, scope, params, fields) {
return 'this.gradient('
+ encode_scale_getScale(enc.gradient, scope, params, fields)
+ ',' + Object(vega_util["Z" /* stringValue */])(enc.start)
+ ',' + Object(vega_util["Z" /* stringValue */])(enc.stop)
+ ',' + Object(vega_util["Z" /* stringValue */])(enc.count)
+ ')';
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/entry.js
/* harmony default export */ var encode_entry = (function(channel, enc, scope, params, fields) {
if (enc.gradient != null) {
return encode_gradient(enc, scope, params, fields);
}
var value = enc.signal ? encode_expression(enc.signal, scope, params, fields)
: enc.color ? encode_color(enc.color, scope, params, fields)
: enc.field != null ? encode_field(enc.field, scope, params, fields)
: enc.value !== undefined ? Object(vega_util["Z" /* stringValue */])(enc.value)
: undefined;
if (enc.scale != null) {
value = encode_scale(enc, value, scope, params, fields);
}
if (value === undefined) {
value = null;
}
if (enc.exponent != null) {
value = 'Math.pow(' + value + ','
+ encode_property(enc.exponent, scope, params, fields) + ')';
}
if (enc.mult != null) {
value += '*' + encode_property(enc.mult, scope, params, fields);
}
if (enc.offset != null) {
value += '+' + encode_property(enc.offset, scope, params, fields);
}
if (enc.round) {
value = 'Math.round(' + value + ')';
}
return value;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/set.js
/* harmony default export */ var encode_set = (function(obj, key, value) {
const o = obj + '[' + Object(vega_util["Z" /* stringValue */])(key) + ']';
return `$=${value};if(${o}!==$)${o}=$,m=1;`;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/rule.js
/* harmony default export */ var encode_rule = (function(channel, rules, scope, params, fields) {
var code = '';
rules.forEach(function(rule) {
var value = encode_entry(channel, rule, scope, params, fields);
code += rule.test
? encode_expression(rule.test, scope, params, fields) + '?' + value + ':'
: value;
});
// if no else clause, terminate with null (vega/vega#1366)
if (Object(vega_util["U" /* peek */])(code) === ':') {
code += 'null';
}
return encode_set('o', channel, code);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode.js
function encode_parseEncode(encode, marktype, params, scope) {
var fields = {},
code = 'var o=item,datum=o.datum,m=0,$;',
channel, enc, value;
for (channel in encode) {
enc = encode[channel];
if (Object(vega_util["A" /* isArray */])(enc)) { // rule
code += encode_rule(channel, enc, scope, params, fields);
} else {
value = encode_entry(channel, enc, scope, params, fields);
code += encode_set('o', channel, value);
}
}
code += adjust_spatial(encode, marktype);
code += 'return m;';
return {
$expr: code,
$fields: Object.keys(fields),
$output: Object.keys(encode)
};
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/roles.js
var MarkRole = 'mark';
var roles_FrameRole = 'frame';
var roles_ScopeRole = 'scope';
var roles_AxisRole = 'axis';
var AxisDomainRole = 'axis-domain';
var AxisGridRole = 'axis-grid';
var AxisLabelRole = 'axis-label';
var AxisTickRole = 'axis-tick';
var AxisTitleRole = 'axis-title';
var roles_LegendRole = 'legend';
var LegendBandRole = 'legend-band';
var LegendEntryRole = 'legend-entry';
var LegendGradientRole = 'legend-gradient';
var LegendLabelRole = 'legend-label';
var LegendSymbolRole = 'legend-symbol';
var LegendTitleRole = 'legend-title';
var roles_TitleRole = 'title';
var TitleTextRole = 'title-text';
var TitleSubtitleRole = 'title-subtitle';
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/encode/encode-util.js
function encode_util_encoder(_) {
return Object(vega_util["F" /* isObject */])(_) && !Object(vega_util["A" /* isArray */])(_) ? Object(vega_util["o" /* extend */])({}, _) : {value: _};
}
function encode_util_addEncode(object, name, value, set) {
if (value != null) {
// Always assign signal to update, even if the signal is from the enter block
if (Object(vega_util["F" /* isObject */])(value) && !Object(vega_util["A" /* isArray */])(value)) {
object.update[name] = value;
} else {
object[set || 'enter'][name] = {value: value};
}
return 1;
} else {
return 0;
}
}
function encode_util_addEncoders(object, enter, update) {
for (let name in enter) {
encode_util_addEncode(object, name, enter[name]);
}
for (let name in update) {
encode_util_addEncode(object, name, update[name], 'update');
}
}
function encode_util_extendEncode(encode, extra, skip) {
for (var name in extra) {
if (skip && Object(vega_util["v" /* hasOwnProperty */])(skip, name)) continue;
encode[name] = Object(vega_util["o" /* extend */])(encode[name] || {}, extra[name]);
}
return encode;
}
function encode_util_encoders(encode, type, role, style, scope, params) {
var enc, key;
params = params || {};
params.encoders = {$encode: (enc = {})};
encode = encode_util_applyDefaults(encode, type, role, style, scope.config);
for (key in encode) {
enc[key] = encode_parseEncode(encode[key], type, params, scope);
}
return params;
}
function encode_util_applyDefaults(encode, type, role, style, config) {
var defaults = {}, enter = {}, update, key, skip, props;
// if text mark, apply global lineBreak settings (#2370)
key = 'lineBreak';
if (type === 'text' && config[key] != null && !encode_util_has(key, encode)) {
encode_util_applyDefault(defaults, key, config[key]);
}
// ignore legend and axis roles
if (role == 'legend' || String(role).startsWith('axis')) {
role = null;
}
// resolve mark config
props = role === roles_FrameRole ? config.group
: (role === MarkRole) ? Object(vega_util["o" /* extend */])({}, config.mark, config[type])
: null;
for (key in props) {
// do not apply defaults if relevant fields are defined
skip = encode_util_has(key, encode)
|| (key === 'fill' || key === 'stroke')
&& (encode_util_has('fill', encode) || encode_util_has('stroke', encode));
if (!skip) encode_util_applyDefault(defaults, key, props[key]);
}
// resolve styles, apply with increasing precedence
Object(vega_util["i" /* array */])(style).forEach(function(name) {
var props = config.style && config.style[name];
for (var key in props) {
if (!encode_util_has(key, encode)) {
encode_util_applyDefault(defaults, key, props[key]);
}
}
});
encode = Object(vega_util["o" /* extend */])({}, encode); // defensive copy
for (key in defaults) {
props = defaults[key];
if (props.signal) {
(update = update || {})[key] = props;
} else {
enter[key] = props;
}
}
encode.enter = Object(vega_util["o" /* extend */])(enter, encode.enter);
if (update) encode.update = Object(vega_util["o" /* extend */])(update, encode.update);
return encode;
}
function encode_util_applyDefault(defaults, key, value) {
defaults[key] = value && value.signal
? {signal: value.signal}
: {value: value}
}
function encode_util_has(key, encode) {
return encode && (
(encode.enter && encode.enter[key]) ||
(encode.update && encode.update[key])
);
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/guide-mark.js
/* harmony default export */ var guide_mark = (function(type, role, style, key, dataRef, encode, extras) {
return {
type: type,
name: extras ? extras.name : undefined,
role: role,
style: (extras && extras.style) || style,
key: key,
from: dataRef,
interactive: !!(extras && extras.interactive),
encode: encode_util_extendEncode(encode, extras, constants_Skip)
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/guide-util.js
function guide_util_lookup(spec, config) {
const _ = (name, dflt) => util_value(spec[name], util_value(config[name], dflt));
_.isVertical = s => Vertical === util_value(
spec.direction,
config.direction || (s ? config.symbolDirection : config.gradientDirection)
);
_.gradientLength = () => util_value(
spec.gradientLength,
config.gradientLength || config.gradientWidth
);
_.gradientThickness = () => util_value(
spec.gradientThickness,
config.gradientThickness || config.gradientHeight
);
_.entryColumns = () => util_value(
spec.columns,
util_value(config.columns, +_.isVertical(true))
);
return _;
}
function guide_util_getEncoding(name, encode) {
var v = encode && (
(encode.update && encode.update[name]) ||
(encode.enter && encode.enter[name])
);
return v && v.signal ? v : v ? v.value : null;
}
function guide_util_getStyle(name, scope, style) {
var s = scope.config.style[style];
return s && s[name];
}
function guide_util_anchorExpr(s, e, m) {
return `item.anchor === "${constants_Start}" ? ${s} : item.anchor === "${constants_End}" ? ${e} : ${m}`;
}
const guide_util_alignExpr = guide_util_anchorExpr(
Object(vega_util["Z" /* stringValue */])(constants_Left),
Object(vega_util["Z" /* stringValue */])(constants_Right),
Object(vega_util["Z" /* stringValue */])(constants_Center)
);
function guide_util_tickBand(_) {
let v = _('tickBand'),
offset = _('tickOffset'),
band, extra;
if (!v) {
// if no tick band entry, fall back on other properties
band = _('bandPosition');
extra = _('tickExtra');
} else if (v.signal) {
// if signal, augment code to interpret values
band = {signal: `(${v.signal})==='extent'?1:0.5`};
extra = {signal: `(${v.signal})==='extent'?true:false`};
if (!Object(vega_util["F" /* isObject */])(offset)) {
offset = {signal: `(${v.signal})==='extent'?0:${offset}`};
}
} else if (v === 'extent') {
// if constant, simply set values
band = 1;
extra = true;
offset = 0;
} else {
band = 0.5;
extra = false;
}
return {extra, band, offset};
}
function guide_util_extendOffset(value, offset) {
return !offset ? value
: !value ? offset
: !Object(vega_util["F" /* isObject */])(value) ? { value, offset }
: { ...value, offset: guide_util_extendOffset(value.offset, offset) };
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/marktypes.js
var GroupMark = 'group';
var RectMark = 'rect';
var RuleMark = 'rule';
var SymbolMark = 'symbol';
var TextMark = 'text';
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/legend-gradient.js
/* harmony default export */ var legend_gradient = (function(spec, scale, config, userEncode) {
var _ = guide_util_lookup(spec, config),
vertical = _.isVertical(),
thickness = _.gradientThickness(),
length = _.gradientLength(),
encode, enter, start, stop, width, height;
if (vertical) {
start = [0, 1];
stop = [0, 0];
width = thickness;
height = length;
} else {
start = [0, 0];
stop = [1, 0];
width = length;
height = thickness;
}
encode = {
enter: enter = {
opacity: constants_zero,
x: constants_zero,
y: constants_zero,
width: encode_util_encoder(width),
height: encode_util_encoder(height)
},
update: Object(vega_util["o" /* extend */])({}, enter, {
opacity: constants_one,
fill: {gradient: scale, start: start, stop: stop}
}),
exit: {
opacity: constants_zero
}
};
encode_util_addEncoders(encode, {
stroke: _('gradientStrokeColor'),
strokeWidth: _('gradientStrokeWidth')
}, { // update
opacity: _('gradientOpacity')
});
return guide_mark(RectMark, LegendGradientRole, null, undefined, undefined, encode, userEncode);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/legend-gradient-discrete.js
/* harmony default export */ var legend_gradient_discrete = (function(spec, scale, config, userEncode, dataRef) {
var _ = guide_util_lookup(spec, config),
vertical = _.isVertical(),
thickness = _.gradientThickness(),
length = _.gradientLength(),
encode, enter, u, v, uu, vv, adjust = '';
vertical
? (u = 'y', uu = 'y2', v = 'x', vv = 'width', adjust = '1-')
: (u = 'x', uu = 'x2', v = 'y', vv = 'height');
enter = {
opacity: constants_zero,
fill: {scale: scale, field: Value}
};
enter[u] = {signal: adjust + 'datum.' + Perc, mult: length};
enter[v] = constants_zero;
enter[uu] = {signal: adjust + 'datum.' + Perc2, mult: length};
enter[vv] = encode_util_encoder(thickness);
encode = {
enter: enter,
update: Object(vega_util["o" /* extend */])({}, enter, {opacity: constants_one}),
exit: {opacity: constants_zero}
};
encode_util_addEncoders(encode, {
stroke: _('gradientStrokeColor'),
strokeWidth: _('gradientStrokeWidth')
}, { // update
opacity: _('gradientOpacity')
});
return guide_mark(RectMark, LegendBandRole, null, Value, dataRef, encode, userEncode);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/legend-gradient-labels.js
const legend_gradient_labels_alignExpr = `datum.${Perc}<=0?"${constants_Left}":datum.${Perc}>=1?"${constants_Right}":"${constants_Center}"`,
legend_gradient_labels_baselineExpr = `datum.${Perc}<=0?"${constants_Bottom}":datum.${Perc}>=1?"${constants_Top}":"${constants_Middle}"`;
/* harmony default export */ var legend_gradient_labels = (function(spec, config, userEncode, dataRef) {
var _ = guide_util_lookup(spec, config),
vertical = _.isVertical(),
thickness = encode_util_encoder(_.gradientThickness()),
length = _.gradientLength(),
overlap = _('labelOverlap'),
separation = _('labelSeparation'),
encode, enter, update, u, v, adjust = '';
encode = {
enter: enter = {
opacity: constants_zero
},
update: update = {
opacity: constants_one,
text: {field: Label}
},
exit: {
opacity: constants_zero
}
};
encode_util_addEncoders(encode, {
fill: _('labelColor'),
fillOpacity: _('labelOpacity'),
font: _('labelFont'),
fontSize: _('labelFontSize'),
fontStyle: _('labelFontStyle'),
fontWeight: _('labelFontWeight'),
limit: util_value(spec.labelLimit, config.gradientLabelLimit)
});
if (vertical) {
enter.align = {value: 'left'};
enter.baseline = update.baseline = {signal: legend_gradient_labels_baselineExpr};
u = 'y'; v = 'x'; adjust = '1-';
} else {
enter.align = update.align = {signal: legend_gradient_labels_alignExpr};
enter.baseline = {value: 'top'};
u = 'x'; v = 'y';
}
enter[u] = update[u] = {signal: adjust + 'datum.' + Perc, mult: length};
enter[v] = update[v] = thickness;
thickness.offset = util_value(spec.labelOffset, config.gradientLabelOffset) || 0;
spec = guide_mark(TextMark, LegendLabelRole, GuideLabelStyle, Value, dataRef, encode, userEncode);
if (overlap) {
spec.overlap = {
separation: separation,
method: overlap,
order: 'datum.' + Index
};
}
return spec;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/guide-group.js
/* harmony default export */ var guide_group = (function(role, style, name, dataRef, interactive, encode, marks, layout) {
return {
type: GroupMark,
name: name,
role: role,
style: style,
from: dataRef,
interactive: interactive || false,
encode: encode,
marks: marks,
layout: layout
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/legend-symbol-groups.js
// userEncode is top-level, includes entries, symbols, labels
/* harmony default export */ var legend_symbol_groups = (function(spec, config, userEncode, dataRef, columns) {
var _ = guide_util_lookup(spec, config),
entries = userEncode.entries,
interactive = !!(entries && entries.interactive),
name = entries ? entries.name : undefined,
height = _('clipHeight'),
symbolOffset = _('symbolOffset'),
valueRef = {data: 'value'},
encode = {},
xSignal = `(${columns}) ? datum.${Offset} : datum.${Size}`,
yEncode = height ? encode_util_encoder(height) : {field: Size},
index = `datum.${Index}`,
ncols = `max(1, ${columns})`,
enter, update, labelOffset, symbols, labels, nrows, sort;
yEncode.mult = 0.5;
// -- LEGEND SYMBOLS --
encode = {
enter: enter = {
opacity: constants_zero,
x: {signal: xSignal, mult: 0.5, offset: symbolOffset},
y: yEncode
},
update: update = {
opacity: constants_one,
x: enter.x,
y: enter.y
},
exit: {
opacity: constants_zero
}
};
var baseFill = null,
baseStroke = null;
if (!spec.fill) {
baseFill = config.symbolBaseFillColor;
baseStroke = config.symbolBaseStrokeColor;
}
encode_util_addEncoders(encode, {
fill: _('symbolFillColor', baseFill),
shape: _('symbolType'),
size: _('symbolSize'),
stroke: _('symbolStrokeColor', baseStroke),
strokeDash: _('symbolDash'),
strokeDashOffset: _('symbolDashOffset'),
strokeWidth: _('symbolStrokeWidth')
}, { // update
opacity: _('symbolOpacity')
});
LegendScales.forEach(function(scale) {
if (spec[scale]) {
update[scale] = enter[scale] = {scale: spec[scale], field: Value};
}
});
symbols = guide_mark(
SymbolMark, LegendSymbolRole, null,
Value, valueRef, encode, userEncode.symbols
);
if (height) symbols.clip = true;
// -- LEGEND LABELS --
labelOffset = encode_util_encoder(symbolOffset);
labelOffset.offset = _('labelOffset');
encode = {
enter: enter = {
opacity: constants_zero,
x: {signal: xSignal, offset: labelOffset},
y: yEncode
},
update: update = {
opacity: constants_one,
text: {field: Label},
x: enter.x,
y: enter.y
},
exit: {
opacity: constants_zero
}
};
encode_util_addEncoders(encode, {
align: _('labelAlign'),
baseline: _('labelBaseline'),
fill: _('labelColor'),
fillOpacity: _('labelOpacity'),
font: _('labelFont'),
fontSize: _('labelFontSize'),
fontStyle: _('labelFontStyle'),
fontWeight: _('labelFontWeight'),
limit: _('labelLimit')
});
labels = guide_mark(
TextMark, LegendLabelRole, GuideLabelStyle,
Value, valueRef, encode, userEncode.labels
);
// -- LEGEND ENTRY GROUPS --
encode = {
enter: {
noBound: {value: !height}, // ignore width/height in bounds calc
width: constants_zero,
height: height ? encode_util_encoder(height) : constants_zero,
opacity: constants_zero
},
exit: {opacity: constants_zero},
update: update = {
opacity: constants_one,
row: {signal: null},
column: {signal: null}
}
};
// annotate and sort groups to ensure correct ordering
if (_.isVertical(true)) {
nrows = `ceil(item.mark.items.length / ${ncols})`;
update.row.signal = `${index}%${nrows}`;
update.column.signal = `floor(${index} / ${nrows})`;
sort = {field: ['row', index]};
} else {
update.row.signal = `floor(${index} / ${ncols})`;
update.column.signal = `${index} % ${ncols}`;
sort = {field: index};
}
// handle zero column case (implies infinite columns)
update.column.signal = `(${columns})?${update.column.signal}:${index}`;
// facet legend entries into sub-groups
dataRef = {facet: {data: dataRef, name: 'value', groupby: Index}};
spec = guide_group(
roles_ScopeRole, null, name, dataRef, interactive,
encode_util_extendEncode(encode, entries, constants_Skip), [symbols, labels]
);
spec.sort = sort;
return spec;
});
function legend_symbol_groups_legendSymbolLayout(spec, config) {
const _ = guide_util_lookup(spec, config);
// layout parameters for legend entries
return {
align: _('gridAlign'),
columns: _.entryColumns(),
center: {
row: true,
column: false
},
padding: {
row: _('rowPadding'),
column: _('columnPadding')
}
};
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/legend-title.js
// expression logic for align, anchor, angle, and baseline calculation
const legend_title_isL = 'item.orient === "left"',
legend_title_isR = 'item.orient === "right"',
legend_title_isLR = `(${legend_title_isL} || ${legend_title_isR})`,
legend_title_isVG = `datum.vgrad && ${legend_title_isLR}`,
legend_title_baseline = guide_util_anchorExpr('"top"', '"bottom"', '"middle"'),
legend_title_alignFlip = guide_util_anchorExpr('"right"', '"left"', '"center"'),
legend_title_exprAlign = `datum.vgrad && ${legend_title_isR} ? (${legend_title_alignFlip}) : (${legend_title_isLR} && !(datum.vgrad && ${legend_title_isL})) ? "left" : ${guide_util_alignExpr}`,
legend_title_exprAnchor = `item._anchor || (${legend_title_isLR} ? "middle" : "start")`,
legend_title_exprAngle = `${legend_title_isVG} ? (${legend_title_isL} ? -90 : 90) : 0`,
legend_title_exprBaseline = `${legend_title_isLR} ? (datum.vgrad ? (${legend_title_isR} ? "bottom" : "top") : ${legend_title_baseline}) : "top"`;
/* harmony default export */ var legend_title = (function(spec, config, userEncode, dataRef) {
var _ = guide_util_lookup(spec, config), encode;
encode = {
enter: {opacity: constants_zero},
update: {
opacity: constants_one,
x: {field: {group: 'padding'}},
y: {field: {group: 'padding'}}
},
exit: {opacity: constants_zero}
};
encode_util_addEncoders(encode, {
orient: _('titleOrient'),
_anchor: _('titleAnchor'),
anchor: {signal: legend_title_exprAnchor},
angle: {signal: legend_title_exprAngle},
align: {signal: legend_title_exprAlign},
baseline: {signal: legend_title_exprBaseline},
text: spec.title,
fill: _('titleColor'),
fillOpacity: _('titleOpacity'),
font: _('titleFont'),
fontSize: _('titleFontSize'),
fontStyle: _('titleFontStyle'),
fontWeight: _('titleFontWeight'),
limit: _('titleLimit'),
lineHeight: _('titleLineHeight')
}, { // require update
align: _('titleAlign'),
baseline: _('titleBaseline'),
});
return guide_mark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/clip.js
/* harmony default export */ var marks_clip = (function(clip, scope) {
var expr;
if (Object(vega_util["F" /* isObject */])(clip)) {
if (clip.signal) {
expr = clip.signal;
} else if (clip.path) {
expr = 'pathShape(' + clip_param(clip.path) + ')';
} else if (clip.sphere) {
expr = 'geoShape(' + clip_param(clip.sphere) + ', {type: "Sphere"})';
}
}
return expr
? scope.signalRef(expr)
: !!clip;
});
function clip_param(value) {
return Object(vega_util["F" /* isObject */])(value) && value.signal
? value.signal
: Object(vega_util["Z" /* stringValue */])(value);
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/role.js
/* harmony default export */ var marks_role = (function(spec) {
var role = spec.role || '';
return (!role.indexOf('axis') || !role.indexOf('legend') || !role.indexOf('title'))
? role
: spec.type === GroupMark ? roles_ScopeRole : (role || MarkRole);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/definition.js
/* harmony default export */ var marks_definition = (function(spec) {
return {
marktype: spec.type,
name: spec.name || undefined,
role: spec.role || marks_role(spec),
zindex: +spec.zindex || undefined
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/interactive.js
/* harmony default export */ var marks_interactive = (function(spec, scope) {
return spec && spec.signal ? scope.signalRef(spec.signal)
: spec === false ? false
: true;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/transform.js
/**
* Parse a data transform specification.
*/
/* harmony default export */ var parsers_transform = (function(spec, scope) {
var def = register_definition(spec.type);
if (!def) Object(vega_util["n" /* error */])('Unrecognized transform type: ' + Object(vega_util["Z" /* stringValue */])(spec.type));
var t = util_entry(def.type.toLowerCase(), null, transform_parseParameters(def, spec, scope));
if (spec.signal) scope.addSignal(spec.signal, scope.proxy(t));
t.metadata = def.metadata || {};
return t;
});
/**
* Parse all parameters of a data transform.
*/
function transform_parseParameters(def, spec, scope) {
var params = {}, pdef, i, n;
for (i=0, n=def.params.length; i<n; ++i) {
pdef = def.params[i];
params[pdef.name] = transform_parseParameter(pdef, spec, scope);
}
return params;
}
/**
* Parse a data transform parameter.
*/
function transform_parseParameter(def, spec, scope) {
var type = def.type,
value = spec[def.name];
if (type === 'index') {
return transform_parseIndexParameter(def, spec, scope);
} else if (value === undefined) {
if (def.required) {
Object(vega_util["n" /* error */])('Missing required ' + Object(vega_util["Z" /* stringValue */])(spec.type)
+ ' parameter: ' + Object(vega_util["Z" /* stringValue */])(def.name));
}
return;
} else if (type === 'param') {
return transform_parseSubParameters(def, spec, scope);
} else if (type === 'projection') {
return scope.projectionRef(spec[def.name]);
}
return def.array && !util_isSignal(value)
? value.map(function(v) { return transform_parameterValue(def, v, scope); })
: transform_parameterValue(def, value, scope);
}
/**
* Parse a single parameter value.
*/
function transform_parameterValue(def, value, scope) {
var type = def.type;
if (util_isSignal(value)) {
return transform_isExpr(type) ? Object(vega_util["n" /* error */])('Expression references can not be signals.')
: transform_isField(type) ? scope.fieldRef(value)
: transform_isCompare(type) ? scope.compareRef(value)
: scope.signalRef(value.signal);
} else {
var expr = def.expr || transform_isField(type);
return expr && transform_outerExpr(value) ? scope.exprRef(value.expr, value.as)
: expr && transform_outerField(value) ? util_fieldRef(value.field, value.as)
: transform_isExpr(type) ? parsers_expression(value, scope)
: transform_isData(type) ? util_ref(scope.getData(value).values)
: transform_isField(type) ? util_fieldRef(value)
: transform_isCompare(type) ? scope.compareRef(value)
: value;
}
}
/**
* Parse parameter for accessing an index of another data set.
*/
function transform_parseIndexParameter(def, spec, scope) {
if (!Object(vega_util["H" /* isString */])(spec.from)) {
Object(vega_util["n" /* error */])('Lookup "from" parameter must be a string literal.');
}
return scope.getData(spec.from).lookupRef(scope, spec.key);
}
/**
* Parse a parameter that contains one or more sub-parameter objects.
*/
function transform_parseSubParameters(def, spec, scope) {
var value = spec[def.name];
if (def.array) {
if (!Object(vega_util["A" /* isArray */])(value)) { // signals not allowed!
Object(vega_util["n" /* error */])('Expected an array of sub-parameters. Instead: ' + Object(vega_util["Z" /* stringValue */])(value));
}
return value.map(function(v) {
return transform_parseSubParameter(def, v, scope);
});
} else {
return transform_parseSubParameter(def, value, scope);
}
}
/**
* Parse a sub-parameter object.
*/
function transform_parseSubParameter(def, value, scope) {
var params, pdef, k, i, n;
// loop over defs to find matching key
for (i=0, n=def.params.length; i<n; ++i) {
pdef = def.params[i];
for (k in pdef.key) {
if (pdef.key[k] !== value[k]) { pdef = null; break; }
}
if (pdef) break;
}
// raise error if matching key not found
if (!pdef) Object(vega_util["n" /* error */])('Unsupported parameter: ' + Object(vega_util["Z" /* stringValue */])(value));
// parse params, create Params transform, return ref
params = Object(vega_util["o" /* extend */])(transform_parseParameters(pdef, value, scope), pdef.key);
return util_ref(scope.add(transforms_Params(params)));
}
// -- Utilities -----
function transform_outerExpr(_) {
return _ && _.expr;
}
function transform_outerField(_) {
return _ && _.field;
}
function transform_isData(_) {
return _ === 'data';
}
function transform_isExpr(_) {
return _ === 'expr';
}
function transform_isField(_) {
return _ === 'field';
}
function transform_isCompare(_) {
return _ === 'compare'
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/data.js
/* harmony default export */ var marks_data = (function(from, group, scope) {
var facet, key, op, dataRef, parent;
// if no source data, generate singleton datum
if (!from) {
dataRef = util_ref(scope.add(transforms_Collect(null, [{}])));
}
// if faceted, process facet specification
else if (facet = from.facet) {
if (!group) Object(vega_util["n" /* error */])('Only group marks can be faceted.');
// use pre-faceted source data, if available
if (facet.field != null) {
dataRef = parent = data_getDataRef(facet, scope);
} else {
// generate facet aggregates if no direct data specification
if (!from.data) {
op = parsers_transform(Object(vega_util["o" /* extend */])({
type: 'aggregate',
groupby: Object(vega_util["i" /* array */])(facet.groupby)
}, facet.aggregate), scope);
op.params.key = scope.keyRef(facet.groupby);
op.params.pulse = data_getDataRef(facet, scope);
dataRef = parent = util_ref(scope.add(op));
} else {
parent = util_ref(scope.getData(from.data).aggregate);
}
key = scope.keyRef(facet.groupby, true);
}
}
// if not yet defined, get source data reference
if (!dataRef) {
dataRef = data_getDataRef(from, scope);
}
return {
key: key,
pulse: dataRef,
parent: parent
};
});
function data_getDataRef(from, scope) {
return from.$ref ? from
: from.data && from.data.$ref ? from.data
: util_ref(scope.getData(from.data).output);
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/DataScope.js
function DataScope_DataScope(scope, input, output, values, aggr) {
this.scope = scope; // parent scope object
this.input = input; // first operator in pipeline (tuple input)
this.output = output; // last operator in pipeline (tuple output)
this.values = values; // operator for accessing tuples (but not tuple flow)
// last aggregate in transform pipeline
this.aggregate = aggr;
// lookup table of field indices
this.index = {};
}
DataScope_DataScope.fromEntries = function(scope, entries) {
var n = entries.length,
i = 1,
input = entries[0],
values = entries[n-1],
output = entries[n-2],
aggr = null;
if (input && input.type === 'load') {
input = entries[1];
}
// add operator entries to this scope, wire up pulse chain
scope.add(entries[0]);
for (; i<n; ++i) {
entries[i].params.pulse = util_ref(entries[i-1]);
scope.add(entries[i]);
if (entries[i].type === 'aggregate') aggr = entries[i];
}
return new DataScope_DataScope(scope, input, output, values, aggr);
};
var DataScope_prototype = DataScope_DataScope.prototype;
DataScope_prototype.countsRef = function(scope, field, sort) {
var ds = this,
cache = ds.counts || (ds.counts = {}),
k = DataScope_fieldKey(field), v, a, p;
if (k != null) {
scope = ds.scope;
v = cache[k];
}
if (!v) {
p = {
groupby: scope.fieldRef(field, 'key'),
pulse: util_ref(ds.output)
};
if (sort && sort.field) DataScope_addSortField(scope, p, sort);
a = scope.add(transforms_Aggregate(p));
v = scope.add(transforms_Collect({pulse: util_ref(a)}));
v = {agg: a, ref: util_ref(v)};
if (k != null) cache[k] = v;
} else if (sort && sort.field) {
DataScope_addSortField(scope, v.agg.params, sort);
}
return v.ref;
};
function DataScope_fieldKey(field) {
return Object(vega_util["H" /* isString */])(field) ? field : null;
}
function DataScope_addSortField(scope, p, sort) {
var as = util_aggrField(sort.op, sort.field), s;
if (p.ops) {
for (var i=0, n=p.as.length; i<n; ++i) {
if (p.as[i] === as) return;
}
} else {
p.ops = ['count'];
p.fields = [null];
p.as = ['count'];
}
if (sort.op) {
p.ops.push((s=sort.op.signal) ? scope.signalRef(s) : sort.op);
p.fields.push(scope.fieldRef(sort.field));
p.as.push(as);
}
}
function DataScope_cache(scope, ds, name, optype, field, counts, index) {
var cache = ds[name] || (ds[name] = {}),
sort = util_sortKey(counts),
k = DataScope_fieldKey(field), v, op;
if (k != null) {
scope = ds.scope;
k = k + (sort ? '|' + sort : '');
v = cache[k];
}
if (!v) {
var params = counts
? {field: util_keyFieldRef, pulse: ds.countsRef(scope, field, counts)}
: {field: scope.fieldRef(field), pulse: util_ref(ds.output)};
if (sort) params.sort = scope.sortRef(counts);
op = scope.add(util_entry(optype, undefined, params));
if (index) ds.index[field] = op;
v = util_ref(op);
if (k != null) cache[k] = v;
}
return v;
}
DataScope_prototype.tuplesRef = function() {
return util_ref(this.values);
};
DataScope_prototype.extentRef = function(scope, field) {
return DataScope_cache(scope, this, 'extent', 'extent', field, false);
};
DataScope_prototype.domainRef = function(scope, field) {
return DataScope_cache(scope, this, 'domain', 'values', field, false);
};
DataScope_prototype.valuesRef = function(scope, field, sort) {
return DataScope_cache(scope, this, 'vals', 'values', field, sort || true);
};
DataScope_prototype.lookupRef = function(scope, field) {
return DataScope_cache(scope, this, 'lookup', 'tupleindex', field, false);
};
DataScope_prototype.indataRef = function(scope, field) {
return DataScope_cache(scope, this, 'indata', 'tupleindex', field, true, true);
};
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/facet.js
/* harmony default export */ var marks_facet = (function(spec, scope, group) {
var facet = spec.from.facet,
name = facet.name,
data = data_getDataRef(facet, scope),
subscope, source, values, op;
if (!facet.name) {
Object(vega_util["n" /* error */])('Facet must have a name: ' + Object(vega_util["Z" /* stringValue */])(facet));
}
if (!facet.data) {
Object(vega_util["n" /* error */])('Facet must reference a data set: ' + Object(vega_util["Z" /* stringValue */])(facet));
}
if (facet.field) {
op = scope.add(transforms_PreFacet({
field: scope.fieldRef(facet.field),
pulse: data
}));
} else if (facet.groupby) {
op = scope.add(transforms_Facet({
key: scope.keyRef(facet.groupby),
group: util_ref(scope.proxy(group.parent)),
pulse: data
}));
} else {
Object(vega_util["n" /* error */])('Facet must specify groupby or field: ' + Object(vega_util["Z" /* stringValue */])(facet));
}
// initialize facet subscope
subscope = scope.fork();
source = subscope.add(transforms_Collect());
values = subscope.add(transforms_Sieve({pulse: util_ref(source)}));
subscope.addData(name, new DataScope_DataScope(subscope, source, source, values));
subscope.addSignal('parent', null);
// parse faceted subflow
op.params.subflow = {
$subflow: parsers_spec(spec, subscope).toRuntime()
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/marks/subflow.js
/* harmony default export */ var marks_subflow = (function(spec, scope, input) {
var op = scope.add(transforms_PreFacet({pulse: input.pulse})),
subscope = scope.fork();
subscope.add(transforms_Sieve());
subscope.addSignal('parent', null);
// parse group mark subflow
op.params.subflow = {
$subflow: parsers_spec(spec, subscope).toRuntime()
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/trigger.js
/* harmony default export */ var trigger = (function(spec, scope, name) {
var remove = spec.remove,
insert = spec.insert,
toggle = spec.toggle,
modify = spec.modify,
values = spec.values,
op = scope.add(util_operator()),
update, expr;
update = 'if(' + spec.trigger + ',modify("'
+ name + '",'
+ [insert, remove, toggle, modify, values]
.map(function(_) { return _ == null ? 'null' : _; })
.join(',')
+ '),0)';
expr = parsers_expression(update, scope);
op.update = expr.$expr;
op.params = expr.$params;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/mark.js
/* harmony default export */ var parsers_mark = (function(spec, scope) {
var role = marks_role(spec),
group = spec.type === GroupMark,
facet = spec.from && spec.from.facet,
layout = spec.layout || role === roles_ScopeRole || role === roles_FrameRole,
nested = role === MarkRole || layout || facet,
overlap = spec.overlap,
ops, op, input, store, enc, bound, render, sieve, name,
joinRef, markRef, encodeRef, layoutRef, boundRef;
// resolve input data
input = marks_data(spec.from, group, scope);
// data join to map tuples to visual items
op = scope.add(transforms_DataJoin({
key: input.key || (spec.key ? util_fieldRef(spec.key) : undefined),
pulse: input.pulse,
clean: !group
}));
joinRef = util_ref(op);
// collect visual items
op = store = scope.add(transforms_Collect({pulse: joinRef}));
// connect visual items to scenegraph
op = scope.add(transforms_Mark({
markdef: marks_definition(spec),
interactive: marks_interactive(spec.interactive, scope),
clip: marks_clip(spec.clip, scope),
context: {$context: true},
groups: scope.lookup(),
parent: scope.signals.parent ? scope.signalRef('parent') : null,
index: scope.markpath(),
pulse: util_ref(op)
}));
markRef = util_ref(op);
// add visual encoders
op = enc = scope.add(transforms_Encode(encode_util_encoders(
spec.encode, spec.type, role, spec.style, scope,
{mod: false, pulse: markRef}
)));
// monitor parent marks to propagate changes
op.params.parent = scope.encode();
// add post-encoding transforms, if defined
if (spec.transform) {
spec.transform.forEach(function(_) {
const tx = parsers_transform(_, scope),
md = tx.metadata;
if (md.generates || md.changes) {
Object(vega_util["n" /* error */])('Mark transforms should not generate new data.');
}
if (!md.nomod) enc.params.mod = true; // update encode mod handling
tx.params.pulse = util_ref(op);
scope.add(op = tx);
});
}
// if item sort specified, perform post-encoding
if (spec.sort) {
op = scope.add(transforms_SortItems({
sort: scope.compareRef(spec.sort),
pulse: util_ref(op)
}));
}
encodeRef = util_ref(op);
// add view layout operator if needed
if (facet || layout) {
layout = scope.add(transforms_ViewLayout({
layout: scope.objectProperty(spec.layout),
legends: scope.legends,
mark: markRef,
pulse: encodeRef
}));
layoutRef = util_ref(layout);
}
// compute bounding boxes
bound = scope.add(transforms_Bound({mark: markRef, pulse: layoutRef || encodeRef}));
boundRef = util_ref(bound);
// if group mark, recurse to parse nested content
if (group) {
// juggle layout & bounds to ensure they run *after* any faceting transforms
if (nested) { ops = scope.operators; ops.pop(); if (layout) ops.pop(); }
scope.pushState(encodeRef, layoutRef || boundRef, joinRef);
facet ? marks_facet(spec, scope, input) // explicit facet
: nested ? marks_subflow(spec, scope, input) // standard mark group
: parsers_spec(spec, scope); // guide group, we can avoid nested scopes
scope.popState();
if (nested) { if (layout) ops.push(layout); ops.push(bound); }
}
// if requested, add overlap removal transform
if (overlap) {
boundRef = mark_parseOverlap(overlap, boundRef, scope);
}
// render / sieve items
render = scope.add(transforms_Render({pulse: boundRef}));
sieve = scope.add(transforms_Sieve({pulse: util_ref(render)}, undefined, scope.parent()));
// if mark is named, make accessible as reactive geometry
// add trigger updates if defined
if (spec.name != null) {
name = spec.name;
scope.addData(name, new DataScope_DataScope(scope, store, render, sieve));
if (spec.on) spec.on.forEach(function(on) {
if (on.insert || on.remove || on.toggle) {
Object(vega_util["n" /* error */])('Marks only support modify triggers.');
}
trigger(on, scope, name);
});
}
});
function mark_parseOverlap(overlap, source, scope) {
var method = overlap.method,
bound = overlap.bound,
sep = overlap.separation, tol;
var params = {
separation: util_isSignal(sep) ? scope.signalRef(sep.signal) : sep,
method: util_isSignal(method) ? scope.signalRef(method.signal) : method,
pulse: source
};
if (overlap.order) {
params.sort = scope.compareRef({field: overlap.order});
}
if (bound) {
tol = bound.tolerance;
params.boundTolerance = util_isSignal(tol) ? scope.signalRef(tol.signal) : +tol;
params.boundScale = scope.scaleRef(bound.scale);
params.boundOrient = bound.orient;
}
return util_ref(scope.add(transforms_Overlap(params)));
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/legend.js
/* harmony default export */ var parsers_legend = (function(spec, scope) {
var config = scope.config.legend,
encode = spec.encode || {},
legendEncode = encode.legend || {},
name = legendEncode.name || undefined,
interactive = legendEncode.interactive,
style = legendEncode.style,
_ = guide_util_lookup(spec, config),
entryEncode, entryLayout, params, children,
type, datum, dataRef, entryRef, group;
// resolve 'canonical' scale name
var scale = LegendScales.reduce(function(a, b) { return a || spec[b]; }, 0);
if (!scale) Object(vega_util["n" /* error */])('Missing valid scale for legend.');
// resolve legend type (symbol, gradient, or discrete gradient)
type = legend_legendType(spec, scope.scaleType(scale));
// single-element data source for legend group
datum = {
title: spec.title != null,
type: type,
vgrad: type !== 'symbol' && _.isVertical()
};
dataRef = util_ref(scope.add(transforms_Collect(null, [datum])));
// encoding properties for legend group
legendEncode = encode_util_extendEncode(
legend_buildLegendEncode(_, config), legendEncode, constants_Skip
);
// encoding properties for legend entry sub-group
entryEncode = {enter: {x: {value: 0}, y: {value: 0}}};
// data source for legend values
entryRef = util_ref(scope.add(transforms_LegendEntries(params = {
type: type,
scale: scope.scaleRef(scale),
count: scope.objectProperty(_('tickCount')),
limit: scope.property(_('symbolLimit')),
values: scope.objectProperty(spec.values),
minstep: scope.property(spec.tickMinStep),
formatType: scope.property(spec.formatType),
formatSpecifier: scope.property(spec.format)
})));
// continuous gradient legend
if (type === constants_Gradient) {
children = [
legend_gradient(spec, scale, config, encode.gradient),
legend_gradient_labels(spec, config, encode.labels, entryRef)
];
// adjust default tick count based on the gradient length
params.count = params.count || scope.signalRef(
`max(2,2*floor((${util_deref(_.gradientLength())})/100))`
);
}
// discrete gradient legend
else if (type === constants_Discrete) {
children = [
legend_gradient_discrete(spec, scale, config, encode.gradient, entryRef),
legend_gradient_labels(spec, config, encode.labels, entryRef)
];
}
// symbol legend
else {
// determine legend symbol group layout
entryLayout = legend_symbol_groups_legendSymbolLayout(spec, config);
children = [
legend_symbol_groups(spec, config, encode, entryRef, util_deref(entryLayout.columns))
];
// pass symbol size information to legend entry generator
params.size = legend_sizeExpression(spec, scope, children[0].marks);
}
// generate legend marks
children = [
guide_group(LegendEntryRole, null, null, dataRef, interactive,
entryEncode, children, entryLayout)
];
// include legend title if defined
if (datum.title) {
children.push(legend_title(spec, config, encode.title, dataRef));
}
// build legend specification
group = guide_group(roles_LegendRole, style, name, dataRef, interactive, legendEncode, children);
if (spec.zindex) group.zindex = spec.zindex;
// parse legend specification
return parsers_mark(group, scope);
});
function legend_legendType(spec, scaleType) {
var type = spec.type || constants_Symbols;
if (!spec.type && legend_scaleCount(spec) === 1 && (spec.fill || spec.stroke)) {
type = node_modules_vega_scale_src_scales_isContinuous(scaleType) ? constants_Gradient
: node_modules_vega_scale_src_scales_isDiscretizing(scaleType) ? constants_Discrete
: constants_Symbols;
}
return type !== constants_Gradient ? type
: node_modules_vega_scale_src_scales_isDiscretizing(scaleType) ? constants_Discrete
: constants_Gradient;
}
function legend_scaleCount(spec) {
return LegendScales.reduce(function(count, type) {
return count + (spec[type] ? 1 : 0);
}, 0);
}
function legend_buildLegendEncode(_, config) {
var encode = {enter: {}, update: {}};
encode_util_addEncoders(encode, {
orient: _('orient'),
offset: _('offset'),
padding: _('padding'),
titlePadding: _('titlePadding'),
cornerRadius: _('cornerRadius'),
fill: _('fillColor'),
stroke: _('strokeColor'),
strokeWidth: config.strokeWidth,
strokeDash: config.strokeDash,
x: _('legendX'),
y: _('legendY'),
});
return encode;
}
function legend_sizeExpression(spec, scope, marks) {
var size = util_deref(legend_getChannel('size', spec, marks)),
strokeWidth = util_deref(legend_getChannel('strokeWidth', spec, marks)),
fontSize = util_deref(legend_getFontSize(marks[1].encode, scope, GuideLabelStyle));
return parsers_expression(
`max(ceil(sqrt(${size})+${strokeWidth}),${fontSize})`,
scope
);
}
function legend_getChannel(name, spec, marks) {
return spec[name]
? `scale("${spec[name]}",datum)`
: guide_util_getEncoding(name, marks[0].encode);
}
function legend_getFontSize(encode, scope, style) {
return guide_util_getEncoding('fontSize', encode) || guide_util_getStyle('fontSize', scope, style);
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/title.js
const title_angleExpr = `item.orient==="${constants_Left}"?-90:item.orient==="${constants_Right}"?90:0`;
/* harmony default export */ var parsers_title = (function(spec, scope) {
spec = Object(vega_util["H" /* isString */])(spec) ? {text: spec} : spec;
var _ = guide_util_lookup(spec, scope.config.title),
encode = spec.encode || {},
userEncode = encode.group || {},
name = userEncode.name || undefined,
interactive = userEncode.interactive,
style = userEncode.style,
children = [],
dataRef, group;
// single-element data source for group title
dataRef = util_ref(scope.add(transforms_Collect(null, [{}])));
// include title text
children.push(title_buildTitle(spec, _, title_titleEncode(spec), dataRef));
// include subtitle text
if (spec.subtitle) {
children.push(title_buildSubTitle(spec, _, encode.subtitle, dataRef));
}
// build title specification
group = guide_group(roles_TitleRole, style, name, dataRef, interactive,
title_groupEncode(_, userEncode), children);
if (spec.zindex) group.zindex = spec.zindex;
// parse title specification
return parsers_mark(group, scope);
});
// provide backwards-compatibility for title custom encode;
// the top-level encode block has been *deprecated*.
function title_titleEncode(spec) {
const encode = spec.encode;
return (encode && encode.title) || Object(vega_util["o" /* extend */])({
name: spec.name,
interactive: spec.interactive,
style: spec.style
}, encode);
}
function title_groupEncode(_, userEncode) {
var encode = {enter: {}, update: {}};
encode_util_addEncoders(encode, {
orient: _('orient'),
anchor: _('anchor'),
align: {signal: guide_util_alignExpr},
angle: {signal: title_angleExpr},
limit: _('limit'),
frame: _('frame'),
offset: _('offset') || 0,
padding: _('subtitlePadding')
});
return encode_util_extendEncode(encode, userEncode, constants_Skip);
}
function title_buildTitle(spec, _, userEncode, dataRef) {
var zero = {value: 0},
text = spec.text,
encode = {
enter: {opacity: zero},
update: {opacity: {value: 1}},
exit: {opacity: zero}
};
encode_util_addEncoders(encode, {
text: text,
align: {signal: 'item.mark.group.align'},
angle: {signal: 'item.mark.group.angle'},
limit: {signal: 'item.mark.group.limit'},
baseline: 'top',
dx: _('dx'),
dy: _('dy'),
fill: _('color'),
font: _('font'),
fontSize: _('fontSize'),
fontStyle: _('fontStyle'),
fontWeight: _('fontWeight'),
lineHeight: _('lineHeight')
}, { // update
align: _('align'),
angle: _('angle'),
baseline: _('baseline')
});
return guide_mark(TextMark, TitleTextRole, GroupTitleStyle,
null, dataRef, encode, userEncode);
}
function title_buildSubTitle(spec, _, userEncode, dataRef) {
var zero = {value: 0},
text = spec.subtitle,
encode = {
enter: {opacity: zero},
update: {opacity: {value: 1}},
exit: {opacity: zero}
};
encode_util_addEncoders(encode, {
text: text,
align: {signal: 'item.mark.group.align'},
angle: {signal: 'item.mark.group.angle'},
limit: {signal: 'item.mark.group.limit'},
baseline: 'top',
dx: _('dx'),
dy: _('dy'),
fill: _('subtitleColor'),
font: _('subtitleFont'),
fontSize: _('subtitleFontSize'),
fontStyle: _('subtitleFontStyle'),
fontWeight: _('subtitleFontWeight'),
lineHeight: _('subtitleLineHeight')
}, { // update
align: _('align'),
angle: _('angle'),
baseline: _('baseline')
});
return guide_mark(TextMark, TitleSubtitleRole, GroupSubtitleStyle,
null, dataRef, encode, userEncode);
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/data.js
function data_parseData(data, scope) {
var transforms = [];
if (data.transform) {
data.transform.forEach(function(tx) {
transforms.push(parsers_transform(tx, scope));
});
}
if (data.on) {
data.on.forEach(function(on) {
trigger(on, scope, data.name);
});
}
scope.addDataPipeline(data.name, data_analyze(data, scope, transforms));
}
/**
* Analyze a data pipeline, add needed operators.
*/
function data_analyze(data, scope, ops) {
var output = [],
source = null,
modify = false,
generate = false,
upstream, i, n, t, m;
if (data.values) {
// hard-wired input data set
if (util_hasSignal(data.values) || util_hasSignal(data.format)) {
// if either values or format has signal, use dynamic loader
output.push(data_load(scope, data));
output.push(source = data_collect());
} else {
// otherwise, ingest upon dataflow init
output.push(source = data_collect({
$ingest: data.values,
$format: data.format
}));
}
} else if (data.url) {
// load data from external source
if (util_hasSignal(data.url) || util_hasSignal(data.format)) {
// if either url or format has signal, use dynamic loader
output.push(data_load(scope, data));
output.push(source = data_collect());
} else {
// otherwise, request load upon dataflow init
output.push(source = data_collect({
$request: data.url,
$format: data.format
}));
}
} else if (data.source) {
// derives from one or more other data sets
source = upstream = Object(vega_util["i" /* array */])(data.source).map(function(d) {
return util_ref(scope.getData(d).output);
});
output.push(null); // populate later
}
// scan data transforms, add collectors as needed
for (i=0, n=ops.length; i<n; ++i) {
t = ops[i];
m = t.metadata;
if (!source && !m.source) {
output.push(source = data_collect());
}
output.push(t);
if (m.generates) generate = true;
if (m.modifies && !generate) modify = true;
if (m.source) source = t;
else if (m.changes) source = null;
}
if (upstream) {
n = upstream.length - 1;
output[0] = transforms_Relay({
derive: modify,
pulse: n ? upstream : upstream[0]
});
if (modify || n) {
// collect derived and multi-pulse tuples
output.splice(1, 0, data_collect());
}
}
if (!source) output.push(data_collect());
output.push(transforms_Sieve({}));
return output;
}
function data_collect(values) {
var s = transforms_Collect({}, values);
s.metadata = {source: true};
return s;
}
function data_load(scope, data) {
return transforms_Load({
url: data.url ? scope.property(data.url) : undefined,
async: data.async ? scope.property(data.async) : undefined,
values: data.values ? scope.property(data.values) : undefined,
format: scope.objectProperty(data.format)
});
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/axis-config.js
/* harmony default export */ var axis_config = (function(spec, scope) {
var config = scope.config,
orient = spec.orient,
xy = (orient === constants_Top || orient === constants_Bottom) ? config.axisX : config.axisY,
or = config['axis' + orient[0].toUpperCase() + orient.slice(1)],
band = scope.scaleType(spec.scale) === 'band' && config.axisBand;
return (xy || or || band)
? Object(vega_util["o" /* extend */])({}, config.axis, xy, or, band)
: config.axis;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/axis-domain.js
/* harmony default export */ var axis_domain = (function(spec, config, userEncode, dataRef) {
var _ = guide_util_lookup(spec, config),
orient = spec.orient,
encode, enter, update, u, u2, v;
encode = {
enter: enter = {opacity: constants_zero},
update: update = {opacity: constants_one},
exit: {opacity: constants_zero}
};
encode_util_addEncoders(encode, {
stroke: _('domainColor'),
strokeDash: _('domainDash'),
strokeDashOffset: _('domainDashOffset'),
strokeWidth: _('domainWidth'),
strokeOpacity: _('domainOpacity')
});
if (orient === constants_Top || orient === constants_Bottom) {
u = 'x';
v = 'y';
} else {
u = 'y';
v = 'x';
}
u2 = u + '2';
enter[v] = constants_zero;
update[u] = enter[u] = axis_domain_position(spec, 0);
update[u2] = enter[u2] = axis_domain_position(spec, 1);
return guide_mark(RuleMark, AxisDomainRole, null, null, dataRef, encode, userEncode);
});
function axis_domain_position(spec, pos) {
return {scale: spec.scale, range: pos};
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/axis-grid.js
/* harmony default export */ var axis_grid = (function(spec, config, userEncode, dataRef, band) {
var _ = guide_util_lookup(spec, config),
orient = spec.orient,
vscale = spec.gridScale,
sign = (orient === constants_Left || orient === constants_Top) ? 1 : -1,
offset = axis_grid_offsetValue(spec.offset, sign),
encode, enter, exit, update, tickPos, u, v, v2, s;
encode = {
enter: enter = {opacity: constants_zero},
update: update = {opacity: constants_one},
exit: exit = {opacity: constants_zero}
};
encode_util_addEncoders(encode, {
stroke: _('gridColor'),
strokeDash: _('gridDash'),
strokeDashOffset: _('gridDashOffset'),
strokeOpacity: _('gridOpacity'),
strokeWidth: _('gridWidth')
});
tickPos = {
scale: spec.scale,
field: Value,
band: band.band,
extra: band.extra,
offset: band.offset,
round: _('tickRound')
};
if (orient === constants_Top || orient === constants_Bottom) {
u = 'x';
v = 'y';
s = 'height';
} else {
u = 'y';
v = 'x';
s = 'width';
}
v2 = v + '2';
update[u] = enter[u] = exit[u] = tickPos;
if (vscale) {
update[v] = enter[v] = {scale: vscale, range: 0, mult: sign, offset: offset};
update[v2] = enter[v2] = {scale: vscale, range: 1, mult: sign, offset: offset};
} else {
update[v] = enter[v] = {value: 0, offset: offset};
update[v2] = enter[v2] = {signal: s, mult: sign, offset: offset};
}
return guide_mark(RuleMark, AxisGridRole, null, Value, dataRef, encode, userEncode);
});
function axis_grid_offsetValue(offset, sign) {
if (sign === 1) {
// do nothing!
} else if (!Object(vega_util["F" /* isObject */])(offset)) {
offset = sign * (offset || 0);
} else {
var entry = offset = Object(vega_util["o" /* extend */])({}, offset);
while (entry.mult != null) {
if (!Object(vega_util["F" /* isObject */])(entry.mult)) {
entry.mult *= sign;
return offset;
} else {
entry = entry.mult = Object(vega_util["o" /* extend */])({}, entry.mult);
}
}
entry.mult = sign;
}
return offset;
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/axis-ticks.js
/* harmony default export */ var axis_ticks = (function(spec, config, userEncode, dataRef, size, band) {
var _ = guide_util_lookup(spec, config),
orient = spec.orient,
sign = (orient === constants_Left || orient === constants_Top) ? -1 : 1,
encode, enter, exit, update, tickSize, tickPos;
encode = {
enter: enter = {opacity: constants_zero},
update: update = {opacity: constants_one},
exit: exit = {opacity: constants_zero}
};
encode_util_addEncoders(encode, {
stroke: _('tickColor'),
strokeDash: _('tickDash'),
strokeDashOffset: _('tickDashOffset'),
strokeOpacity: _('tickOpacity'),
strokeWidth: _('tickWidth')
});
tickSize = encode_util_encoder(size);
tickSize.mult = sign;
tickPos = {
scale: spec.scale,
field: Value,
band: band.band,
extra: band.extra,
offset: band.offset,
round: _('tickRound')
};
if (orient === constants_Top || orient === constants_Bottom) {
update.y = enter.y = constants_zero;
update.y2 = enter.y2 = tickSize;
update.x = enter.x = exit.x = tickPos;
} else {
update.x = enter.x = constants_zero;
update.x2 = enter.x2 = tickSize;
update.y = enter.y = exit.y = tickPos;
}
return guide_mark(RuleMark, AxisTickRole, null, Value, dataRef, encode, userEncode);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/axis-labels.js
function axis_labels_flushExpr(scale, threshold, a, b, c) {
return {
signal: 'flush(range("' + scale + '"), '
+ 'scale("' + scale + '", datum.value), '
+ threshold + ',' + a + ',' + b + ',' + c + ')'
};
}
/* harmony default export */ var axis_labels = (function(spec, config, userEncode, dataRef, size, band) {
var _ = guide_util_lookup(spec, config),
orient = spec.orient,
sign = (orient === constants_Left || orient === constants_Top) ? -1 : 1,
isXAxis = (orient === constants_Top || orient === constants_Bottom),
scale = spec.scale,
flush = util_deref(_('labelFlush')),
flushOffset = util_deref(_('labelFlushOffset')),
flushOn = flush === 0 || !!flush,
labelAlign = _('labelAlign'),
labelBaseline = _('labelBaseline'),
encode, enter, tickSize, tickPos, align, baseline, offset,
bound, overlap, separation;
tickSize = encode_util_encoder(size);
tickSize.mult = sign;
tickSize.offset = encode_util_encoder(_('labelPadding') || 0);
tickSize.offset.mult = sign;
tickPos = {
scale: scale,
field: Value,
band: 0.5,
offset: guide_util_extendOffset(band.offset, _('labelOffset'))
};
if (isXAxis) {
align = labelAlign || (flushOn
? axis_labels_flushExpr(scale, flush, '"left"', '"right"', '"center"')
: 'center');
baseline = labelBaseline || (orient === constants_Top ? 'bottom' : 'top');
offset = !labelAlign;
} else {
align = labelAlign || (orient === constants_Right ? 'left' : 'right');
baseline = labelBaseline || (flushOn
? axis_labels_flushExpr(scale, flush, '"top"', '"bottom"', '"middle"')
: 'middle');
offset = !labelBaseline;
}
offset = offset && flushOn && flushOffset
? axis_labels_flushExpr(scale, flush, '-(' + flushOffset + ')', flushOffset, 0)
: null;
encode = {
enter: enter = {
opacity: constants_zero,
x: isXAxis ? tickPos : tickSize,
y: isXAxis ? tickSize : tickPos
},
update: {
opacity: constants_one,
text: {field: Label},
x: enter.x,
y: enter.y
},
exit: {
opacity: constants_zero,
x: enter.x,
y: enter.y
}
};
encode_util_addEncoders(encode, {
[isXAxis ? 'dx' : 'dy']: offset,
align: align,
baseline: baseline,
angle: _('labelAngle'),
fill: _('labelColor'),
fillOpacity: _('labelOpacity'),
font: _('labelFont'),
fontSize: _('labelFontSize'),
fontWeight: _('labelFontWeight'),
fontStyle: _('labelFontStyle'),
limit: _('labelLimit'),
lineHeight: _('labelLineHeight')
});
bound = _('labelBound');
overlap = _('labelOverlap');
separation = _('labelSeparation');
spec = guide_mark(TextMark, AxisLabelRole, GuideLabelStyle, Value, dataRef, encode, userEncode);
// if overlap method or bound defined, request label overlap removal
if (overlap || bound) {
spec.overlap = {
separation: separation,
method: overlap,
order: 'datum.index',
bound: bound ? {scale: scale, orient: orient, tolerance: bound} : null
};
}
return spec;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/guides/axis-title.js
/* harmony default export */ var axis_title = (function(spec, config, userEncode, dataRef) {
var _ = guide_util_lookup(spec, config),
orient = spec.orient,
sign = (orient === constants_Left || orient === constants_Top) ? -1 : 1,
horizontal = (orient === constants_Top || orient === constants_Bottom),
encode, enter, update, titlePos;
encode = {
enter: enter = {
opacity: constants_zero,
anchor: encode_util_encoder(_('titleAnchor')),
align: {signal: guide_util_alignExpr}
},
update: update = Object(vega_util["o" /* extend */])({}, enter, {
opacity: constants_one,
text: encode_util_encoder(spec.title)
}),
exit: {
opacity: constants_zero
}
};
titlePos = {
signal: `lerp(range("${spec.scale}"), ${guide_util_anchorExpr(0, 1, 0.5)})`
};
if (horizontal) {
update.x = titlePos;
enter.angle = {value: 0};
enter.baseline = {value: orient === constants_Top ? 'bottom' : 'top'};
} else {
update.y = titlePos;
enter.angle = {value: sign * 90};
enter.baseline = {value: 'bottom'};
}
encode_util_addEncoders(encode, {
angle: _('titleAngle'),
baseline: _('titleBaseline'),
fill: _('titleColor'),
fillOpacity: _('titleOpacity'),
font: _('titleFont'),
fontSize: _('titleFontSize'),
fontStyle: _('titleFontStyle'),
fontWeight: _('titleFontWeight'),
limit: _('titleLimit'),
lineHeight: _('titleLineHeight')
}, { // require update
align: _('titleAlign')
});
!encode_util_addEncode(encode, 'x', _('titleX'), 'update')
&& !horizontal && !encode_util_has('x', userEncode)
&& (encode.enter.auto = {value: true});
!encode_util_addEncode(encode, 'y', _('titleY'), 'update')
&& horizontal && !encode_util_has('y', userEncode)
&& (encode.enter.auto = {value: true});
return guide_mark(TextMark, AxisTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/axis.js
/* harmony default export */ var parsers_axis = (function(spec, scope) {
var config = axis_config(spec, scope),
encode = spec.encode || {},
axisEncode = encode.axis || {},
name = axisEncode.name || undefined,
interactive = axisEncode.interactive,
style = axisEncode.style,
_ = guide_util_lookup(spec, config),
band = guide_util_tickBand(_),
datum, dataRef, ticksRef, size, group, children;
// single-element data source for axis group
datum = {
orient: spec.orient,
ticks: !!_('ticks'),
labels: !!_('labels'),
grid: !!_('grid'),
domain: !!_('domain'),
title: spec.title != null,
translate: _('translate')
};
dataRef = util_ref(scope.add(transforms_Collect({}, [datum])));
// encoding properties for axis group item
axisEncode = encode_util_extendEncode({
update: {
offset: encode_util_encoder(_('offset') || 0),
position: encode_util_encoder(util_value(spec.position, 0)),
titlePadding: encode_util_encoder(_('titlePadding')),
minExtent: encode_util_encoder(_('minExtent')),
maxExtent: encode_util_encoder(_('maxExtent')),
range: {signal: `abs(span(range("${spec.scale}")))`}
}
}, encode.axis, constants_Skip);
// data source for axis ticks
ticksRef = util_ref(scope.add(transforms_AxisTicks({
scale: scope.scaleRef(spec.scale),
extra: scope.property(band.extra),
count: scope.objectProperty(spec.tickCount),
values: scope.objectProperty(spec.values),
minstep: scope.property(spec.tickMinStep),
formatType: scope.property(spec.formatType),
formatSpecifier: scope.property(spec.format)
})));
// generate axis marks
children = [];
// include axis gridlines if requested
if (datum.grid) {
children.push(axis_grid(spec, config, encode.grid, ticksRef, band));
}
// include axis ticks if requested
if (datum.ticks) {
size = _('tickSize');
children.push(axis_ticks(spec, config, encode.ticks, ticksRef, size, band));
}
// include axis labels if requested
if (datum.labels) {
size = datum.ticks ? size : 0;
children.push(axis_labels(spec, config, encode.labels, ticksRef, size, band));
}
// include axis domain path if requested
if (datum.domain) {
children.push(axis_domain(spec, config, encode.domain, dataRef));
}
// include axis title if defined
if (datum.title) {
children.push(axis_title(spec, config, encode.title, dataRef));
}
// build axis specification
group = guide_group(roles_AxisRole, style, name, dataRef, interactive, axisEncode, children);
if (spec.zindex) group.zindex = spec.zindex;
// parse axis specification
return parsers_mark(group, scope);
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/spec.js
/* harmony default export */ var parsers_spec = (function(spec, scope, preprocessed) {
var signals = Object(vega_util["i" /* array */])(spec.signals),
scales = Object(vega_util["i" /* array */])(spec.scales);
// parse signal definitions, if not already preprocessed
if (!preprocessed) signals.forEach(_ => parsers_signal(_, scope));
// parse cartographic projection definitions
Object(vega_util["i" /* array */])(spec.projections).forEach(_ => parsers_projection(_, scope));
// initialize scale references
scales.forEach(_ => scale_initScale(_, scope));
// parse data sources
Object(vega_util["i" /* array */])(spec.data).forEach(_ => data_parseData(_, scope));
// parse scale definitions
scales.forEach(_ => scale_parseScale(_, scope));
// parse signal updates
(preprocessed || signals).forEach(_ => signal_updates(_, scope));
// parse axis definitions
Object(vega_util["i" /* array */])(spec.axes).forEach(_ => parsers_axis(_, scope));
// parse mark definitions
Object(vega_util["i" /* array */])(spec.marks).forEach(_ => parsers_mark(_, scope));
// parse legend definitions
Object(vega_util["i" /* array */])(spec.legends).forEach(_ => parsers_legend(_, scope));
// parse title, if defined
if (spec.title) parsers_title(spec.title, scope);
// parse collected lambda (anonymous) expressions
scope.parseLambdas();
return scope;
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parsers/view.js
function view_parseView(spec, scope) {
var config = scope.config,
op, input, encode, parent, root, signals;
// add scenegraph root
root = util_ref(scope.root = scope.add(util_operator()));
// parse top-level signal definitions
signals = view_collectSignals(spec, config);
signals.forEach(_ => parsers_signal(_, scope));
// assign description, event and legend configuration
scope.description = spec.description || config.description;
scope.eventConfig = config.events;
scope.legends = scope.objectProperty(config.legend && config.legend.layout);
// store root group item
input = scope.add(transforms_Collect());
// encode root group item
encode = encode_util_extendEncode({
enter: { x: {value: 0}, y: {value: 0} },
update: { width: {signal: 'width'}, height: {signal: 'height'} }
}, spec.encode);
encode = scope.add(transforms_Encode(
encode_util_encoders(encode, GroupMark, roles_FrameRole, spec.style, scope, {pulse: util_ref(input)}))
);
// perform view layout
parent = scope.add(transforms_ViewLayout({
layout: scope.objectProperty(spec.layout),
legends: scope.legends,
autosize: scope.signalRef('autosize'),
mark: root,
pulse: util_ref(encode)
}));
scope.operators.pop();
// parse remainder of specification
scope.pushState(util_ref(encode), util_ref(parent), null);
parsers_spec(spec, scope, signals);
scope.operators.push(parent);
// bound / render / sieve root item
op = scope.add(transforms_Bound({mark: root, pulse: util_ref(parent)}));
op = scope.add(transforms_Render({pulse: util_ref(op)}));
op = scope.add(transforms_Sieve({pulse: util_ref(op)}));
// track metadata for root item
scope.addData('root', new DataScope_DataScope(scope, input, input, op));
return scope;
}
function view_signalObject(name, value) {
return value && value.signal
? { name, update: value.signal }
: { name, value };
}
/**
* Collect top-level signals, merging values as needed. Signals
* defined in the config signals arrays are added only if that
* signal is not explicitly defined in the specification.
* Built-in signals (autosize, background, padding, width, height)
* receive special treatment. They are initialized using the
* top-level spec property, or, if undefined in the spec, using
* the corresponding top-level config property. If this property
* is a signal reference object, the signal expression maps to the
* signal 'update' property. If the spec's top-level signal array
* contains an entry that matches a built-in signal, that entry
* will be merged with the built-in specification, potentially
* overwriting existing 'value' or 'update' properties.
*/
function view_collectSignals(spec, config) {
const _ = name => util_value(spec[name], config[name]),
signals = [
view_signalObject('background', _('background')),
view_signalObject('autosize', parsers_autosize(_('autosize'))),
view_signalObject('padding', parsers_padding(_('padding'))),
view_signalObject('width', _('width') || 0),
view_signalObject('height', _('height') || 0)
],
pre = signals.reduce((p, s) => (p[s.name] = s, p), {}),
map = {};
// add spec signal array
Object(vega_util["i" /* array */])(spec.signals).forEach(s => {
if (Object(vega_util["v" /* hasOwnProperty */])(pre, s.name)) {
// merge if built-in signal
s = Object(vega_util["o" /* extend */])(pre[s.name], s);
} else {
// otherwise add to signal list
signals.push(s);
}
map[s.name] = s;
});
// add config signal array
Object(vega_util["i" /* array */])(config.signals).forEach(s => {
if (!Object(vega_util["v" /* hasOwnProperty */])(map, s.name) && !Object(vega_util["v" /* hasOwnProperty */])(pre, s.name)) {
// add to signal list if not already defined
signals.push(s);
}
});
return signals;
}
// CONCATENATED MODULE: ./node_modules/vega-parser/src/Scope.js
function Scope_Scope(config) {
this.config = config;
this.bindings = [];
this.field = {};
this.signals = {};
this.lambdas = {};
this.scales = {};
this.events = {};
this.data = {};
this.streams = [];
this.updates = [];
this.operators = [];
this.eventConfig = null;
this._id = 0;
this._subid = 0;
this._nextsub = [0];
this._parent = [];
this._encode = [];
this._lookup = [];
this._markpath = [];
}
function Scope_Subscope(scope) {
this.config = scope.config;
this.legends = scope.legends;
this.field = Object.create(scope.field);
this.signals = Object.create(scope.signals);
this.lambdas = Object.create(scope.lambdas);
this.scales = Object.create(scope.scales);
this.events = Object.create(scope.events);
this.data = Object.create(scope.data);
this.streams = [];
this.updates = [];
this.operators = [];
this._id = 0;
this._subid = ++scope._nextsub[0];
this._nextsub = scope._nextsub;
this._parent = scope._parent.slice();
this._encode = scope._encode.slice();
this._lookup = scope._lookup.slice();
this._markpath = scope._markpath;
}
var Scope_prototype = Scope_Scope.prototype = Scope_Subscope.prototype;
// ----
Scope_prototype.fork = function() {
return new Scope_Subscope(this);
};
Scope_prototype.isSubscope = function() {
return this._subid > 0;
};
Scope_prototype.toRuntime = function() {
this.finish();
return {
description: this.description,
operators: this.operators,
streams: this.streams,
updates: this.updates,
bindings: this.bindings,
eventConfig: this.eventConfig
};
};
Scope_prototype.id = function() {
return (this._subid ? this._subid + ':' : 0) + this._id++;
};
Scope_prototype.add = function(op) {
this.operators.push(op);
op.id = this.id();
// if pre-registration references exist, resolve them now
if (op.refs) {
op.refs.forEach(function(ref) { ref.$ref = op.id; });
op.refs = null;
}
return op;
};
Scope_prototype.proxy = function(op) {
var vref = op instanceof util_Entry ? util_ref(op) : op;
return this.add(transforms_Proxy({value: vref}));
};
Scope_prototype.addStream = function(stream) {
this.streams.push(stream);
stream.id = this.id();
return stream;
};
Scope_prototype.addUpdate = function(update) {
this.updates.push(update);
return update;
};
// Apply metadata
Scope_prototype.finish = function() {
var name, ds;
// annotate root
if (this.root) this.root.root = true;
// annotate signals
for (name in this.signals) {
this.signals[name].signal = name;
}
// annotate scales
for (name in this.scales) {
this.scales[name].scale = name;
}
// annotate data sets
function annotate(op, name, type) {
var data, list;
if (op) {
data = op.data || (op.data = {});
list = data[name] || (data[name] = []);
list.push(type);
}
}
for (name in this.data) {
ds = this.data[name];
annotate(ds.input, name, 'input');
annotate(ds.output, name, 'output');
annotate(ds.values, name, 'values');
for (var field in ds.index) {
annotate(ds.index[field], name, 'index:' + field);
}
}
return this;
};
// ----
Scope_prototype.pushState = function(encode, parent, lookup) {
this._encode.push(util_ref(this.add(transforms_Sieve({pulse: encode}))));
this._parent.push(parent);
this._lookup.push(lookup ? util_ref(this.proxy(lookup)) : null);
this._markpath.push(-1);
};
Scope_prototype.popState = function() {
this._encode.pop();
this._parent.pop();
this._lookup.pop();
this._markpath.pop();
};
Scope_prototype.parent = function() {
return Object(vega_util["U" /* peek */])(this._parent);
};
Scope_prototype.encode = function() {
return Object(vega_util["U" /* peek */])(this._encode);
};
Scope_prototype.lookup = function() {
return Object(vega_util["U" /* peek */])(this._lookup);
};
Scope_prototype.markpath = function() {
var p = this._markpath;
return ++p[p.length-1];
};
// ----
Scope_prototype.fieldRef = function(field, name) {
if (Object(vega_util["H" /* isString */])(field)) return util_fieldRef(field, name);
if (!field.signal) {
Object(vega_util["n" /* error */])('Unsupported field reference: ' + Object(vega_util["Z" /* stringValue */])(field));
}
var s = field.signal,
f = this.field[s],
params;
if (!f) {
params = {name: this.signalRef(s)};
if (name) params.as = name;
this.field[s] = f = util_ref(this.add(transforms_Field(params)));
}
return f;
};
Scope_prototype.compareRef = function(cmp) {
function check(_) {
if (util_isSignal(_)) {
signal = true;
return scope.signalRef(_.signal);
} else if (util_isExpr(_)) {
signal = true;
return scope.exprRef(_.expr);
} else {
return _;
}
}
var scope = this,
signal = false,
fields = Object(vega_util["i" /* array */])(cmp.field).map(check),
orders = Object(vega_util["i" /* array */])(cmp.order).map(check);
return signal
? util_ref(this.add(transforms_Compare({fields: fields, orders: orders})))
: util_compareRef(fields, orders);
};
Scope_prototype.keyRef = function(fields, flat) {
function check(_) {
if (util_isSignal(_)) {
signal = true;
return util_ref(sig[_.signal]);
} else {
return _;
}
}
var sig = this.signals,
signal = false;
fields = Object(vega_util["i" /* array */])(fields).map(check);
return signal
? util_ref(this.add(transforms_Key({fields: fields, flat: flat})))
: util_keyRef(fields, flat);
};
Scope_prototype.sortRef = function(sort) {
if (!sort) return sort;
// including id ensures stable sorting
var a = util_aggrField(sort.op, sort.field),
o = sort.order || util_Ascending;
return o.signal
? util_ref(this.add(transforms_Compare({
fields: a,
orders: this.signalRef(o.signal)
})))
: util_compareRef(a, o);
};
// ----
Scope_prototype.event = function(source, type) {
var key = source + ':' + type;
if (!this.events[key]) {
var id = this.id();
this.streams.push({
id: id,
source: source,
type: type
});
this.events[key] = id;
}
return this.events[key];
};
// ----
Scope_prototype.hasOwnSignal = function(name) {
return Object(vega_util["v" /* hasOwnProperty */])(this.signals, name);
};
Scope_prototype.addSignal = function(name, value) {
if (this.hasOwnSignal(name)) {
Object(vega_util["n" /* error */])('Duplicate signal name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
var op = value instanceof util_Entry ? value : this.add(util_operator(value));
return this.signals[name] = op;
};
Scope_prototype.getSignal = function(name) {
if (!this.signals[name]) {
Object(vega_util["n" /* error */])('Unrecognized signal name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
return this.signals[name];
};
Scope_prototype.signalRef = function(s) {
if (this.signals[s]) {
return util_ref(this.signals[s]);
} else if (!Object(vega_util["v" /* hasOwnProperty */])(this.lambdas, s)) {
this.lambdas[s] = this.add(util_operator(null));
}
return util_ref(this.lambdas[s]);
};
Scope_prototype.parseLambdas = function() {
var code = Object.keys(this.lambdas);
for (var i=0, n=code.length; i<n; ++i) {
var s = code[i],
e = parsers_expression(s, this),
op = this.lambdas[s];
op.params = e.$params;
op.update = e.$expr;
}
};
Scope_prototype.property = function(spec) {
return spec && spec.signal ? this.signalRef(spec.signal) : spec;
};
Scope_prototype.objectProperty = function(spec) {
return (!spec || !Object(vega_util["F" /* isObject */])(spec)) ? spec
: this.signalRef(spec.signal || Scope_propertyLambda(spec));
};
function Scope_propertyLambda(spec) {
return (Object(vega_util["A" /* isArray */])(spec) ? Scope_arrayLambda : Scope_objectLambda)(spec);
}
function Scope_arrayLambda(array) {
var code = '[',
i = 0,
n = array.length,
value;
for (; i<n; ++i) {
value = array[i];
code += (i > 0 ? ',' : '')
+ (Object(vega_util["F" /* isObject */])(value)
? (value.signal || Scope_propertyLambda(value))
: Object(vega_util["Z" /* stringValue */])(value));
}
return code + ']';
}
function Scope_objectLambda(obj) {
var code = '{',
i = 0,
key, value;
for (key in obj) {
value = obj[key];
code += (++i > 1 ? ',' : '')
+ Object(vega_util["Z" /* stringValue */])(key) + ':'
+ (Object(vega_util["F" /* isObject */])(value)
? (value.signal || Scope_propertyLambda(value))
: Object(vega_util["Z" /* stringValue */])(value));
}
return code + '}';
}
Scope_prototype.exprRef = function(code, name) {
var params = {expr: parsers_expression(code, this)};
if (name) params.expr.$name = name;
return util_ref(this.add(transforms_Expression(params)));
}
Scope_prototype.addBinding = function(name, bind) {
if (!this.bindings) {
Object(vega_util["n" /* error */])('Nested signals do not support binding: ' + Object(vega_util["Z" /* stringValue */])(name));
}
this.bindings.push(Object(vega_util["o" /* extend */])({signal: name}, bind));
};
// ----
Scope_prototype.addScaleProj = function(name, transform) {
if (Object(vega_util["v" /* hasOwnProperty */])(this.scales, name)) {
Object(vega_util["n" /* error */])('Duplicate scale or projection name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
this.scales[name] = this.add(transform);
};
Scope_prototype.addScale = function(name, params) {
this.addScaleProj(name, transforms_Scale(params));
};
Scope_prototype.addProjection = function(name, params) {
this.addScaleProj(name, transforms_Projection(params));
};
Scope_prototype.getScale = function(name) {
if (!this.scales[name]) {
Object(vega_util["n" /* error */])('Unrecognized scale name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
return this.scales[name];
};
Scope_prototype.projectionRef =
Scope_prototype.scaleRef = function(name) {
return util_ref(this.getScale(name));
};
Scope_prototype.projectionType =
Scope_prototype.scaleType = function(name) {
return this.getScale(name).params.type;
};
// ----
Scope_prototype.addData = function(name, dataScope) {
if (Object(vega_util["v" /* hasOwnProperty */])(this.data, name)) {
Object(vega_util["n" /* error */])('Duplicate data set name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
return (this.data[name] = dataScope);
};
Scope_prototype.getData = function(name) {
if (!this.data[name]) {
Object(vega_util["n" /* error */])('Undefined data set name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
return this.data[name];
};
Scope_prototype.addDataPipeline = function(name, entries) {
if (Object(vega_util["v" /* hasOwnProperty */])(this.data, name)) {
Object(vega_util["n" /* error */])('Duplicate data set name: ' + Object(vega_util["Z" /* stringValue */])(name));
}
return this.addData(name, DataScope_DataScope.fromEntries(this, entries));
};
// CONCATENATED MODULE: ./node_modules/vega-parser/src/config.js
var defaultFont = 'sans-serif',
defaultSymbolSize = 30,
defaultStrokeWidth = 2,
defaultColor = '#4c78a8',
black = '#000',
config_gray = '#888',
lightGray = '#ddd';
/**
* Standard configuration defaults for Vega specification parsing.
* Users can provide their own (sub-)set of these default values
* by passing in a config object to the top-level parse method.
*/
/* harmony default export */ var src_config = (function() {
return {
// default visualization description
description: 'Vega visualization',
// default padding around visualization
padding: 0,
// default for automatic sizing; options: 'none', 'pad', 'fit'
// or provide an object (e.g., {'type': 'pad', 'resize': true})
autosize: 'pad',
// default view background color
// covers the entire view component
background: null,
// default event handling configuration
// preventDefault for view-sourced event types except 'wheel'
events: {
defaults: {allow: ['wheel']}
},
// defaults for top-level group marks
// accepts mark properties (fill, stroke, etc)
// covers the data rectangle within group width/height
group: null,
// defaults for basic mark types
// each subset accepts mark properties (fill, stroke, etc)
mark: null,
arc: { fill: defaultColor },
area: { fill: defaultColor },
image: null,
line: {
stroke: defaultColor,
strokeWidth: defaultStrokeWidth
},
path: { stroke: defaultColor },
rect: { fill: defaultColor },
rule: { stroke: black },
shape: { stroke: defaultColor },
symbol: {
fill: defaultColor,
size: 64
},
text: {
fill: black,
font: defaultFont,
fontSize: 11
},
trail: {
fill: defaultColor,
size: defaultStrokeWidth
},
// style definitions
style: {
// axis & legend labels
'guide-label': {
fill: black,
font: defaultFont,
fontSize: 10
},
// axis & legend titles
'guide-title': {
fill: black,
font: defaultFont,
fontSize: 11,
fontWeight: 'bold'
},
// headers, including chart title
'group-title': {
fill: black,
font: defaultFont,
fontSize: 13,
fontWeight: 'bold'
},
// chart subtitle
'group-subtitle': {
fill: black,
font: defaultFont,
fontSize: 12
},
// defaults for styled point marks in Vega-Lite
point: {
size: defaultSymbolSize,
strokeWidth: defaultStrokeWidth,
shape: 'circle'
},
circle: {
size: defaultSymbolSize,
strokeWidth: defaultStrokeWidth
},
square: {
size: defaultSymbolSize,
strokeWidth: defaultStrokeWidth,
shape: 'square'
},
// defaults for styled group marks in Vega-Lite
cell: {
fill: 'transparent',
stroke: lightGray
}
},
// defaults for title
title: {
orient: 'top',
anchor: 'middle',
offset: 4,
subtitlePadding: 3
},
// defaults for axes
axis: {
minExtent: 0,
maxExtent: 200,
bandPosition: 0.5,
domain: true,
domainWidth: 1,
domainColor: config_gray,
grid: false,
gridWidth: 1,
gridColor: lightGray,
labels: true,
labelAngle: 0,
labelLimit: 180,
labelOffset: 0,
labelPadding: 2,
ticks: true,
tickColor: config_gray,
tickOffset: 0,
tickRound: true,
tickSize: 5,
tickWidth: 1,
titlePadding: 4
},
// correction for centering bias
axisBand: {
tickOffset: -0.5
},
// defaults for cartographic projection
projection: {
type: 'mercator'
},
// defaults for legends
legend: {
orient: 'right',
padding: 0,
gridAlign: 'each',
columnPadding: 10,
rowPadding: 2,
symbolDirection: 'vertical',
gradientDirection: 'vertical',
gradientLength: 200,
gradientThickness: 16,
gradientStrokeColor: lightGray,
gradientStrokeWidth: 0,
gradientLabelOffset: 2,
labelAlign: 'left',
labelBaseline: 'middle',
labelLimit: 160,
labelOffset: 4,
labelOverlap: true,
symbolLimit: 30,
symbolType: 'circle',
symbolSize: 100,
symbolOffset: 0,
symbolStrokeWidth: 1.5,
symbolBaseFillColor: 'transparent',
symbolBaseStrokeColor: config_gray,
titleLimit: 180,
titleOrient: 'top',
titlePadding: 5,
layout: {
offset: 18,
direction: 'horizontal',
left: { direction: 'vertical' },
right: { direction: 'vertical' }
}
},
// defaults for scale ranges
range: {
category: {
scheme: 'tableau10'
},
ordinal: {
scheme: 'blues'
},
heatmap: {
scheme: 'yellowgreenblue'
},
ramp: {
scheme: 'blues'
},
diverging: {
scheme: 'blueorange',
extent: [1, 0]
},
symbol: [
'circle',
'square',
'triangle-up',
'cross',
'diamond',
'triangle-right',
'triangle-down',
'triangle-left'
]
}
};
});
// CONCATENATED MODULE: ./node_modules/vega-parser/src/parse.js
/* harmony default export */ var src_parse = (function(spec, config) {
if (!Object(vega_util["F" /* isObject */])(spec)) {
Object(vega_util["n" /* error */])('Input Vega specification must be an object.');
}
config = Object(vega_util["N" /* mergeConfig */])(src_config(), config, spec.config);
return view_parseView(spec, new Scope_Scope(config)).toRuntime();
});
// CONCATENATED MODULE: ./node_modules/vega-parser/index.js
// CONCATENATED MODULE: ./node_modules/vega/index.js
// -- Transforms -----
Object(vega_util["o" /* extend */])(register_transforms, vega_transforms_namespaceObject, vega_view_transforms_namespaceObject, vega_encode_namespaceObject, vega_geo_namespaceObject, vega_force_namespaceObject, vega_hierarchy_namespaceObject, vega_regression_namespaceObject, vega_voronoi_namespaceObject, vega_wordcloud_namespaceObject, vega_crossfilter_namespaceObject);
// -- Exports -----
// EXTERNAL MODULE: ./node_modules/vega-lite/build/package.json
var build_package = __webpack_require__(287);
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/accessor.js
/* harmony default export */ var src_accessor = (function(fn, fields, name) {
fn.fields = fields || [];
fn.fname = name;
return fn;
});
function accessorName(fn) {
return fn == null ? null : fn.fname;
}
function accessorFields(fn) {
return fn == null ? null : fn.fields;
}
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/error.js
/* harmony default export */ var src_error = (function(message) {
throw Error(message);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/splitAccessPath.js
/* harmony default export */ var splitAccessPath = (function(p) {
var path = [],
q = null,
b = 0,
n = p.length,
s = '',
i, j, c;
p = p + '';
function push() {
path.push(s + p.substring(i, j));
s = '';
i = j + 1;
}
for (i=j=0; j<n; ++j) {
c = p[j];
if (c === '\\') {
s += p.substring(i, j);
s += p.substring(++j, ++j);
i = j;
} else if (c === q) {
push();
q = null;
b = -1;
} else if (q) {
continue;
} else if (i === b && c === '"') {
i = j + 1;
q = c;
} else if (i === b && c === "'") {
i = j + 1;
q = c;
} else if (c === '.' && !b) {
if (j > i) {
push();
} else {
i = j + 1;
}
} else if (c === '[') {
if (j > i) push();
b = i = j + 1;
} else if (c === ']') {
if (!b) src_error('Access path missing open bracket: ' + p);
if (b > 0) push();
b = 0;
i = j + 1;
}
}
if (b) src_error('Access path missing closing bracket: ' + p);
if (q) src_error('Access path missing closing quote: ' + p);
if (j > i) {
j++;
push();
}
return path;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isArray.js
/* harmony default export */ var isArray = (Array.isArray);
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isObject.js
/* harmony default export */ var isObject = (function(_) {
return _ === Object(_);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isString.js
/* harmony default export */ var isString = (function(_) {
return typeof _ === 'string';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/stringValue.js
function stringValue_$(x) {
return isArray(x) ? '[' + x.map(stringValue_$) + ']'
: isObject(x) || isString(x) ?
// Output valid JSON and JS source strings.
// See http://timelessrepo.com/json-isnt-a-javascript-subset
JSON.stringify(x).replace('\u2028','\\u2028').replace('\u2029', '\\u2029')
: x;
}
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/field.js
/* harmony default export */ var src_field = (function(field, name) {
var path = splitAccessPath(field),
code = 'return _[' + path.map(stringValue_$).join('][') + '];';
return src_accessor(
Function('_', code),
[(field = path.length===1 ? path[0] : field)],
name || field
);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/accessors.js
var accessors_empty = [];
var accessors_id = src_field('id');
var accessors_identity = src_accessor(function(_) { return _; }, accessors_empty, 'identity');
var accessors_zero = src_accessor(function() { return 0; }, accessors_empty, 'zero');
var accessors_one = src_accessor(function() { return 1; }, accessors_empty, 'one');
var accessors_truthy = src_accessor(function() { return true; }, accessors_empty, 'true');
var accessors_falsy = src_accessor(function() { return false; }, accessors_empty, 'false');
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/logger.js
function logger_log(method, level, input) {
var args = [level].concat([].slice.call(input));
console[method].apply(console, args); // eslint-disable-line no-console
}
var logger_None = 0;
var logger_Error = 1;
var Warn = 2;
var Info = 3;
var Debug = 4;
/* harmony default export */ var logger = (function(_, method) {
var level = _ || logger_None;
return {
level: function(_) {
if (arguments.length) {
level = +_;
return this;
} else {
return level;
}
},
error: function() {
if (level >= logger_Error) logger_log(method || 'error', 'ERROR', arguments);
return this;
},
warn: function() {
if (level >= Warn) logger_log(method || 'warn', 'WARN', arguments);
return this;
},
info: function() {
if (level >= Info) logger_log(method || 'log', 'INFO', arguments);
return this;
},
debug: function() {
if (level >= Debug) logger_log(method || 'log', 'DEBUG', arguments);
return this;
}
}
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/mergeConfig.js
function mergeConfig_mergeConfig(...configs) {
return configs.reduce((out, source) => {
for (var key in source) {
if (key === 'signals') {
// for signals, we merge the signals arrays
// source signals take precedence over
// existing signals with the same name
out.signals = mergeConfig_mergeNamed(out.signals, source.signals);
} else {
// otherwise, merge objects subject to recursion constraints
// for legend block, recurse for the layout entry only
// for style block, recurse for all properties
// otherwise, no recursion: objects overwrite, no merging
var r = key === 'legend' ? {'layout': 1}
: key === 'style' ? true
: null;
mergeConfig_writeConfig(out, key, source[key], r);
}
}
return out;
}, {});
}
function mergeConfig_writeConfig(output, key, value, recurse) {
var k, o;
if (isObject(value) && !isArray(value)) {
o = isObject(output[key]) ? output[key] : (output[key] = {});
for (k in value) {
if (recurse && (recurse === true || recurse[k])) {
mergeConfig_writeConfig(o, k, value[k]);
} else {
o[k] = value[k];
}
}
} else {
output[key] = value;
}
}
function mergeConfig_mergeNamed(a, b) {
if (a == null) return b;
const map = {}, out = [];
function add(_) {
if (!map[_.name]) {
map[_.name] = 1;
out.push(_);
}
}
b.forEach(add);
a.forEach(add);
return out;
}
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/peek.js
/* harmony default export */ var src_peek = (function(array) {
return array[array.length - 1];
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/toNumber.js
/* harmony default export */ var toNumber = (function(_) {
return _ == null || _ === '' ? null : +_;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/transform.js
function transform_exp(sign) {
return function(x) { return sign * Math.exp(x); };
}
function transform_log(sign) {
return function(x) { return Math.log(sign * x); };
}
function transform_symlog(c) {
return function(x) { return Math.sign(x) * Math.log1p(Math.abs(x / c)); };
}
function transform_symexp(c) {
return function(x) { return Math.sign(x) * Math.expm1(Math.abs(x)) * c; };
}
function transform_pow(exponent) {
return function(x) {
return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
};
}
function transform_pan(domain, delta, lift, ground) {
var d0 = lift(domain[0]),
d1 = lift(src_peek(domain)),
dd = (d1 - d0) * delta;
return [
ground(d0 - dd),
ground(d1 - dd)
];
}
function transform_panLinear(domain, delta) {
return transform_pan(domain, delta, toNumber, accessors_identity);
}
function transform_panLog(domain, delta) {
var sign = Math.sign(domain[0]);
return transform_pan(domain, delta, transform_log(sign), transform_exp(sign));
}
function transform_panPow(domain, delta, exponent) {
return transform_pan(domain, delta, transform_pow(exponent), transform_pow(1/exponent));
}
function transform_panSymlog(domain, delta, constant) {
return transform_pan(domain, delta, transform_symlog(constant), transform_symexp(constant));
}
function transform_zoom(domain, anchor, scale, lift, ground) {
var d0 = lift(domain[0]),
d1 = lift(src_peek(domain)),
da = anchor != null ? lift(anchor) : (d0 + d1) / 2;
return [
ground(da + (d0 - da) * scale),
ground(da + (d1 - da) * scale)
];
}
function transform_zoomLinear(domain, anchor, scale) {
return transform_zoom(domain, anchor, scale, toNumber, accessors_identity);
}
function transform_zoomLog(domain, anchor, scale) {
var sign = Math.sign(domain[0]);
return transform_zoom(domain, anchor, scale, transform_log(sign), transform_exp(sign));
}
function transform_zoomPow(domain, anchor, scale, exponent) {
return transform_zoom(domain, anchor, scale, transform_pow(exponent), transform_pow(1/exponent));
}
function transform_zoomSymlog(domain, anchor, scale, constant) {
return transform_zoom(domain, anchor, scale, transform_symlog(constant), transform_symexp(constant));
}
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/quarter.js
function quarter_quarter(date) {
return 1 + ~~(new Date(date).getMonth() / 3);
}
function utcquarter(date) {
return 1 + ~~(new Date(date).getUTCMonth() / 3);
}
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/array.js
/* harmony default export */ var vega_util_src_array = (function(_) {
return _ != null ? (isArray(_) ? _ : [_]) : [];
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/clampRange.js
/**
* Span-preserving range clamp. If the span of the input range is less
* than (max - min) and an endpoint exceeds either the min or max value,
* the range is translated such that the span is preserved and one
* endpoint touches the boundary of the min/max range.
* If the span exceeds (max - min), the range [min, max] is returned.
*/
/* harmony default export */ var clampRange = (function(range, min, max) {
var lo = range[0],
hi = range[1],
span;
if (hi < lo) {
span = hi;
hi = lo;
lo = span;
}
span = hi - lo;
return span >= (max - min)
? [min, max]
: [
(lo = Math.min(Math.max(lo, min), max - span)),
lo + span
];
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isFunction.js
/* harmony default export */ var isFunction = (function(_) {
return typeof _ === 'function';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/compare.js
/* harmony default export */ var src_compare = (function(fields, orders) {
var idx = [],
cmp = (fields = vega_util_src_array(fields)).map(function(f, i) {
if (f == null) {
return null;
} else {
idx.push(i);
return isFunction(f) ? f
: splitAccessPath(f).map(stringValue_$).join('][');
}
}),
n = idx.length - 1,
ord = vega_util_src_array(orders),
code = 'var u,v;return ',
i, j, f, u, v, d, t, lt, gt;
if (n < 0) return null;
for (j=0; j<=n; ++j) {
i = idx[j];
f = cmp[i];
if (isFunction(f)) {
d = 'f' + i;
u = '(u=this.' + d + '(a))';
v = '(v=this.' + d + '(b))';
(t = t || {})[d] = f;
} else {
u = '(u=a['+f+'])';
v = '(v=b['+f+'])';
}
d = '((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))';
if (ord[i] !== 'descending') {
gt = 1;
lt = -1;
} else {
gt = -1;
lt = 1;
}
code += '(' + u+'<'+v+'||u==null)&&v!=null?' + lt
+ ':(u>v||v==null)&&u!=null?' + gt
+ ':'+d+'!==u&&v===v?' + lt
+ ':v!==v&&u===u?' + gt
+ (i < n ? ':' : ':0');
}
f = Function('a', 'b', code + ';');
if (t) f = f.bind(t);
fields = fields.reduce(function(map, field) {
if (isFunction(field)) {
(accessorFields(field) || []).forEach(function(_) { map[_] = 1; });
} else if (field != null) {
map[field + ''] = 1;
}
return map;
}, {});
return src_accessor(f, Object.keys(fields));
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/constant.js
/* harmony default export */ var vega_util_src_constant = (function(_) {
return isFunction(_) ? _ : function() { return _; };
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/debounce.js
/* harmony default export */ var debounce = (function(delay, handler) {
var tid, evt;
function callback() {
handler(evt);
tid = evt = null;
}
return function(e) {
evt = e;
if (tid) clearTimeout(tid);
tid = setTimeout(callback, delay);
};
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/extend.js
/* harmony default export */ var src_extend = (function(_) {
for (var x, k, i=1, len=arguments.length; i<len; ++i) {
x = arguments[i];
for (k in x) { _[k] = x[k]; }
}
return _;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/extent.js
/**
* Return an array with minimum and maximum values, in the
* form [min, max]. Ignores null, undefined, and NaN values.
*/
/* harmony default export */ var vega_util_src_extent = (function(array, f) {
var i = 0, n, v, min, max;
if (array && (n = array.length)) {
if (f == null) {
// find first valid value
for (v = array[i]; i < n && (v == null || v !== v); v = array[++i]);
min = max = v;
// visit all other values
for (; i<n; ++i) {
v = array[i];
// skip null/undefined; NaN will fail all comparisons
if (v != null) {
if (v < min) min = v;
if (v > max) max = v;
}
}
} else {
// find first valid value
for (v = f(array[i]); i < n && (v == null || v !== v); v = f(array[++i]));
min = max = v;
// visit all other values
for (; i<n; ++i) {
v = f(array[i]);
// skip null/undefined; NaN will fail all comparisons
if (v != null) {
if (v < min) min = v;
if (v > max) max = v;
}
}
}
}
return [min, max];
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/extentIndex.js
/* harmony default export */ var extentIndex = (function(array, f) {
var i = -1,
n = array.length,
a, b, c, u, v;
if (f == null) {
while (++i < n) {
b = array[i];
if (b != null && b >= b) {
a = c = b;
break;
}
}
if (i === n) return [-1, -1];
u = v = i;
while (++i < n) {
b = array[i];
if (b != null) {
if (a > b) {
a = b;
u = i;
}
if (c < b) {
c = b;
v = i;
}
}
}
} else {
while (++i < n) {
b = f(array[i], i, array);
if (b != null && b >= b) {
a = c = b;
break;
}
}
if (i === n) return [-1, -1];
u = v = i;
while (++i < n) {
b = f(array[i], i, array);
if (b != null) {
if (a > b) {
a = b;
u = i;
}
if (c < b) {
c = b;
v = i;
}
}
}
}
return [u, v];
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/hasOwnProperty.js
const hop = Object.prototype.hasOwnProperty;
/* harmony default export */ var src_hasOwnProperty = (function(object, property) {
return hop.call(object, property);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/fastmap.js
var fastmap_NULL = {};
/* harmony default export */ var fastmap = (function(input) {
var obj = {},
map,
test;
function has(key) {
return src_hasOwnProperty(obj, key) && obj[key] !== fastmap_NULL;
}
map = {
size: 0,
empty: 0,
object: obj,
has: has,
get: function(key) {
return has(key) ? obj[key] : undefined;
},
set: function(key, value) {
if (!has(key)) {
++map.size;
if (obj[key] === fastmap_NULL) --map.empty;
}
obj[key] = value;
return this;
},
delete: function(key) {
if (has(key)) {
--map.size;
++map.empty;
obj[key] = fastmap_NULL;
}
return this;
},
clear: function() {
map.size = map.empty = 0;
map.object = obj = {};
},
test: function(_) {
if (arguments.length) {
test = _;
return map;
} else {
return test;
}
},
clean: function() {
var next = {},
size = 0,
key, value;
for (key in obj) {
value = obj[key];
if (value !== fastmap_NULL && (!test || !test(value))) {
next[key] = value;
++size;
}
}
map.size = size;
map.empty = 0;
map.object = (obj = next);
}
};
if (input) Object.keys(input).forEach(function(key) {
map.set(key, input[key]);
});
return map;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/flush.js
/* harmony default export */ var src_flush = (function(range, value, threshold, left, right, center) {
if (!threshold && threshold !== 0) return center;
var a = range[0],
b = src_peek(range),
t = +threshold,
l, r;
// swap endpoints if range is reversed
if (b < a) {
l = a; a = b; b = l;
}
// compare value to endpoints
l = Math.abs(value - a);
r = Math.abs(b - value);
// adjust if value is within threshold distance of endpoint
return l < r && l <= t ? left : r <= t ? right : center;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/inherits.js
/* harmony default export */ var inherits = (function(child, parent) {
var proto = (child.prototype = Object.create(parent.prototype));
proto.constructor = child;
return proto;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/inrange.js
/**
* Predicate that returns true if the value lies within the span
* of the given range. The left and right flags control the use
* of inclusive (true) or exclusive (false) comparisons.
*/
/* harmony default export */ var inrange = (function(value, range, left, right) {
var r0 = range[0], r1 = range[range.length-1], t;
if (r0 > r1) {
t = r0;
r0 = r1;
r1 = t;
}
left = left === undefined || left;
right = right === undefined || right;
return (left ? r0 <= value : r0 < value) &&
(right ? value <= r1 : value < r1);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isBoolean.js
/* harmony default export */ var src_isBoolean = (function(_) {
return typeof _ === 'boolean';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isDate.js
/* harmony default export */ var src_isDate = (function(_) {
return Object.prototype.toString.call(_) === '[object Date]';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isNumber.js
/* harmony default export */ var src_isNumber = (function(_) {
return typeof _ === 'number';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/isRegExp.js
/* harmony default export */ var isRegExp = (function(_) {
return Object.prototype.toString.call(_) === '[object RegExp]';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/key.js
/* harmony default export */ var src_key = (function(fields, flat) {
if (fields) {
fields = flat
? vega_util_src_array(fields).map(function(f) { return f.replace(/\\(.)/g, '$1'); })
: vega_util_src_array(fields);
}
var fn = !(fields && fields.length)
? function() { return ''; }
: Function('_', 'return \'\'+' +
fields.map(function(f) {
return '_[' + (flat
? stringValue_$(f)
: splitAccessPath(f).map(stringValue_$).join('][')
) + ']';
}).join('+\'|\'+') + ';');
return src_accessor(fn, fields, 'key');
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/lerp.js
/* harmony default export */ var lerp = (function(array, frac) {
const lo = array[0],
hi = src_peek(array),
f = +frac;
return !f ? lo : f === 1 ? hi : lo + f * (hi - lo);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/merge.js
/* harmony default export */ var vega_util_src_merge = (function(compare, array0, array1, output) {
var n0 = array0.length,
n1 = array1.length;
if (!n1) return array0;
if (!n0) return array1;
var merged = output || new array0.constructor(n0 + n1),
i0 = 0, i1 = 0, i = 0;
for (; i0<n0 && i1<n1; ++i) {
merged[i] = compare(array0[i0], array1[i1]) > 0
? array1[i1++]
: array0[i0++];
}
for (; i0<n0; ++i0, ++i) {
merged[i] = array0[i0];
}
for (; i1<n1; ++i1, ++i) {
merged[i] = array1[i1];
}
return merged;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/repeat.js
/* harmony default export */ var src_repeat = (function(str, reps) {
var s = '';
while (--reps >= 0) s += str;
return s;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/pad.js
/* harmony default export */ var src_pad = (function(str, length, padchar, align) {
var c = padchar || ' ',
s = str + '',
n = length - s.length;
return n <= 0 ? s
: align === 'left' ? src_repeat(c, n) + s
: align === 'center' ? src_repeat(c, ~~(n/2)) + s + src_repeat(c, Math.ceil(n/2))
: s + src_repeat(c, n);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/span.js
/**
* Return the numerical span of an array: the difference between
* the last and first values.
*/
/* harmony default export */ var src_span = (function(array) {
return array && (src_peek(array) - array[0]) || 0;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/toBoolean.js
/* harmony default export */ var toBoolean = (function(_) {
return _ == null || _ === '' ? null : !_ || _ === 'false' || _ === '0' ? false : !!_;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/toDate.js
function toDate_defaultParser(_) {
return src_isNumber(_) ? _ : src_isDate(_) ? _ : Date.parse(_);
}
/* harmony default export */ var toDate = (function(_, parser) {
parser = parser || toDate_defaultParser;
return _ == null || _ === '' ? null : parser(_);
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/toString.js
/* harmony default export */ var src_toString = (function(_) {
return _ == null || _ === '' ? null : _ + '';
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/toSet.js
/* harmony default export */ var toSet = (function(_) {
for (var s={}, i=0, n=_.length; i<n; ++i) s[_[i]] = true;
return s;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/truncate.js
/* harmony default export */ var src_truncate = (function(str, length, align, ellipsis) {
var e = ellipsis != null ? ellipsis : '\u2026',
s = str + '',
n = s.length,
l = Math.max(0, length - e.length);
return n <= length ? s
: align === 'left' ? e + s.slice(n - l)
: align === 'center' ? s.slice(0, Math.ceil(l/2)) + e + s.slice(n - ~~(l/2))
: s.slice(0, l) + e;
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/src/visitArray.js
/* harmony default export */ var visitArray = (function(array, filter, visitor) {
if (array) {
var i = 0, n = array.length, t;
if (filter) {
for (; i<n; ++i) {
if (t = filter(array[i])) visitor(t, i, array);
}
} else {
array.forEach(visitor);
}
}
});
// CONCATENATED MODULE: ./node_modules/vega-lite/node_modules/vega-util/index.js
// CONCATENATED MODULE: ./node_modules/array-flat-polyfill/index.mjs
Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function r(){var t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,function(a,e){return Array.isArray(e)?a.push.apply(a,r.call(e,t-1)):a.push(e),a},[]):Array.prototype.slice.call(this)},writable:!0}),Array.prototype.flatMap||Object.defineProperty(Array.prototype,"flatMap",{configurable:!0,value:function(r){return Array.prototype.map.apply(this,arguments).flat()},writable:!0})
// EXTERNAL MODULE: ./node_modules/clone/clone.js
var clone_clone = __webpack_require__(286);
var clone_default = /*#__PURE__*/__webpack_require__.n(clone_clone);
// EXTERNAL MODULE: ./node_modules/fast-deep-equal/index.js
var fast_deep_equal = __webpack_require__(285);
var fast_deep_equal_default = /*#__PURE__*/__webpack_require__.n(fast_deep_equal);
// EXTERNAL MODULE: ./node_modules/fast-json-stable-stringify/index.js
var fast_json_stable_stringify = __webpack_require__(80);
var fast_json_stable_stringify_default = /*#__PURE__*/__webpack_require__.n(fast_json_stable_stringify);
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/logical.js
function isLogicalOr(op) {
return !!op.or;
}
function isLogicalAnd(op) {
return !!op.and;
}
function isLogicalNot(op) {
return !!op.not;
}
function forEachLeaf(op, fn) {
if (isLogicalNot(op)) {
forEachLeaf(op.not, fn);
}
else if (isLogicalAnd(op)) {
for (const subop of op.and) {
forEachLeaf(subop, fn);
}
}
else if (isLogicalOr(op)) {
for (const subop of op.or) {
forEachLeaf(subop, fn);
}
}
else {
fn(op);
}
}
function normalizeLogicalOperand(op, normalizer) {
if (isLogicalNot(op)) {
return { not: normalizeLogicalOperand(op.not, normalizer) };
}
else if (isLogicalAnd(op)) {
return { and: op.and.map(o => normalizeLogicalOperand(o, normalizer)) };
}
else if (isLogicalOr(op)) {
return { or: op.or.map(o => normalizeLogicalOperand(o, normalizer)) };
}
else {
return normalizer(op);
}
}
//# sourceMappingURL=logical.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/util.js
const util_deepEqual = fast_deep_equal_default.a;
const util_duplicate = clone_default.a;
/**
* Creates an object composed of the picked object properties.
*
* var object = {'a': 1, 'b': '2', 'c': 3};
* pick(object, ['a', 'c']);
* // → {'a': 1, 'c': 3}
*/
function util_pick(obj, props) {
const copy = {};
for (const prop of props) {
if (src_hasOwnProperty(obj, prop)) {
copy[prop] = obj[prop];
}
}
return copy;
}
/**
* The opposite of _.pick; this method creates an object composed of the own
* and inherited enumerable string keyed properties of object that are not omitted.
*/
function util_omit(obj, props) {
const copy = Object.assign({}, obj);
for (const prop of props) {
delete copy[prop];
}
return copy;
}
/**
* Monkey patch Set so that `stringify` produces a string representation of sets.
*/
Set.prototype['toJSON'] = function () {
return `Set(${[...this].map(x => fast_json_stable_stringify_default()(x)).join(',')})`;
};
/**
* Converts any object to a string representation that can be consumed by humans.
*/
const util_stringify = fast_json_stable_stringify_default.a;
/**
* Converts any object to a string of limited size, or a number.
*/
function util_hash(a) {
if (src_isNumber(a)) {
return a;
}
const str = isString(a) ? a : fast_json_stable_stringify_default()(a);
// short strings can be used as hash directly, longer strings are hashed to reduce memory usage
if (str.length < 250) {
return str;
}
// from http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
let h = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
h = (h << 5) - h + char;
h = h & h; // Convert to 32bit integer
}
return h;
}
function util_isNullOrFalse(x) {
return x === false || x === null;
}
function util_contains(array, item) {
return array.indexOf(item) > -1;
}
/** Returns the array without the elements in item */
function util_without(array, excludedItems) {
return array.filter(item => !util_contains(excludedItems, item));
}
function util_union(array, other) {
return array.concat(util_without(other, array));
}
/**
* Returns true if any item returns true.
*/
function util_some(arr, f) {
let i = 0;
for (const [k, a] of arr.entries()) {
if (f(a, k, i++)) {
return true;
}
}
return false;
}
/**
* Returns true if all items return true.
*/
function util_every(arr, f) {
let i = 0;
for (const [k, a] of arr.entries()) {
if (!f(a, k, i++)) {
return false;
}
}
return true;
}
/**
* recursively merges src into dest
*/
function util_mergeDeep(dest, ...src) {
for (const s of src) {
util_deepMerge_(dest, (s !== null && s !== void 0 ? s : {}));
}
return dest;
}
function util_deepMerge_(dest, src) {
for (const property of Object.keys(src)) {
mergeConfig_writeConfig(dest, property, src[property], true);
}
}
function util_unique(values, f) {
const results = [];
const u = {};
let v;
for (const val of values) {
v = f(val);
if (v in u) {
continue;
}
u[v] = 1;
results.push(val);
}
return results;
}
/**
* Returns true if the two dictionaries disagree. Applies only to defined values.
*/
function util_isEqual(dict, other) {
const dictKeys = util_keys(dict);
const otherKeys = util_keys(other);
if (dictKeys.length !== otherKeys.length) {
return false;
}
for (const key of dictKeys) {
if (dict[key] !== other[key]) {
return false;
}
}
return true;
}
function util_setEqual(a, b) {
if (a.size !== b.size) {
return false;
}
for (const e of a) {
if (!b.has(e)) {
return false;
}
}
return true;
}
function util_hasIntersection(a, b) {
for (const key of a) {
if (b.has(key)) {
return true;
}
}
return false;
}
function util_prefixGenerator(a) {
const prefixes = new Set();
for (const x of a) {
const splitField = splitAccessPath(x);
// Wrap every element other than the first in `[]`
const wrappedWithAccessors = splitField.map((y, i) => (i === 0 ? y : `[${y}]`));
const computedPrefixes = wrappedWithAccessors.map((_, i) => wrappedWithAccessors.slice(0, i + 1).join(''));
computedPrefixes.forEach(y => prefixes.add(y));
}
return prefixes;
}
/**
* Returns true if a and b have an intersection. Also return true if a or b are undefined
* since this means we don't know what fields a node produces or depends on.
*/
function util_fieldIntersection(a, b) {
if (a === undefined || b === undefined) {
return true;
}
return util_hasIntersection(util_prefixGenerator(a), util_prefixGenerator(b));
}
// This is a stricter version of Object.keys but with better types. See https://github.com/Microsoft/TypeScript/pull/12253#issuecomment-263132208
const util_keys = Object.keys;
function util_vals(x) {
const _vals = [];
for (const k in x) {
if (src_hasOwnProperty(x, k)) {
_vals.push(x[k]);
}
}
return _vals;
}
function util_entries(x) {
const _entries = [];
for (const k in x) {
if (src_hasOwnProperty(x, k)) {
_entries.push({
key: k,
value: x[k]
});
}
}
return _entries;
}
function util_isBoolean(b) {
return b === true || b === false;
}
/**
* Convert a string into a valid variable name
*/
function util_varName(s) {
// Replace non-alphanumeric characters (anything besides a-zA-Z0-9_) with _
const alphanumericS = s.replace(/\W/g, '_');
// Add _ if the string has leading numbers.
return (s.match(/^\d+/) ? '_' : '') + alphanumericS;
}
function util_logicalExpr(op, cb) {
if (isLogicalNot(op)) {
return '!(' + util_logicalExpr(op.not, cb) + ')';
}
else if (isLogicalAnd(op)) {
return '(' + op.and.map((and) => util_logicalExpr(and, cb)).join(') && (') + ')';
}
else if (isLogicalOr(op)) {
return '(' + op.or.map((or) => util_logicalExpr(or, cb)).join(') || (') + ')';
}
else {
return cb(op);
}
}
/**
* Delete nested property of an object, and delete the ancestors of the property if they become empty.
*/
function util_deleteNestedProperty(obj, orderedProps) {
if (orderedProps.length === 0) {
return true;
}
const prop = orderedProps.shift(); // eslint-disable-line @typescript-eslint/no-non-null-assertion
if (util_deleteNestedProperty(obj[prop], orderedProps)) {
delete obj[prop];
}
return util_keys(obj).length === 0;
}
function util_titlecase(s) {
return s.charAt(0).toUpperCase() + s.substr(1);
}
/**
* Converts a path to an access path with datum.
* @param path The field name.
* @param datum The string to use for `datum`.
*/
function util_accessPathWithDatum(path, datum = 'datum') {
const pieces = splitAccessPath(path);
const prefixes = [];
for (let i = 1; i <= pieces.length; i++) {
const prefix = `[${pieces
.slice(0, i)
.map(stringValue_$)
.join('][')}]`;
prefixes.push(`${datum}${prefix}`);
}
return prefixes.join(' && ');
}
/**
* Return access with datum to the flattened field.
*
* @param path The field name.
* @param datum The string to use for `datum`.
*/
function util_flatAccessWithDatum(path, datum = 'datum') {
return `${datum}[${stringValue_$(splitAccessPath(path).join('.'))}]`;
}
/**
* Replaces path accesses with access to non-nested field.
* For example, `foo["bar"].baz` becomes `foo\\.bar\\.baz`.
*/
function util_replacePathInField(path) {
return `${splitAccessPath(path)
.map(p => util_replaceAll(p, '.', '\\.'))
.join('\\.')}`;
}
/**
* Replace all ocurrences of a string with another string.
*
* @param string the string to replace in
* @param find the string to replace
* @param replacement the replacement
*/
function util_replaceAll(string, find, replacement) {
return string.replace(new RegExp(find.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replacement);
}
/**
* Remove path accesses with access from field.
* For example, `foo["bar"].baz` becomes `foo.bar.baz`.
*/
function util_removePathFromField(path) {
return `${splitAccessPath(path).join('.')}`;
}
/**
* Count the depth of the path. Returns 1 for fields that are not nested.
*/
function util_accessPathDepth(path) {
if (!path) {
return 0;
}
return splitAccessPath(path).length;
}
/**
* This is a replacement for chained || for numeric properties or properties that respect null so that 0 will be included.
*/
function util_getFirstDefined(...args) {
for (const arg of args) {
if (arg !== undefined) {
return arg;
}
}
return undefined;
}
// variable used to generate id
let util_idCounter = 42;
/**
* Returns a new random id every time it gets called.
*
* Has side effect!
*/
function util_uniqueId(prefix) {
const id = ++util_idCounter;
return prefix ? String(prefix) + id : id;
}
/**
* Resets the id counter used in uniqueId. This can be useful for testing.
*/
function util_resetIdCounter() {
util_idCounter = 42;
}
function util_internalField(name) {
return util_isInternalField(name) ? name : `__${name}`;
}
function util_isInternalField(name) {
return name.indexOf('__') === 0;
}
/**
* Normalize angle to be within [0,360).
*/
function util_normalizeAngle(angle) {
return ((angle % 360) + 360) % 360;
}
//# sourceMappingURL=util.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/mark.js
const mark_AREA = 'area';
const mark_BAR = 'bar';
const mark_IMAGE = 'image';
const mark_LINE = 'line';
const mark_POINT = 'point';
const mark_RECT = 'rect';
const mark_RULE = 'rule';
const mark_TEXT = 'text';
const mark_TICK = 'tick';
const mark_TRAIL = 'trail';
const mark_CIRCLE = 'circle';
const mark_SQUARE = 'square';
const mark_GEOSHAPE = 'geoshape';
// Using mapped type to declare index, ensuring we always have all marks when we add more.
const mark_MARK_INDEX = {
area: 1,
bar: 1,
image: 1,
line: 1,
point: 1,
text: 1,
tick: 1,
trail: 1,
rect: 1,
geoshape: 1,
rule: 1,
circle: 1,
square: 1
};
function mark_isMark(m) {
return !!mark_MARK_INDEX[m];
}
function mark_isPathMark(m) {
return util_contains(['line', 'area', 'trail'], m);
}
function mark_isRectBasedMark(m) {
return util_contains(['rect', 'bar', 'image'], m);
}
const mark_PRIMITIVE_MARKS = util_keys(mark_MARK_INDEX);
function mark_isMarkDef(mark) {
return mark['type'];
}
const mark_PRIMITIVE_MARK_INDEX = toSet(mark_PRIMITIVE_MARKS);
function mark_isPrimitiveMark(mark) {
const markType = mark_isMarkDef(mark) ? mark.type : mark;
return markType in mark_PRIMITIVE_MARK_INDEX;
}
const mark_STROKE_CONFIG = [
'stroke',
'strokeWidth',
'strokeDash',
'strokeDashOffset',
'strokeOpacity',
'strokeJoin',
'strokeMiterLimit'
];
const mark_FILL_CONFIG = ['fill', 'fillOpacity'];
const mark_FILL_STROKE_CONFIG = [...mark_STROKE_CONFIG, ...mark_FILL_CONFIG];
const mark_VL_ONLY_MARK_CONFIG_PROPERTIES = [
'filled',
'color',
'tooltip',
'invalid',
'timeUnitBandPosition',
'timeUnitBand'
];
const mark_VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {
area: ['line', 'point'],
bar: ['binSpacing', 'continuousBandSize', 'discreteBandSize'],
rect: ['binSpacing', 'continuousBandSize', 'discreteBandSize'],
line: ['point'],
tick: ['bandSize', 'thickness']
};
const mark_defaultMarkConfig = {
color: '#4c78a8',
invalid: 'filter',
timeUnitBand: 1
};
const mark_DEFAULT_RECT_BAND_SIZE = 5;
const mark_defaultBarConfig = {
binSpacing: 1,
continuousBandSize: mark_DEFAULT_RECT_BAND_SIZE,
timeUnitBandPosition: 0.5
};
const mark_defaultRectConfig = {
binSpacing: 0,
continuousBandSize: mark_DEFAULT_RECT_BAND_SIZE,
timeUnitBandPosition: 0.5
};
const mark_defaultTickConfig = {
thickness: 1
};
function mark_getMarkType(m) {
return mark_isMarkDef(m) ? m.type : m;
}
//# sourceMappingURL=mark.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/unit.js
function isUnitSpec(spec) {
return !!spec['mark'];
}
//# sourceMappingURL=unit.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compositemark/base.js
class base_CompositeMarkNormalizer {
constructor(name, run) {
this.name = name;
this.run = run;
}
hasMatchingType(spec) {
if (isUnitSpec(spec)) {
return mark_getMarkType(spec.mark) === this.name;
}
return false;
}
}
//# sourceMappingURL=base.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/aggregate.js
const aggregate_AGGREGATE_OP_INDEX = {
argmax: 1,
argmin: 1,
average: 1,
count: 1,
distinct: 1,
max: 1,
mean: 1,
median: 1,
min: 1,
missing: 1,
q1: 1,
q3: 1,
ci0: 1,
ci1: 1,
stderr: 1,
stdev: 1,
stdevp: 1,
sum: 1,
valid: 1,
values: 1,
variance: 1,
variancep: 1
};
const aggregate_MULTIDOMAIN_SORT_OP_INDEX = {
count: 1,
min: 1,
max: 1
};
function aggregate_isArgminDef(a) {
return !!a && !!a['argmin'];
}
function aggregate_isArgmaxDef(a) {
return !!a && !!a['argmax'];
}
const aggregate_AGGREGATE_OPS = util_keys(aggregate_AGGREGATE_OP_INDEX);
function aggregate_isAggregateOp(a) {
return isString(a) && !!aggregate_AGGREGATE_OP_INDEX[a];
}
const aggregate_COUNTING_OPS = ['count', 'valid', 'missing', 'distinct'];
function aggregate_isCountingAggregateOp(aggregate) {
return isString(aggregate) && util_contains(aggregate_COUNTING_OPS, aggregate);
}
function aggregate_isMinMaxOp(aggregate) {
return isString(aggregate) && util_contains(['min', 'max'], aggregate);
}
/** Additive-based aggregation operations. These can be applied to stack. */
const aggregate_SUM_OPS = ['count', 'sum', 'distinct', 'valid', 'missing'];
/**
* Aggregation operators that always produce values within the range [domainMin, domainMax].
*/
const aggregate_SHARED_DOMAIN_OPS = ['mean', 'average', 'median', 'q1', 'q3', 'min', 'max'];
const aggregate_SHARED_DOMAIN_OP_INDEX = toSet(aggregate_SHARED_DOMAIN_OPS);
//# sourceMappingURL=aggregate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/channel.js
/*
* Constants and utilities for encoding channels (Visual variables)
* such as 'x', 'y', 'color'.
*/
// Facet
const channel_ROW = 'row';
const channel_COLUMN = 'column';
const channel_FACET = 'facet';
// Position
const channel_X = 'x';
const channel_Y = 'y';
const channel_X2 = 'x2';
const channel_Y2 = 'y2';
// Geo Position
const channel_LATITUDE = 'latitude';
const channel_LONGITUDE = 'longitude';
const channel_LATITUDE2 = 'latitude2';
const channel_LONGITUDE2 = 'longitude2';
// Mark property with scale
const channel_COLOR = 'color';
const channel_FILL = 'fill';
const channel_STROKE = 'stroke';
const channel_SHAPE = 'shape';
const channel_SIZE = 'size';
const channel_OPACITY = 'opacity';
const channel_FILLOPACITY = 'fillOpacity';
const channel_STROKEOPACITY = 'strokeOpacity';
const channel_STROKEWIDTH = 'strokeWidth';
// Non-scale channel
const channel_TEXT = 'text';
const channel_ORDER = 'order';
const channel_DETAIL = 'detail';
const channel_KEY = 'key';
const channel_TOOLTIP = 'tooltip';
const channel_HREF = 'href';
const channel_URL = 'url';
const channel_POSITION_CHANNEL_INDEX = {
x: 1,
y: 1,
x2: 1,
y2: 1
};
function channel_isPositionChannel(c) {
return c in channel_POSITION_CHANNEL_INDEX;
}
function channel_getPositionChannelFromLatLong(channel) {
switch (channel) {
case channel_LATITUDE:
return 'y';
case channel_LATITUDE2:
return 'y2';
case channel_LONGITUDE:
return 'x';
case channel_LONGITUDE2:
return 'x2';
}
}
const channel_GEOPOSITION_CHANNEL_INDEX = {
longitude: 1,
longitude2: 1,
latitude: 1,
latitude2: 1
};
function channel_isGeoPositionChannel(c) {
return c in channel_GEOPOSITION_CHANNEL_INDEX;
}
const channel_GEOPOSITION_CHANNELS = util_keys(channel_GEOPOSITION_CHANNEL_INDEX);
const channel_UNIT_CHANNEL_INDEX = Object.assign(Object.assign(Object.assign({}, channel_POSITION_CHANNEL_INDEX), channel_GEOPOSITION_CHANNEL_INDEX), {
// color
color: 1, fill: 1, stroke: 1,
// other non-position with scale
opacity: 1, fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, size: 1, shape: 1,
// channels without scales
order: 1, text: 1, detail: 1, key: 1, tooltip: 1, href: 1, url: 1 });
function channel_isColorChannel(channel) {
return channel === 'color' || channel === 'fill' || channel === 'stroke';
}
const channel_FACET_CHANNEL_INDEX = {
row: 1,
column: 1,
facet: 1
};
const channel_FACET_CHANNELS = util_keys(channel_FACET_CHANNEL_INDEX);
const channel_CHANNEL_INDEX = Object.assign(Object.assign({}, channel_UNIT_CHANNEL_INDEX), channel_FACET_CHANNEL_INDEX);
const channel_CHANNELS = util_keys(channel_CHANNEL_INDEX);
const { order: channel_o, detail: channel_d, tooltip: channel_tt1 } = channel_CHANNEL_INDEX, channel_SINGLE_DEF_CHANNEL_INDEX = tslib_es6_rest(channel_CHANNEL_INDEX, ["order", "detail", "tooltip"]);
const { row: channel_r, column: channel_c, facet: channel_f } = channel_SINGLE_DEF_CHANNEL_INDEX, channel_SINGLE_DEF_UNIT_CHANNEL_INDEX = tslib_es6_rest(channel_SINGLE_DEF_CHANNEL_INDEX, ["row", "column", "facet"]);
/**
* Channels that cannot have an array of channelDef.
* model.fieldDef, getFieldDef only work for these channels.
*
* (The only two channels that can have an array of channelDefs are "detail" and "order".
* Since there can be multiple fieldDefs for detail and order, getFieldDef/model.fieldDef
* are not applicable for them. Similarly, selection projection won't work with "detail" and "order".)
*/
const channel_SINGLE_DEF_CHANNELS = util_keys(channel_SINGLE_DEF_CHANNEL_INDEX);
const channel_SINGLE_DEF_UNIT_CHANNELS = util_keys(channel_SINGLE_DEF_UNIT_CHANNEL_INDEX);
function channel_isSingleDefUnitChannel(str) {
return !!channel_SINGLE_DEF_UNIT_CHANNEL_INDEX[str];
}
function channel_isChannel(str) {
return !!channel_CHANNEL_INDEX[str];
}
const channel_SECONDARY_RANGE_CHANNEL = ['x2', 'y2', 'latitude2', 'longitude2'];
function channel_isSecondaryRangeChannel(c) {
const main = channel_getMainRangeChannel(c);
return main !== c;
}
/**
* Get the main channel for a range channel. E.g. `x` for `x2`.
*/
function channel_getMainRangeChannel(channel) {
switch (channel) {
case 'x2':
return 'x';
case 'y2':
return 'y';
case 'latitude2':
return 'latitude';
case 'longitude2':
return 'longitude';
}
return channel;
}
/**
* Get the main channel for a range channel. E.g. `x` for `x2`.
*/
function channel_getSecondaryRangeChannel(channel) {
switch (channel) {
case 'x':
return 'x2';
case 'y':
return 'y2';
case 'latitude':
return 'latitude2';
case 'longitude':
return 'longitude2';
}
return undefined;
}
// CHANNELS without COLUMN, ROW
const channel_UNIT_CHANNELS = util_keys(channel_UNIT_CHANNEL_INDEX);
// NONPOSITION_CHANNELS = UNIT_CHANNELS without X, Y, X2, Y2;
const { x: channel_x, y: channel_y,
// x2 and y2 share the same scale as x and y
x2: channel_x2, y2: channel_y2, latitude: channel_latitude, longitude: channel_longitude, latitude2: channel_latitude2, longitude2: channel_longitude2 } = channel_UNIT_CHANNEL_INDEX,
// The rest of unit channels then have scale
channel_NONPOSITION_CHANNEL_INDEX = tslib_es6_rest(channel_UNIT_CHANNEL_INDEX, ["x", "y", "x2", "y2", "latitude", "longitude", "latitude2", "longitude2"]);
const channel_NONPOSITION_CHANNELS = util_keys(channel_NONPOSITION_CHANNEL_INDEX);
// POSITION_SCALE_CHANNELS = X and Y;
const channel_POSITION_SCALE_CHANNEL_INDEX = { x: 1, y: 1 };
const channel_POSITION_SCALE_CHANNELS = util_keys(channel_POSITION_SCALE_CHANNEL_INDEX);
function channel_getSizeType(channel) {
return channel === 'x' ? 'width' : 'height';
}
function channel_getPositionScaleChannel(sizeType) {
return sizeType === 'width' ? 'x' : 'y';
}
// NON_POSITION_SCALE_CHANNEL = SCALE_CHANNELS without X, Y
const {
// x2 and y2 share the same scale as x and y
// text and tooltip have format instead of scale,
// href has neither format, nor scale
text: channel_t, tooltip: channel_tt, href: channel_hr, url: channel_u,
// detail and order have no scale
detail: channel_dd, key: channel_k, order: channel_oo } = channel_NONPOSITION_CHANNEL_INDEX, channel_NONPOSITION_SCALE_CHANNEL_INDEX = tslib_es6_rest(channel_NONPOSITION_CHANNEL_INDEX, ["text", "tooltip", "href", "url", "detail", "key", "order"]);
const channel_NONPOSITION_SCALE_CHANNELS = util_keys(channel_NONPOSITION_SCALE_CHANNEL_INDEX);
function channel_isNonPositionScaleChannel(channel) {
return !!channel_NONPOSITION_CHANNEL_INDEX[channel];
}
/**
* @returns whether Vega supports legends for a particular channel
*/
function channel_supportLegend(channel) {
switch (channel) {
case channel_COLOR:
case channel_FILL:
case channel_STROKE:
case channel_SIZE:
case channel_SHAPE:
case channel_OPACITY:
case channel_STROKEWIDTH:
return true;
case channel_FILLOPACITY:
case channel_STROKEOPACITY:
return false;
}
}
// Declare SCALE_CHANNEL_INDEX
const channel_SCALE_CHANNEL_INDEX = Object.assign(Object.assign({}, channel_POSITION_SCALE_CHANNEL_INDEX), channel_NONPOSITION_SCALE_CHANNEL_INDEX);
/** List of channels with scales */
const channel_SCALE_CHANNELS = util_keys(channel_SCALE_CHANNEL_INDEX);
function channel_isScaleChannel(channel) {
return !!channel_SCALE_CHANNEL_INDEX[channel];
}
/**
* Return whether a channel supports a particular mark type.
* @param channel channel name
* @param mark the mark type
* @return whether the mark supports the channel
*/
function channel_supportMark(channel, mark) {
return channel_getSupportedMark(channel)[mark];
}
const channel_ALL_MARKS = {
// all marks
area: 'always',
bar: 'always',
circle: 'always',
geoshape: 'always',
image: 'always',
line: 'always',
rule: 'always',
point: 'always',
rect: 'always',
square: 'always',
trail: 'always',
text: 'always',
tick: 'always'
};
const { geoshape: channel_g } = channel_ALL_MARKS, channel_ALL_MARKS_EXCEPT_GEOSHAPE = tslib_es6_rest(channel_ALL_MARKS, ["geoshape"]);
/**
* Return a dictionary showing whether a channel supports mark type.
* @param channel
* @return A dictionary mapping mark types to 'always', 'binned', or undefined
*/
function channel_getSupportedMark(channel) {
switch (channel) {
case channel_COLOR:
case channel_FILL:
case channel_STROKE:
// falls through
case channel_DETAIL:
case channel_KEY:
case channel_TOOLTIP:
case channel_HREF:
case channel_ORDER: // TODO: revise (order might not support rect, which is not stackable?)
case channel_OPACITY:
case channel_FILLOPACITY:
case channel_STROKEOPACITY:
case channel_STROKEWIDTH:
// falls through
case channel_FACET:
case channel_ROW: // falls through
case channel_COLUMN:
return channel_ALL_MARKS;
case channel_X:
case channel_Y:
case channel_LATITUDE:
case channel_LONGITUDE:
// all marks except geoshape. geoshape does not use X, Y -- it uses a projection
return channel_ALL_MARKS_EXCEPT_GEOSHAPE;
case channel_X2:
case channel_Y2:
case channel_LATITUDE2:
case channel_LONGITUDE2:
return {
area: 'always',
bar: 'always',
image: 'always',
rect: 'always',
rule: 'always',
circle: 'binned',
point: 'binned',
square: 'binned',
tick: 'binned',
line: 'binned',
trail: 'binned'
};
case channel_SIZE:
return {
point: 'always',
tick: 'always',
rule: 'always',
circle: 'always',
square: 'always',
bar: 'always',
text: 'always',
line: 'always',
trail: 'always'
};
case channel_SHAPE:
return { point: 'always', geoshape: 'always' };
case channel_TEXT:
return { text: 'always' };
case channel_URL:
return { image: 'always' };
}
}
function channel_rangeType(channel) {
switch (channel) {
case channel_X:
case channel_Y:
case channel_SIZE:
case channel_STROKEWIDTH:
case channel_OPACITY:
case channel_FILLOPACITY:
case channel_STROKEOPACITY:
// X2 and Y2 use X and Y scales, so they similarly have continuous range. [falls through]
case channel_X2:
case channel_Y2:
return undefined;
case channel_FACET:
case channel_ROW:
case channel_COLUMN:
case channel_SHAPE:
// TEXT, TOOLTIP, URL, and HREF have no scale but have discrete output [falls through]
case channel_TEXT:
case channel_TOOLTIP:
case channel_HREF:
case channel_URL:
return 'discrete';
// Color can be either continuous or discrete, depending on scale type.
case channel_COLOR:
case channel_FILL:
case channel_STROKE:
return 'flexible';
// No scale, no range type.
case channel_LATITUDE:
case channel_LONGITUDE:
case channel_LATITUDE2:
case channel_LONGITUDE2:
case channel_DETAIL:
case channel_KEY:
case channel_ORDER:
return undefined;
}
}
//# sourceMappingURL=channel.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/log/message.js
/**
* Collection of all Vega-Lite Error Messages
*/
function message_invalidSpec(spec) {
return `Invalid specification ${JSON.stringify(spec)}. Make sure the specification includes at least one of the following properties: "mark", "layer", "facet", "hconcat", "vconcat", "concat", or "repeat".`;
}
// FIT
const message_FIT_NON_SINGLE = 'Autosize "fit" only works for single views and layered views.';
function message_containerSizeNonSingle(name) {
const uName = name == 'width' ? 'Width' : 'Height';
return `${uName} "container" only works for single views and layered views.`;
}
function message_containerSizeNotCompatibleWithAutosize(name) {
const uName = name == 'width' ? 'Width' : 'Height';
return `${uName} "container" only works well with autosize "fit" or "fit-x".`;
}
function message_droppingFit(channel) {
return channel
? `Dropping "fit-${channel}" because spec has discrete ${channel_getSizeType(channel)}.`
: `Dropping "fit" because spec has discrete size.`;
}
// SELECTION
function message_cannotProjectOnChannelWithoutField(channel) {
return `Cannot project a selection on encoding channel "${channel}", which has no field.`;
}
function message_cannotProjectAggregate(channel, aggregate) {
return `Cannot project a selection on encoding channel "${channel}" as it uses an aggregate function ("${aggregate}").`;
}
function message_nearestNotSupportForContinuous(mark) {
return `The "nearest" transform is not supported for ${mark} marks.`;
}
function message_selectionNotSupported(mark) {
return `Selection not supported for ${mark} yet.`;
}
function message_selectionNotFound(name) {
return `Cannot find a selection named "${name}".`;
}
const message_SCALE_BINDINGS_CONTINUOUS = 'Scale bindings are currently only supported for scales with unbinned, continuous domains.';
const message_LEGEND_BINDINGS_PROJECT_LENGTH = 'Legend bindings are only supported for selections over an individual field or encoding channel.';
function message_noSameUnitLookup(name) {
return (`Cannot define and lookup the "${name}" selection in the same view. ` +
`Try moving the lookup into a second, layered view?`);
}
// REPEAT
function message_noSuchRepeatedValue(field) {
return `Unknown repeated value "${field}".`;
}
function message_columnsNotSupportByRowCol(type) {
return `The "columns" property cannot be used when "${type}" has nested row/column.`;
}
// CONCAT
const message_CONCAT_CANNOT_SHARE_AXIS = 'Axes cannot be shared in concatenated views yet (https://github.com/vega/vega-lite/issues/2415).';
// REPEAT
const message_REPEAT_CANNOT_SHARE_AXIS = 'Axes cannot be shared in repeated views yet (https://github.com/vega/vega-lite/issues/2415).';
// DATA
function message_unrecognizedParse(p) {
return `Unrecognized parse "${p}".`;
}
function message_differentParse(field, local, ancestor) {
return `An ancestor parsed field "${field}" as ${ancestor} but a child wants to parse the field as ${local}.`;
}
// TRANSFORMS
function message_invalidTransformIgnored(transform) {
return `Ignoring an invalid transform: ${util_stringify(transform)}.`;
}
const message_NO_FIELDS_NEEDS_AS = 'If "from.fields" is not specified, "as" has to be a string that specifies the key to be used for the data from the secondary source.';
// ENCODING & FACET
function message_encodingOverridden(channels) {
return `Layer's shared ${channels.join(',')} channel ${channels.length === 1 ? 'is' : 'are'} overriden.`;
}
function message_projectionOverridden(opt) {
const { parentProjection, projection } = opt;
return `Layer's shared projection ${util_stringify(parentProjection)} is overridden by a child projection ${util_stringify(projection)}.`;
}
function message_primitiveChannelDef(channel, type, value) {
return `Channel ${channel} is a ${type}. Converted to {value: ${util_stringify(value)}}.`;
}
function message_invalidFieldType(type) {
return `Invalid field type "${type}".`;
}
function message_nonZeroScaleUsedWithLengthMark(mark, channel, opt) {
const scaleText = opt.scaleType
? `${opt.scaleType} scale`
: opt.zeroFalse
? 'scale with zero=false'
: 'scale with custom domain that excludes zero';
return `A ${scaleText} is used to encode ${mark}'s ${channel}. This can be misleading as the ${channel === 'x' ? 'width' : 'height'} of the ${mark} can be arbitrary based on the scale domain. You may want to use point mark instead.`;
}
function message_invalidFieldTypeForCountAggregate(type, aggregate) {
return `Invalid field type "${type}" for aggregate: "${aggregate}", using "quantitative" instead.`;
}
function message_invalidAggregate(aggregate) {
return `Invalid aggregation operator "${aggregate}".`;
}
function message_missingFieldType(channel, newType) {
return `Missing type for channel "${channel}", using "${newType}" instead.`;
}
function message_droppingColor(type, opt) {
const { fill, stroke } = opt;
return `Dropping color ${type} as the plot also has ${fill && stroke ? 'fill and stroke' : fill ? 'fill' : 'stroke'}.`;
}
function message_emptyFieldDef(fieldDef, channel) {
return `Dropping ${util_stringify(fieldDef)} from channel "${channel}" since it does not contain data field or value.`;
}
function message_latLongDeprecated(channel, type, newChannel) {
return `${channel}-encoding with type ${type} is deprecated. Replacing with ${newChannel}-encoding.`;
}
const message_LINE_WITH_VARYING_SIZE = 'Line marks cannot encode size with a non-groupby field. You may want to use trail marks instead.';
function message_incompatibleChannel(channel, markOrFacet, when) {
return `${channel} dropped as it is incompatible with "${markOrFacet}"${when ? ` when ${when}` : ''}.`;
}
function message_invalidEncodingChannel(channel) {
return `${channel}-encoding is dropped as ${channel} is not a valid encoding channel.`;
}
function message_facetChannelShouldBeDiscrete(channel) {
return `${channel} encoding should be discrete (ordinal / nominal / binned).`;
}
function message_facetChannelDropped(channels) {
return `Facet encoding dropped as ${channels.join(' and ')} ${channels.length > 1 ? 'are' : 'is'} also specified.`;
}
function message_discreteChannelCannotEncode(channel, type) {
return `Using discrete channel "${channel}" to encode "${type}" field can be misleading as it does not encode ${type === 'ordinal' ? 'order' : 'magnitude'}.`;
}
// Mark
function message_lineWithRange(hasX2, hasY2) {
const channels = hasX2 && hasY2 ? 'x2 and y2' : hasX2 ? 'x2' : 'y2';
return `Line mark is for continuous lines and thus cannot be used with ${channels}. We will use the rule mark (line segments) instead.`;
}
function message_orientOverridden(original, actual) {
return `Specified orient "${original}" overridden with "${actual}".`;
}
// SCALE
const message_CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN = 'Custom domain scale cannot be unioned with default field-based domain.';
const message_RANGE_STEP_DEPRECATED = `Scale's "rangeStep" is deprecated and will be removed in Vega-Lite 5.0. Please use "width"/"height": {"step": ...} instead. See https://vega.github.io/vega-lite/docs/size.html.`;
function message_cannotUseScalePropertyWithNonColor(prop) {
return `Cannot use the scale property "${prop}" with non-color channel.`;
}
function message_unaggregateDomainHasNoEffectForRawField(fieldDef) {
return `Using unaggregated domain with raw field has no effect (${util_stringify(fieldDef)}).`;
}
function message_unaggregateDomainWithNonSharedDomainOp(aggregate) {
return `Unaggregated domain not applicable for "${aggregate}" since it produces values outside the origin domain of the source data.`;
}
function message_unaggregatedDomainWithLogScale(fieldDef) {
return `Unaggregated domain is currently unsupported for log scale (${util_stringify(fieldDef)}).`;
}
function message_cannotApplySizeToNonOrientedMark(mark) {
return `Cannot apply size to non-oriented mark "${mark}".`;
}
function message_scaleTypeNotWorkWithChannel(channel, scaleType, defaultScaleType) {
return `Channel "${channel}" does not work with "${scaleType}" scale. We are using "${defaultScaleType}" scale instead.`;
}
function message_scaleTypeNotWorkWithFieldDef(scaleType, defaultScaleType) {
return `FieldDef does not work with "${scaleType}" scale. We are using "${defaultScaleType}" scale instead.`;
}
function message_scalePropertyNotWorkWithScaleType(scaleType, propName, channel) {
return `${channel}-scale's "${propName}" is dropped as it does not work with ${scaleType} scale.`;
}
function message_scaleTypeNotWorkWithMark(mark, scaleType) {
return `Scale type "${scaleType}" does not work with mark "${mark}".`;
}
function message_stepDropped(channel) {
return `The step for "${channel}" is dropped because the ${channel === 'width' ? 'x' : 'y'} is continuous.`;
}
function message_mergeConflictingProperty(property, propertyOf, v1, v2) {
return `Conflicting ${propertyOf.toString()} property "${property.toString()}" (${util_stringify(v1)} and ${util_stringify(v2)}). Using ${util_stringify(v1)}.`;
}
function message_mergeConflictingDomainProperty(property, propertyOf, v1, v2) {
return `Conflicting ${propertyOf.toString()} property "${property.toString()}" (${util_stringify(v1)} and ${util_stringify(v2)}). Using the union of the two domains.`;
}
function message_independentScaleMeansIndependentGuide(channel) {
return `Setting the scale to be independent for "${channel}" means we also have to set the guide (axis or legend) to be independent.`;
}
function message_domainSortDropped(sort) {
return `Dropping sort property ${util_stringify(sort)} as unioned domains only support boolean or op "count", "min", and "max".`;
}
const message_UNABLE_TO_MERGE_DOMAINS = 'Unable to merge domains.';
const message_MORE_THAN_ONE_SORT = 'Domains that should be unioned has conflicting sort properties. Sort will be set to true.';
// AXIS
const message_INVALID_CHANNEL_FOR_AXIS = 'Invalid channel for axis.';
// STACK
function message_cannotStackRangedMark(channel) {
return `Cannot stack "${channel}" if there is already "${channel}2".`;
}
function message_cannotStackNonLinearScale(scaleType) {
return `Cannot stack non-linear scale (${scaleType}).`;
}
function message_stackNonSummativeAggregate(aggregate) {
return `Stacking is applied even though the aggregate function is non-summative ("${aggregate}").`;
}
// TIMEUNIT
function message_invalidTimeUnit(unitName, value) {
return `Invalid ${unitName}: ${util_stringify(value)}.`;
}
function message_dayReplacedWithDate(fullTimeUnit) {
return `Time unit "${fullTimeUnit}" is not supported. We are replacing it with ${util_replaceAll(fullTimeUnit, 'day', 'date')}.`;
}
function message_droppedDay(d) {
return `Dropping day from datetime ${util_stringify(d)} as day cannot be combined with other units.`;
}
function message_errorBarCenterAndExtentAreNotNeeded(center, extent) {
return `${extent ? 'extent ' : ''}${extent && center ? 'and ' : ''}${center ? 'center ' : ''}${extent && center ? 'are ' : 'is '}not needed when data are aggregated.`;
}
function message_errorBarCenterIsUsedWithWrongExtent(center, extent, mark) {
return `${center} is not usually used with ${extent} for ${mark}.`;
}
function message_errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark) {
return `Continuous axis should not have customized aggregation function ${aggregate}; ${compositeMark} already agregates the axis.`;
}
function message_errorBarCenterIsNotNeeded(extent, mark) {
return `Center is not needed to be specified in ${mark} when extent is ${extent}.`;
}
function message_errorBand1DNotSupport(property) {
return `1D error band does not support ${property}.`;
}
// CHANNEL
function message_channelRequiredForBinned(channel) {
return `Channel ${channel} is required for "binned" bin.`;
}
function message_domainRequiredForThresholdScale(channel) {
return `Domain for ${channel} is required for threshold scale.`;
}
//# sourceMappingURL=message.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/log/index.js
/**
* Vega-Lite's singleton logger utility.
*/
const log_message = message_namespaceObject;
/**
* Main (default) Vega Logger instance for Vega-Lite.
*/
const log_main = logger(Warn);
let log_current = log_main;
/**
* Logger tool for checking if the code throws correct warning.
*/
class log_LocalLogger {
constructor() {
this.warns = [];
this.infos = [];
this.debugs = [];
}
level() {
return this;
}
warn(...args) {
this.warns.push(...args);
return this;
}
info(...args) {
this.infos.push(...args);
return this;
}
debug(...args) {
this.debugs.push(...args);
return this;
}
error(...args) {
throw Error(...args);
}
}
function log_wrap(f) {
return () => {
log_current = new log_LocalLogger();
f(log_current);
log_reset();
};
}
/**
* Set the singleton logger to be a custom logger.
*/
function log_set(newLogger) {
log_current = newLogger;
return log_current;
}
/**
* Reset the main logger to use the default Vega Logger.
*/
function log_reset() {
log_current = log_main;
return log_current;
}
function src_log_warn(...args) {
log_current.warn(...args);
}
function src_log_info(...args) {
log_current.info(...args);
}
function src_log_debug(...args) {
log_current.debug(...args);
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/datetime.js
// DateTime definition object
/*
* A designated year that starts on Sunday.
*/
const datetime_SUNDAY_YEAR = 2006;
function datetime_isDateTime(o) {
return (!!o &&
(!!o.year ||
!!o.quarter ||
!!o.month ||
!!o.date ||
!!o.day ||
!!o.hours ||
!!o.minutes ||
!!o.seconds ||
!!o.milliseconds));
}
const datetime_MONTHS = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december'
];
const datetime_SHORT_MONTHS = datetime_MONTHS.map(m => m.substr(0, 3));
const datetime_DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
const datetime_SHORT_DAYS = datetime_DAYS.map(d => d.substr(0, 3));
function datetime_normalizeQuarter(q) {
if (src_isNumber(q)) {
if (q > 4) {
src_log_warn(log_message.invalidTimeUnit('quarter', q));
}
// We accept 1-based quarter, so need to readjust to 0-based quarter
return (q - 1).toString();
}
else {
// Invalid quarter
throw new Error(log_message.invalidTimeUnit('quarter', q));
}
}
function datetime_normalizeMonth(m) {
if (src_isNumber(m)) {
// We accept 1-based month, so need to readjust to 0-based month
return (m - 1).toString();
}
else {
const lowerM = m.toLowerCase();
const monthIndex = datetime_MONTHS.indexOf(lowerM);
if (monthIndex !== -1) {
return monthIndex + ''; // 0 for january, ...
}
const shortM = lowerM.substr(0, 3);
const shortMonthIndex = datetime_SHORT_MONTHS.indexOf(shortM);
if (shortMonthIndex !== -1) {
return shortMonthIndex + '';
}
// Invalid month
throw new Error(log_message.invalidTimeUnit('month', m));
}
}
function datetime_normalizeDay(d) {
if (src_isNumber(d)) {
// mod so that this can be both 0-based where 0 = sunday
// and 1-based where 7=sunday
return (d % 7) + '';
}
else {
const lowerD = d.toLowerCase();
const dayIndex = datetime_DAYS.indexOf(lowerD);
if (dayIndex !== -1) {
return dayIndex + ''; // 0 for january, ...
}
const shortD = lowerD.substr(0, 3);
const shortDayIndex = datetime_SHORT_DAYS.indexOf(shortD);
if (shortDayIndex !== -1) {
return shortDayIndex + '';
}
// Invalid day
throw new Error(log_message.invalidTimeUnit('day', d));
}
}
/**
* Return Vega Expression for a particular date time.
* @param d
* @param normalize whether to normalize quarter, month, day.
* @param toJSON whether to return the date in JSON format
*/
function datetime_dateTimeExpr(d, normalize = false, toJSON = false) {
const units = [];
if (normalize && d.day !== undefined) {
if (util_keys(d).length > 1) {
src_log_warn(log_message.droppedDay(d));
d = util_duplicate(d);
delete d.day;
}
}
if (d.year !== undefined) {
units.push(d.year);
}
else if (d.day !== undefined) {
// Set year to 2006 for working with day since January 1 2006 is a Sunday
units.push(datetime_SUNDAY_YEAR);
}
else {
units.push(0);
}
if (d.month !== undefined) {
const month = normalize ? datetime_normalizeMonth(d.month) : d.month;
units.push(month);
}
else if (d.quarter !== undefined) {
const quarter = normalize ? datetime_normalizeQuarter(d.quarter) : d.quarter;
units.push(quarter + '*3');
}
else {
units.push(0); // months start at zero in JS
}
if (d.date !== undefined) {
units.push(d.date);
}
else if (d.day !== undefined) {
// HACK: Day only works as a standalone unit
// This is only correct because we always set year to 2006 for day
const day = normalize ? datetime_normalizeDay(d.day) : d.day;
units.push(day + '+1');
}
else {
units.push(1); // Date starts at 1 in JS
}
// Note: can't use TimeUnit enum here as importing it will create
// circular dependency problem!
for (const timeUnit of ['hours', 'minutes', 'seconds', 'milliseconds']) {
const unit = d[timeUnit];
units.push(typeof unit === 'undefined' ? 0 : unit);
}
const unitsString = units.join(', ');
if (toJSON) {
if (d.utc) {
return new Function(`return +new Date(Date.UTC(${unitsString}))`)();
}
else {
return new Function(`return +new Date(${unitsString})`)();
}
}
if (d.utc) {
return `utc(${unitsString})`;
}
else {
return `datetime(${unitsString})`;
}
}
//# sourceMappingURL=datetime.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/timeunit.js
var timeunit_TimeUnit;
(function (TimeUnit) {
TimeUnit.YEAR = 'year';
TimeUnit.MONTH = 'month';
TimeUnit.DAY = 'day';
TimeUnit.DATE = 'date';
TimeUnit.HOURS = 'hours';
TimeUnit.MINUTES = 'minutes';
TimeUnit.SECONDS = 'seconds';
TimeUnit.MILLISECONDS = 'milliseconds';
TimeUnit.YEARMONTH = 'yearmonth';
TimeUnit.YEARMONTHDATE = 'yearmonthdate';
TimeUnit.YEARMONTHDATEHOURS = 'yearmonthdatehours';
TimeUnit.YEARMONTHDATEHOURSMINUTES = 'yearmonthdatehoursminutes';
TimeUnit.YEARMONTHDATEHOURSMINUTESSECONDS = 'yearmonthdatehoursminutesseconds';
// MONTHDATE and MONTHDATEHOURS always include 29 February since we use year 0th (which is a leap year);
TimeUnit.MONTHDATE = 'monthdate';
TimeUnit.MONTHDATEHOURS = 'monthdatehours';
TimeUnit.HOURSMINUTES = 'hoursminutes';
TimeUnit.HOURSMINUTESSECONDS = 'hoursminutesseconds';
TimeUnit.MINUTESSECONDS = 'minutesseconds';
TimeUnit.SECONDSMILLISECONDS = 'secondsmilliseconds';
TimeUnit.QUARTER = 'quarter';
TimeUnit.YEARQUARTER = 'yearquarter';
TimeUnit.QUARTERMONTH = 'quartermonth';
TimeUnit.YEARQUARTERMONTH = 'yearquartermonth';
TimeUnit.UTCYEAR = 'utcyear';
TimeUnit.UTCMONTH = 'utcmonth';
TimeUnit.UTCDAY = 'utcday';
TimeUnit.UTCDATE = 'utcdate';
TimeUnit.UTCHOURS = 'utchours';
TimeUnit.UTCMINUTES = 'utcminutes';
TimeUnit.UTCSECONDS = 'utcseconds';
TimeUnit.UTCMILLISECONDS = 'utcmilliseconds';
TimeUnit.UTCYEARMONTH = 'utcyearmonth';
TimeUnit.UTCYEARMONTHDATE = 'utcyearmonthdate';
TimeUnit.UTCYEARMONTHDATEHOURS = 'utcyearmonthdatehours';
TimeUnit.UTCYEARMONTHDATEHOURSMINUTES = 'utcyearmonthdatehoursminutes';
TimeUnit.UTCYEARMONTHDATEHOURSMINUTESSECONDS = 'utcyearmonthdatehoursminutesseconds';
// UTCMONTHDATE and UTCMONTHDATEHOURS always include 29 February since we use year 0th (which is a leap year);
TimeUnit.UTCMONTHDATE = 'utcmonthdate';
TimeUnit.UTCMONTHDATEHOURS = 'utcmonthdatehours';
TimeUnit.UTCHOURSMINUTES = 'utchoursminutes';
TimeUnit.UTCHOURSMINUTESSECONDS = 'utchoursminutesseconds';
TimeUnit.UTCMINUTESSECONDS = 'utcminutesseconds';
TimeUnit.UTCSECONDSMILLISECONDS = 'utcsecondsmilliseconds';
TimeUnit.UTCQUARTER = 'utcquarter';
TimeUnit.UTCYEARQUARTER = 'utcyearquarter';
TimeUnit.UTCQUARTERMONTH = 'utcquartermonth';
TimeUnit.UTCYEARQUARTERMONTH = 'utcyearquartermonth';
})(timeunit_TimeUnit || (timeunit_TimeUnit = {}));
/** Time Unit that only corresponds to only one part of Date objects. */
const timeunit_LOCAL_SINGLE_TIMEUNIT_INDEX = {
year: 1,
quarter: 1,
month: 1,
day: 1,
date: 1,
hours: 1,
minutes: 1,
seconds: 1,
milliseconds: 1
};
const timeunit_TIMEUNIT_PARTS = util_keys(timeunit_LOCAL_SINGLE_TIMEUNIT_INDEX);
function timeunit_isLocalSingleTimeUnit(timeUnit) {
return !!timeunit_LOCAL_SINGLE_TIMEUNIT_INDEX[timeUnit];
}
const timeunit_UTC_SINGLE_TIMEUNIT_INDEX = {
utcyear: 1,
utcquarter: 1,
utcmonth: 1,
utcday: 1,
utcdate: 1,
utchours: 1,
utcminutes: 1,
utcseconds: 1,
utcmilliseconds: 1
};
function timeunit_isUtcSingleTimeUnit(timeUnit) {
return !!timeunit_UTC_SINGLE_TIMEUNIT_INDEX[timeUnit];
}
const timeunit_LOCAL_MULTI_TIMEUNIT_INDEX = {
yearquarter: 1,
yearquartermonth: 1,
yearmonth: 1,
yearmonthdate: 1,
yearmonthdatehours: 1,
yearmonthdatehoursminutes: 1,
yearmonthdatehoursminutesseconds: 1,
quartermonth: 1,
monthdate: 1,
monthdatehours: 1,
hoursminutes: 1,
hoursminutesseconds: 1,
minutesseconds: 1,
secondsmilliseconds: 1
};
const timeunit_UTC_MULTI_TIMEUNIT_INDEX = {
utcyearquarter: 1,
utcyearquartermonth: 1,
utcyearmonth: 1,
utcyearmonthdate: 1,
utcyearmonthdatehours: 1,
utcyearmonthdatehoursminutes: 1,
utcyearmonthdatehoursminutesseconds: 1,
utcquartermonth: 1,
utcmonthdate: 1,
utcmonthdatehours: 1,
utchoursminutes: 1,
utchoursminutesseconds: 1,
utcminutesseconds: 1,
utcsecondsmilliseconds: 1
};
const timeunit_UTC_TIMEUNIT_INDEX = Object.assign(Object.assign({}, timeunit_UTC_SINGLE_TIMEUNIT_INDEX), timeunit_UTC_MULTI_TIMEUNIT_INDEX);
function timeunit_isUTCTimeUnit(t) {
return !!timeunit_UTC_TIMEUNIT_INDEX[t];
}
function timeunit_getLocalTimeUnit(t) {
return t.substr(3);
}
const timeunit_TIMEUNIT_INDEX = Object.assign(Object.assign(Object.assign(Object.assign({}, timeunit_LOCAL_SINGLE_TIMEUNIT_INDEX), timeunit_UTC_SINGLE_TIMEUNIT_INDEX), timeunit_LOCAL_MULTI_TIMEUNIT_INDEX), timeunit_UTC_MULTI_TIMEUNIT_INDEX);
const timeunit_TIMEUNITS = util_keys(timeunit_TIMEUNIT_INDEX);
// In order of increasing specificity
const timeunit_VEGALITE_TIMEFORMAT = {
'year-month': '%b %Y ',
'year-month-date': '%b %d, %Y '
};
function timeunit_isTimeUnit(t) {
return !!timeunit_TIMEUNIT_INDEX[t];
}
function timeunit_getTimeUnitParts(timeUnit) {
return timeunit_TIMEUNIT_PARTS.reduce((parts, part) => {
if (timeunit_containsTimeUnit(timeUnit, part)) {
return [...parts, part];
}
return parts;
}, []);
}
/** Returns true if fullTimeUnit contains the timeUnit, false otherwise. */
function timeunit_containsTimeUnit(fullTimeUnit, timeUnit) {
const index = fullTimeUnit.indexOf(timeUnit);
return (index > -1 && (timeUnit !== timeunit_TimeUnit.SECONDS || index === 0 || fullTimeUnit.charAt(index - 1) !== 'i') // exclude milliseconds
);
}
/**
* Returns Vega expresssion for a given timeUnit and fieldRef
*/
function timeunit_fieldExpr(fullTimeUnit, field, { end } = { end: false }) {
const fieldRef = util_accessPathWithDatum(field);
const utc = timeunit_isUTCTimeUnit(fullTimeUnit) ? 'utc' : '';
function func(timeUnit) {
if (timeUnit === timeunit_TimeUnit.QUARTER) {
// quarter starting at 0 (0,3,6,9).
return `(${utc}quarter(${fieldRef})-1)`;
}
else {
return `${utc}${timeUnit}(${fieldRef})`;
}
}
let lastTimeUnit;
const d = timeunit_TIMEUNIT_PARTS.reduce((dateExpr, tu) => {
if (timeunit_containsTimeUnit(fullTimeUnit, tu)) {
dateExpr[tu] = func(tu);
lastTimeUnit = tu;
}
return dateExpr;
}, {});
if (end) {
d[lastTimeUnit] += '+1';
}
return datetime_dateTimeExpr(d);
}
function timeunit_getTimeUnitSpecifierExpression(timeUnit) {
if (!timeUnit) {
return undefined;
}
const timeUnitParts = timeunit_getTimeUnitParts(timeUnit);
return `timeUnitSpecifier(${fast_json_stable_stringify_default()(timeUnitParts)}, ${fast_json_stable_stringify_default()(timeunit_VEGALITE_TIMEFORMAT)})`;
}
/**
* returns the signal expression used for axis labels for a time unit
*/
function timeunit_formatExpression(timeUnit, field, isUTCScale) {
if (!timeUnit) {
return undefined;
}
const timeUnitSpecifierExpr = timeunit_getTimeUnitSpecifierExpression(timeUnit);
// We only use utcFormat for utc scale
// For utc time units, the data is already converted as a part of timeUnit transform.
// Thus, utc time units should use timeFormat to avoid shifting the time twice.
if (isUTCScale) {
return `utcFormat(${field}, ${timeUnitSpecifierExpr})`;
}
else {
return `timeFormat(${field}, ${timeUnitSpecifierExpr})`;
}
}
function timeunit_normalizeTimeUnit(timeUnit) {
if (timeUnit !== 'day' && timeUnit.indexOf('day') >= 0) {
src_log_warn(log_message.dayReplacedWithDate(timeUnit));
return util_replaceAll(timeUnit, 'day', 'date');
}
return timeUnit;
}
//# sourceMappingURL=timeunit.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/predicate.js
function predicate_isSelectionPredicate(predicate) {
var _a;
return (_a = predicate) === null || _a === void 0 ? void 0 : _a['selection'];
}
function predicate_isFieldEqualPredicate(predicate) {
return predicate && !!predicate.field && predicate.equal !== undefined;
}
function predicate_isFieldLTPredicate(predicate) {
return predicate && !!predicate.field && predicate.lt !== undefined;
}
function predicate_isFieldLTEPredicate(predicate) {
return predicate && !!predicate.field && predicate.lte !== undefined;
}
function predicate_isFieldGTPredicate(predicate) {
return predicate && !!predicate.field && predicate.gt !== undefined;
}
function predicate_isFieldGTEPredicate(predicate) {
return predicate && !!predicate.field && predicate.gte !== undefined;
}
function predicate_isFieldRangePredicate(predicate) {
if (predicate && predicate.field) {
if (isArray(predicate.range) && predicate.range.length === 2) {
return true;
}
}
return false;
}
function predicate_isFieldOneOfPredicate(predicate) {
return (predicate && !!predicate.field && (isArray(predicate.oneOf) || isArray(predicate.in)) // backward compatibility
);
}
function predicate_isFieldValidPredicate(predicate) {
return predicate && !!predicate.field && predicate.valid !== undefined;
}
function predicate_isFieldPredicate(predicate) {
return (predicate_isFieldOneOfPredicate(predicate) ||
predicate_isFieldEqualPredicate(predicate) ||
predicate_isFieldRangePredicate(predicate) ||
predicate_isFieldLTPredicate(predicate) ||
predicate_isFieldGTPredicate(predicate) ||
predicate_isFieldLTEPredicate(predicate) ||
predicate_isFieldGTEPredicate(predicate));
}
function predicate_predicateValueExpr(v, timeUnit) {
return channeldef_valueExpr(v, { timeUnit, time: true });
}
function predicate_predicateValuesExpr(vals, timeUnit) {
return vals.map(v => predicate_predicateValueExpr(v, timeUnit));
}
// This method is used by Voyager. Do not change its behavior without changing Voyager.
function predicate_fieldFilterExpression(predicate, useInRange = true) {
const { field, timeUnit } = predicate;
const fieldExpr = timeUnit
? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.
// TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline
// TODO: support utc
'time(' + timeunit_fieldExpr(timeUnit, field) + ')'
: channeldef_vgField(predicate, { expr: 'datum' });
if (predicate_isFieldEqualPredicate(predicate)) {
return fieldExpr + '===' + predicate_predicateValueExpr(predicate.equal, timeUnit);
}
else if (predicate_isFieldLTPredicate(predicate)) {
const upper = predicate.lt;
return `${fieldExpr}<${predicate_predicateValueExpr(upper, timeUnit)}`;
}
else if (predicate_isFieldGTPredicate(predicate)) {
const lower = predicate.gt;
return `${fieldExpr}>${predicate_predicateValueExpr(lower, timeUnit)}`;
}
else if (predicate_isFieldLTEPredicate(predicate)) {
const upper = predicate.lte;
return `${fieldExpr}<=${predicate_predicateValueExpr(upper, timeUnit)}`;
}
else if (predicate_isFieldGTEPredicate(predicate)) {
const lower = predicate.gte;
return `${fieldExpr}>=${predicate_predicateValueExpr(lower, timeUnit)}`;
}
else if (predicate_isFieldOneOfPredicate(predicate)) {
return `indexof([${predicate_predicateValuesExpr(predicate.oneOf, timeUnit).join(',')}], ${fieldExpr}) !== -1`;
}
else if (predicate_isFieldValidPredicate(predicate)) {
return predicate_fieldValidPredicate(fieldExpr, predicate.valid);
}
else if (predicate_isFieldRangePredicate(predicate)) {
const lower = predicate.range[0];
const upper = predicate.range[1];
if (lower !== null && upper !== null && useInRange) {
return ('inrange(' +
fieldExpr +
', [' +
predicate_predicateValueExpr(lower, timeUnit) +
', ' +
predicate_predicateValueExpr(upper, timeUnit) +
'])');
}
const exprs = [];
if (lower !== null) {
exprs.push(`${fieldExpr} >= ${predicate_predicateValueExpr(lower, timeUnit)}`);
}
if (upper !== null) {
exprs.push(`${fieldExpr} <= ${predicate_predicateValueExpr(upper, timeUnit)}`);
}
return exprs.length > 0 ? exprs.join(' && ') : 'true';
}
/* istanbul ignore next: it should never reach here */
throw new Error(`Invalid field predicate: ${JSON.stringify(predicate)}`);
}
function predicate_fieldValidPredicate(fieldExpr, valid = true) {
if (valid) {
return `isValid(${fieldExpr}) && isFinite(+${fieldExpr})`;
}
else {
return `!isValid(${fieldExpr}) || !isFinite(+${fieldExpr})`;
}
}
function predicate_normalizePredicate(f) {
if (predicate_isFieldPredicate(f) && f.timeUnit) {
return Object.assign(Object.assign({}, f), { timeUnit: timeunit_normalizeTimeUnit(f.timeUnit) });
}
return f;
}
//# sourceMappingURL=predicate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/type.js
/** Constants and utilities for data type */
/** Data type based on level of measurement */
const TYPE_INDEX = {
quantitative: 1,
ordinal: 1,
temporal: 1,
nominal: 1,
geojson: 1
};
function isType(t) {
return !!TYPE_INDEX[t];
}
const QUANTITATIVE = 'quantitative';
const ORDINAL = 'ordinal';
const TEMPORAL = 'temporal';
const NOMINAL = 'nominal';
const GEOJSON = 'geojson';
/**
* Get full, lowercase type name for a given type.
* @param type
* @return Full type name.
*/
function getFullName(type) {
if (type) {
type = type.toLowerCase();
switch (type) {
case 'q':
case QUANTITATIVE:
return 'quantitative';
case 't':
case TEMPORAL:
return 'temporal';
case 'o':
case ORDINAL:
return 'ordinal';
case 'n':
case NOMINAL:
return 'nominal';
case GEOJSON:
return 'geojson';
}
}
// If we get invalid input, return undefined type.
return undefined;
}
//# sourceMappingURL=type.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/scale.js
var scale_ScaleType;
(function (ScaleType) {
// Continuous - Quantitative
ScaleType.LINEAR = 'linear';
ScaleType.LOG = 'log';
ScaleType.POW = 'pow';
ScaleType.SQRT = 'sqrt';
ScaleType.SYMLOG = 'symlog';
// Continuous - Time
ScaleType.TIME = 'time';
ScaleType.UTC = 'utc';
// Discretizing scales
ScaleType.QUANTILE = 'quantile';
ScaleType.QUANTIZE = 'quantize';
ScaleType.THRESHOLD = 'threshold';
ScaleType.BIN_ORDINAL = 'bin-ordinal';
// Discrete scales
ScaleType.ORDINAL = 'ordinal';
ScaleType.POINT = 'point';
ScaleType.BAND = 'band';
})(scale_ScaleType || (scale_ScaleType = {}));
/**
* Index for scale categories -- only scale of the same categories can be merged together.
* Current implementation is trying to be conservative and avoid merging scale type that might not work together
*/
const scale_SCALE_CATEGORY_INDEX = {
linear: 'numeric',
log: 'numeric',
pow: 'numeric',
sqrt: 'numeric',
symlog: 'numeric',
time: 'time',
utc: 'time',
ordinal: 'ordinal',
'bin-ordinal': 'bin-ordinal',
point: 'ordinal-position',
band: 'ordinal-position',
quantile: 'discretizing',
quantize: 'discretizing',
threshold: 'discretizing'
};
const scale_SCALE_TYPES = util_keys(scale_SCALE_CATEGORY_INDEX);
/**
* Whether the two given scale types can be merged together.
*/
function scale_scaleCompatible(scaleType1, scaleType2) {
const scaleCategory1 = scale_SCALE_CATEGORY_INDEX[scaleType1];
const scaleCategory2 = scale_SCALE_CATEGORY_INDEX[scaleType2];
return (scaleCategory1 === scaleCategory2 ||
(scaleCategory1 === 'ordinal-position' && scaleCategory2 === 'time') ||
(scaleCategory2 === 'ordinal-position' && scaleCategory1 === 'time'));
}
/**
* Index for scale precedence -- high score = higher priority for merging.
*/
const scale_SCALE_PRECEDENCE_INDEX = {
// numeric
linear: 0,
log: 1,
pow: 1,
sqrt: 1,
symlog: 1,
// time
time: 0,
utc: 0,
// ordinal-position -- these have higher precedence than continuous scales as they support more types of data
point: 10,
band: 11,
// non grouped types
ordinal: 0,
'bin-ordinal': 0,
quantile: 0,
quantize: 0,
threshold: 0
};
/**
* Return scale categories -- only scale of the same categories can be merged together.
*/
function scale_scaleTypePrecedence(scaleType) {
return scale_SCALE_PRECEDENCE_INDEX[scaleType];
}
const scale_CONTINUOUS_TO_CONTINUOUS_SCALES = ['linear', 'log', 'pow', 'sqrt', 'symlog', 'time', 'utc'];
const scale_CONTINUOUS_TO_CONTINUOUS_INDEX = toSet(scale_CONTINUOUS_TO_CONTINUOUS_SCALES);
const scale_QUANTITATIVE_SCALES = ['linear', 'log', 'pow', 'sqrt', 'symlog'];
const scale_CONTINUOUS_TO_DISCRETE_SCALES = ['quantile', 'quantize', 'threshold'];
const scale_CONTINUOUS_TO_DISCRETE_INDEX = toSet(scale_CONTINUOUS_TO_DISCRETE_SCALES);
const scale_CONTINUOUS_DOMAIN_SCALES = scale_CONTINUOUS_TO_CONTINUOUS_SCALES.concat([
'quantile',
'quantize',
'threshold'
]);
const scale_CONTINUOUS_DOMAIN_INDEX = toSet(scale_CONTINUOUS_DOMAIN_SCALES);
const scale_DISCRETE_DOMAIN_SCALES = ['ordinal', 'bin-ordinal', 'point', 'band'];
const scale_DISCRETE_DOMAIN_INDEX = toSet(scale_DISCRETE_DOMAIN_SCALES);
const scale_TIME_SCALE_TYPES = ['time', 'utc'];
function scale_hasDiscreteDomain(type) {
return type in scale_DISCRETE_DOMAIN_INDEX;
}
function scale_hasContinuousDomain(type) {
return type in scale_CONTINUOUS_DOMAIN_INDEX;
}
function scale_isContinuousToContinuous(type) {
return type in scale_CONTINUOUS_TO_CONTINUOUS_INDEX;
}
function scale_isContinuousToDiscrete(type) {
return type in scale_CONTINUOUS_TO_DISCRETE_INDEX;
}
const scale_defaultScaleConfig = {
pointPadding: 0.5,
barBandPaddingInner: 0.1,
rectBandPaddingInner: 0,
minBandSize: 2,
minFontSize: 8,
maxFontSize: 40,
minOpacity: 0.3,
maxOpacity: 0.8,
// FIXME: revise if these *can* become ratios of width/height step
minSize: 9,
minStrokeWidth: 1,
maxStrokeWidth: 4,
quantileCount: 4,
quantizeCount: 4
};
function scale_isExtendedScheme(scheme) {
return !isString(scheme) && !!scheme['name'];
}
function scale_isSelectionDomain(domain) {
var _a;
return (_a = domain) === null || _a === void 0 ? void 0 : _a['selection'];
}
const scale_SCALE_PROPERTY_INDEX = {
type: 1,
domain: 1,
align: 1,
range: 1,
scheme: 1,
bins: 1,
// Other properties
reverse: 1,
round: 1,
// quantitative / time
clamp: 1,
nice: 1,
// quantitative
base: 1,
exponent: 1,
constant: 1,
interpolate: 1,
zero: 1,
// band/point
padding: 1,
paddingInner: 1,
paddingOuter: 1
};
const scale_SCALE_PROPERTIES = util_keys(scale_SCALE_PROPERTY_INDEX);
const { type: scale_type, domain: src_scale_domain, range: src_scale_range, scheme: scale_scheme } = scale_SCALE_PROPERTY_INDEX, scale_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX = tslib_es6_rest(scale_SCALE_PROPERTY_INDEX, ["type", "domain", "range", "scheme"]);
const scale_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES = util_keys(scale_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX);
const scale_SCALE_TYPE_INDEX = scale_generateScaleTypeIndex();
function scale_scaleTypeSupportProperty(scaleType, propName) {
switch (propName) {
case 'type':
case 'domain':
case 'reverse':
case 'range':
return true;
case 'scheme':
case 'interpolate':
return !util_contains(['point', 'band', 'identity'], scaleType);
case 'bins':
return !util_contains(['point', 'band', 'identity', 'ordinal'], scaleType);
case 'round':
return scale_isContinuousToContinuous(scaleType) || scaleType === 'band' || scaleType === 'point';
case 'padding':
return scale_isContinuousToContinuous(scaleType) || util_contains(['point', 'band'], scaleType);
case 'paddingOuter':
case 'align':
return util_contains(['point', 'band'], scaleType);
case 'paddingInner':
return scaleType === 'band';
case 'clamp':
return scale_isContinuousToContinuous(scaleType);
case 'nice':
return scale_isContinuousToContinuous(scaleType) || scaleType === 'quantize' || scaleType === 'threshold';
case 'exponent':
return scaleType === 'pow';
case 'base':
return scaleType === 'log';
case 'constant':
return scaleType === 'symlog';
case 'zero':
return (scale_hasContinuousDomain(scaleType) &&
!util_contains([
'log',
'time',
'utc',
'threshold',
'quantile' // quantile depends on distribution so zero does not matter
], scaleType));
}
}
/**
* Returns undefined if the input channel supports the input scale property name
*/
function scale_channelScalePropertyIncompatability(channel, propName) {
switch (propName) {
case 'interpolate':
case 'scheme':
if (!channel_isColorChannel(channel)) {
return log_message.cannotUseScalePropertyWithNonColor(channel);
}
return undefined;
case 'align':
case 'type':
case 'bins':
case 'domain':
case 'range':
case 'base':
case 'exponent':
case 'constant':
case 'nice':
case 'padding':
case 'paddingInner':
case 'paddingOuter':
case 'reverse':
case 'round':
case 'clamp':
case 'zero':
return undefined; // GOOD!
}
}
function scale_scaleTypeSupportDataType(specifiedType, fieldDefType) {
if (util_contains([ORDINAL, NOMINAL], fieldDefType)) {
return specifiedType === undefined || scale_hasDiscreteDomain(specifiedType);
}
else if (fieldDefType === TEMPORAL) {
return util_contains([scale_ScaleType.TIME, scale_ScaleType.UTC, undefined], specifiedType);
}
else if (fieldDefType === QUANTITATIVE) {
return util_contains([
scale_ScaleType.LOG,
scale_ScaleType.POW,
scale_ScaleType.SQRT,
scale_ScaleType.SYMLOG,
scale_ScaleType.QUANTILE,
scale_ScaleType.QUANTIZE,
scale_ScaleType.THRESHOLD,
scale_ScaleType.LINEAR,
undefined
], specifiedType);
}
return true;
}
function scale_channelSupportScaleType(channel, scaleType) {
switch (channel) {
case channel_X:
case channel_Y:
return scale_isContinuousToContinuous(scaleType) || util_contains(['band', 'point'], scaleType);
case channel_SIZE: // TODO: size and opacity can support ordinal with more modification
case channel_STROKEWIDTH:
case channel_OPACITY:
case channel_FILLOPACITY:
case channel_STROKEOPACITY:
// Although it generally doesn't make sense to use band with size and opacity,
// it can also work since we use band: 0.5 to get midpoint.
return (scale_isContinuousToContinuous(scaleType) ||
scale_isContinuousToDiscrete(scaleType) ||
util_contains(['band', 'point'], scaleType));
case channel_COLOR:
case channel_FILL:
case channel_STROKE:
return scaleType !== 'band'; // band does not make sense with color
case channel_SHAPE:
return scaleType === 'ordinal'; // shape = lookup only
}
/* istanbul ignore next: it should never reach here */
return false;
}
function scale_getSupportedScaleType(channel, fieldDefType) {
return scale_SCALE_TYPE_INDEX[scale_generateScaleTypeIndexKey(channel, fieldDefType)];
}
// generates ScaleTypeIndex where keys are encoding channels and values are list of valid ScaleTypes
function scale_generateScaleTypeIndex() {
var _a;
const index = {};
for (const channel of channel_CHANNELS) {
for (const fieldDefType of util_keys(TYPE_INDEX)) {
for (const scaleType of scale_SCALE_TYPES) {
const key = scale_generateScaleTypeIndexKey(channel, fieldDefType);
if (scale_channelSupportScaleType(channel, scaleType) && scale_scaleTypeSupportDataType(scaleType, fieldDefType)) {
index[key] = (_a = index[key], (_a !== null && _a !== void 0 ? _a : []));
index[key].push(scaleType);
}
}
}
}
return index;
}
function scale_generateScaleTypeIndexKey(channel, fieldDefType) {
return channel + '_' + fieldDefType;
}
//# sourceMappingURL=scale.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/title.js
function title_extractTitleConfig(titleConfig) {
const {
// These are non-mark title config that need to be hardcoded
anchor, frame, offset, orient,
// color needs to be redirect to fill
color } = titleConfig,
// The rest are mark config.
titleMarkConfig = tslib_es6_rest(titleConfig, ["anchor", "frame", "offset", "orient", "color"]);
const mark = Object.assign(Object.assign({}, titleMarkConfig), (color ? { fill: color } : {}));
const nonMark = Object.assign(Object.assign(Object.assign(Object.assign({}, (anchor ? { anchor } : {})), (frame ? { frame } : {})), (offset ? { offset } : {})), (orient ? { orient } : {}));
return { mark, nonMark };
}
function title_isText(v) {
return isString(v) || (isArray(v) && isString(v[0]));
}
//# sourceMappingURL=title.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/common.js
const common_BIN_RANGE_DELIMITER = ' \u2013 ';
function common_applyMarkConfig(e, model, propsList) {
for (const property of propsList) {
const value = common_getMarkConfig(property, model.markDef, model.config);
if (value !== undefined) {
e[property] = { value: value };
}
}
return e;
}
function common_getStyles(mark) {
var _a;
return [].concat(mark.type, (_a = mark.style, (_a !== null && _a !== void 0 ? _a : [])));
}
function common_getMarkPropOrConfig(channel, mark, config) {
return util_getFirstDefined(mark[channel], common_getMarkConfig(channel, mark, config));
}
/**
* Return property value from style or mark specific config property if exists.
* Otherwise, return general mark specific config.
*/
function common_getMarkConfig(channel, mark, config, { vgChannel } = {} // Note: Ham: I use `any` here as it's too hard to make TS knows that MarkConfig[vgChannel] would have the same type as MarkConfig[P]
) {
return util_getFirstDefined(
// style config has highest precedence
vgChannel ? common_getStyleConfig(channel, mark, config.style) : undefined, common_getStyleConfig(channel, mark, config.style),
// then mark-specific config
vgChannel ? config[mark.type][vgChannel] : undefined, config[mark.type][channel],
// If there is vgChannel, skip vl channel.
// For example, vl size for text is vg fontSize, but config.mark.size is only for point size.
vgChannel ? config.mark[vgChannel] : config.mark[channel]);
}
function common_getStyleConfig(prop, mark, styleConfigIndex) {
const styles = common_getStyles(mark);
let value;
for (const style of styles) {
const styleConfig = styleConfigIndex[style];
// MarkConfig extends VgMarkConfig so a prop may not be a valid property for style
// However here we also check if it is defined, so it is okay to cast here
const p = prop;
if (styleConfig && styleConfig[p] !== undefined) {
value = styleConfig[p];
}
}
return value;
}
function common_formatSignalRef(fieldDef, specifiedFormat, expr, config) {
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
const isUTCScale = channeldef_isScaleFieldDef(fieldDef) && fieldDef['scale'] && fieldDef['scale'].type === scale_ScaleType.UTC;
return {
signal: common_timeFormatExpression(channeldef_vgField(fieldDef, {
expr
}), fieldDef.timeUnit, specifiedFormat, config.timeFormat, isUTCScale, true)
};
}
else {
const format = common_numberFormat(fieldDef, specifiedFormat, config);
if (bin_isBinning(fieldDef.bin)) {
const startField = channeldef_vgField(fieldDef, { expr });
const endField = channeldef_vgField(fieldDef, { expr, binSuffix: 'end' });
return {
signal: common_binFormatExpression(startField, endField, format, config)
};
}
else if (fieldDef.type === 'quantitative' || format) {
return {
signal: `${common_formatExpr(channeldef_vgField(fieldDef, { expr, binSuffix: 'range' }), format)}`
};
}
else {
return { signal: `''+${channeldef_vgField(fieldDef, { expr })}` };
}
}
}
/**
* Returns number format for a fieldDef
*/
function common_numberFormat(fieldDef, specifiedFormat, config) {
// Specified format in axis/legend has higher precedence than fieldDef.format
if (specifiedFormat) {
return specifiedFormat;
}
if (fieldDef.type === QUANTITATIVE) {
// we only apply the default if the field is quantitative
return config.numberFormat;
}
return undefined;
}
function common_formatExpr(field, format) {
return `format(${field}, "${format || ''}")`;
}
function common_numberFormatExpr(field, specifiedFormat, config) {
return common_formatExpr(field, (specifiedFormat !== null && specifiedFormat !== void 0 ? specifiedFormat : config.numberFormat));
}
function common_binFormatExpression(startField, endField, format, config) {
return `${predicate_fieldValidPredicate(startField, false)} ? "null" : ${common_numberFormatExpr(startField, format, config)} + "${common_BIN_RANGE_DELIMITER}" + ${common_numberFormatExpr(endField, format, config)}`;
}
/**
* Returns the time expression used for axis/legend labels or text mark for a temporal field
*/
function common_timeFormatExpression(field, timeUnit, format, rawTimeFormat, // should be provided only for actual text and headers, not axis/legend labels
isUTCScale, alwaysReturn = false) {
if (!timeUnit || format) {
// If there is not time unit, or if user explicitly specify format for axis/legend/text.
format = (format !== null && format !== void 0 ? format : rawTimeFormat); // only use provided timeFormat if there is no timeUnit.
if (format || alwaysReturn) {
return `${isUTCScale ? 'utc' : 'time'}Format(${field}, '${format}')`;
}
else {
return undefined;
}
}
else {
return timeunit_formatExpression(timeUnit, field, isUTCScale);
}
}
/**
* Return Vega sort parameters (tuple of field and order).
*/
function common_sortParams(orderDef, fieldRefOption) {
return vega_util_src_array(orderDef).reduce((s, orderChannelDef) => {
var _a;
s.field.push(channeldef_vgField(orderChannelDef, fieldRefOption));
s.order.push((_a = orderChannelDef.sort, (_a !== null && _a !== void 0 ? _a : 'ascending')));
return s;
}, { field: [], order: [] });
}
function common_mergeTitleFieldDefs(f1, f2) {
const merged = [...f1];
f2.forEach(fdToMerge => {
for (const fieldDef1 of merged) {
// If already exists, no need to append to merged array
if (util_deepEqual(fieldDef1, fdToMerge)) {
return;
}
}
merged.push(fdToMerge);
});
return merged;
}
function common_mergeTitle(title1, title2) {
if (util_deepEqual(title1, title2) || !title2) {
// if titles are the same or title2 is falsy
return title1;
}
else if (!title1) {
// if title1 is falsy
return title2;
}
else {
return [...vega_util_src_array(title1), ...vega_util_src_array(title2)].join(', ');
}
}
function common_mergeTitleComponent(v1, v2) {
const v1Val = v1.value;
const v2Val = v2.value;
if (v1Val == null || v2Val === null) {
return {
explicit: v1.explicit,
value: null
};
}
else if (title_isText(v1Val) && title_isText(v2Val)) {
return {
explicit: v1.explicit,
value: common_mergeTitle(v1Val, v2Val)
};
}
else if (!title_isText(v1Val) && !title_isText(v2Val)) {
return {
explicit: v1.explicit,
value: common_mergeTitleFieldDefs(v1Val, v2Val)
};
}
/* istanbul ignore next: Condition should not happen -- only for warning in development. */
throw new Error('It should never reach here');
}
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/sort.js
const sort_DEFAULT_SORT_OP = 'mean';
const sort_SORT_BY_CHANNEL_INDEX = {
x: 1,
y: 1,
color: 1,
fill: 1,
stroke: 1,
strokeWidth: 1,
size: 1,
shape: 1,
fillOpacity: 1,
strokeOpacity: 1,
opacity: 1,
text: 1
};
function sort_isSortByChannel(c) {
return !!sort_SORT_BY_CHANNEL_INDEX[c];
}
function sort_isSortByEncoding(sort) {
return !!sort && !!sort['encoding'];
}
function sort_isSortField(sort) {
return !!sort && (sort['op'] === 'count' || !!sort['field']);
}
function sort_isSortArray(sort) {
return !!sort && isArray(sort);
}
//# sourceMappingURL=sort.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/facet.js
function isFacetMapping(f) {
return !!f['row'] || !!f['column'];
}
function isFacetFieldDef(channelDef) {
return !!channelDef && !!channelDef['header'];
}
function isFacetSpec(spec) {
return spec['facet'] !== undefined;
}
//# sourceMappingURL=facet.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/channeldef.js
function channeldef_isConditionalSelection(c) {
return c['selection'];
}
function channeldef_isRepeatRef(field) {
return field && !isString(field) && 'repeat' in field;
}
function channeldef_toFieldDefBase(fieldDef) {
const { field, timeUnit, bin, aggregate } = fieldDef;
return Object.assign(Object.assign(Object.assign(Object.assign({}, (timeUnit ? { timeUnit } : {})), (bin ? { bin } : {})), (aggregate ? { aggregate } : {})), { field });
}
function channeldef_isSortableFieldDef(fieldDef) {
return channeldef_isTypedFieldDef(fieldDef) && !!fieldDef['sort'];
}
function channeldef_getBand(channel, fieldDef, fieldDef2, mark, config, { isMidPoint } = {}) {
const { timeUnit, bin } = fieldDef;
if (util_contains(['x', 'y'], channel)) {
if (channeldef_isPositionFieldDef(fieldDef) && fieldDef.band !== undefined) {
return fieldDef.band;
}
else if (timeUnit && !fieldDef2) {
if (isMidPoint) {
return common_getMarkConfig('timeUnitBandPosition', mark, config);
}
else {
return mark_isRectBasedMark(mark.type) ? common_getMarkConfig('timeUnitBand', mark, config) : 0;
}
}
else if (bin_isBinning(bin)) {
return mark_isRectBasedMark(mark.type) && !isMidPoint ? 1 : 0.5;
}
}
return undefined;
}
function channeldef_hasBand(channel, fieldDef, fieldDef2, mark, config) {
if (bin_isBinning(fieldDef.bin) || (fieldDef.timeUnit && channeldef_isTypedFieldDef(fieldDef) && fieldDef.type === 'temporal')) {
return !!channeldef_getBand(channel, fieldDef, fieldDef2, mark, config);
}
return false;
}
function channeldef_isConditionalDef(channelDef) {
return !!channelDef && !!channelDef.condition;
}
/**
* Return if a channelDef is a ConditionalValueDef with ConditionFieldDef
*/
function channeldef_hasConditionalFieldDef(channelDef) {
return !!channelDef && !!channelDef.condition && !isArray(channelDef.condition) && channeldef_isFieldDef(channelDef.condition);
}
function channeldef_hasConditionalValueDef(channelDef) {
return !!channelDef && !!channelDef.condition && (isArray(channelDef.condition) || channeldef_isValueDef(channelDef.condition));
}
function channeldef_isFieldDef(channelDef) {
return !!channelDef && (!!channelDef['field'] || channelDef['aggregate'] === 'count');
}
function channeldef_isTypedFieldDef(channelDef) {
return !!channelDef && ((!!channelDef['field'] && !!channelDef['type']) || channelDef['aggregate'] === 'count');
}
function channeldef_isStringFieldDef(channelDef) {
return channeldef_isFieldDef(channelDef) && isString(channelDef.field);
}
function channeldef_isValueDef(channelDef) {
return channelDef && 'value' in channelDef && channelDef['value'] !== undefined;
}
function channeldef_isScaleFieldDef(channelDef) {
return !!channelDef && (!!channelDef['scale'] || !!channelDef['sort']);
}
function channeldef_isPositionFieldDef(channelDef) {
return (!!channelDef &&
(!!channelDef['axis'] || !!channelDef['stack'] || !!channelDef['impute'] || channelDef['band'] !== undefined));
}
function channeldef_isMarkPropFieldDef(channelDef) {
return !!channelDef && !!channelDef['legend'];
}
function channeldef_isTextFieldDef(channelDef) {
return !!channelDef && !!channelDef['format'];
}
function channeldef_isOpFieldDef(fieldDef) {
return !!fieldDef['op'];
}
/**
* Get a Vega field reference from a Vega-Lite field def.
*/
function channeldef_vgField(fieldDef, opt = {}) {
var _a, _b, _c;
let field = fieldDef.field;
const prefix = opt.prefix;
let suffix = opt.suffix;
let argAccessor = ''; // for accessing argmin/argmax field at the end without getting escaped
if (channeldef_isCount(fieldDef)) {
field = util_internalField('count');
}
else {
let fn;
if (!opt.nofn) {
if (channeldef_isOpFieldDef(fieldDef)) {
fn = fieldDef.op;
}
else {
const { bin, aggregate, timeUnit } = fieldDef;
if (bin_isBinning(bin)) {
fn = bin_binToString(bin);
suffix = (_a = opt.binSuffix, (_a !== null && _a !== void 0 ? _a : '')) + (_b = opt.suffix, (_b !== null && _b !== void 0 ? _b : ''));
}
else if (aggregate) {
if (aggregate_isArgmaxDef(aggregate)) {
argAccessor = `.${field}`;
field = `argmax_${aggregate.argmax}`;
}
else if (aggregate_isArgminDef(aggregate)) {
argAccessor = `.${field}`;
field = `argmin_${aggregate.argmin}`;
}
else {
fn = String(aggregate);
}
}
else if (timeUnit) {
fn = String(timeUnit);
suffix = ((!util_contains(['range', 'mid'], opt.binSuffix) && opt.binSuffix) || '') + (_c = opt.suffix, (_c !== null && _c !== void 0 ? _c : ''));
}
}
}
if (fn) {
field = field ? `${fn}_${field}` : fn;
}
}
if (suffix) {
field = `${field}_${suffix}`;
}
if (prefix) {
field = `${prefix}_${field}`;
}
if (opt.forAs) {
return field;
}
else if (opt.expr) {
// Expression to access flattened field. No need to escape dots.
return util_flatAccessWithDatum(field, opt.expr) + argAccessor;
}
else {
// We flattened all fields so paths should have become dot.
return util_replacePathInField(field) + argAccessor;
}
}
function channeldef_isDiscrete(fieldDef) {
switch (fieldDef.type) {
case 'nominal':
case 'ordinal':
case 'geojson':
return true;
case 'quantitative':
return !!fieldDef.bin;
case 'temporal':
return false;
}
throw new Error(log_message.invalidFieldType(fieldDef.type));
}
function channeldef_isContinuous(fieldDef) {
return !channeldef_isDiscrete(fieldDef);
}
function channeldef_isCount(fieldDef) {
return fieldDef.aggregate === 'count';
}
function channeldef_verbalTitleFormatter(fieldDef, config) {
const { field, bin, timeUnit, aggregate } = fieldDef;
if (aggregate === 'count') {
return config.countTitle;
}
else if (bin_isBinning(bin)) {
return `${field} (binned)`;
}
else if (timeUnit) {
const units = timeunit_getTimeUnitParts(timeUnit).join('-');
return `${field} (${units})`;
}
else if (aggregate) {
if (aggregate_isArgmaxDef(aggregate)) {
return `${field} for max ${aggregate.argmax}`;
}
else if (aggregate_isArgminDef(aggregate)) {
return `${field} for min ${aggregate.argmin}`;
}
else {
return `${util_titlecase(aggregate)} of ${field}`;
}
}
return field;
}
function channeldef_functionalTitleFormatter(fieldDef) {
const { aggregate, bin, timeUnit, field } = fieldDef;
if (aggregate_isArgmaxDef(aggregate)) {
return `${field} for argmax(${aggregate.argmax})`;
}
else if (aggregate_isArgminDef(aggregate)) {
return `${field} for argmin(${aggregate.argmin})`;
}
const fn = aggregate || timeUnit || (bin_isBinning(bin) && 'bin');
if (fn) {
return fn.toUpperCase() + '(' + field + ')';
}
else {
return field;
}
}
const channeldef_defaultTitleFormatter = (fieldDef, config) => {
switch (config.fieldTitle) {
case 'plain':
return fieldDef.field;
case 'functional':
return channeldef_functionalTitleFormatter(fieldDef);
default:
return channeldef_verbalTitleFormatter(fieldDef, config);
}
};
let channeldef_titleFormatter = channeldef_defaultTitleFormatter;
function channeldef_setTitleFormatter(formatter) {
channeldef_titleFormatter = formatter;
}
function channeldef_resetTitleFormatter() {
channeldef_setTitleFormatter(channeldef_defaultTitleFormatter);
}
function channeldef_title(fieldDef, config, { allowDisabling, includeDefault = true }) {
var _a, _b;
const guide = (_a = channeldef_getGuide(fieldDef), (_a !== null && _a !== void 0 ? _a : {}));
const guideTitle = guide.title;
const def = includeDefault ? channeldef_defaultTitle(fieldDef, config) : undefined;
if (allowDisabling) {
return util_getFirstDefined(guideTitle, fieldDef.title, def);
}
else {
return _b = (guideTitle !== null && guideTitle !== void 0 ? guideTitle : fieldDef.title), (_b !== null && _b !== void 0 ? _b : def);
}
}
function channeldef_getGuide(fieldDef) {
if (channeldef_isPositionFieldDef(fieldDef) && fieldDef.axis) {
return fieldDef.axis;
}
else if (channeldef_isMarkPropFieldDef(fieldDef) && fieldDef.legend) {
return fieldDef.legend;
}
else if (isFacetFieldDef(fieldDef) && fieldDef.header) {
return fieldDef.header;
}
return undefined;
}
function channeldef_defaultTitle(fieldDef, config) {
return channeldef_titleFormatter(fieldDef, config);
}
function channeldef_format(fieldDef) {
var _a;
if (channeldef_isTextFieldDef(fieldDef) && fieldDef.format) {
return fieldDef.format;
}
else {
const guide = (_a = channeldef_getGuide(fieldDef), (_a !== null && _a !== void 0 ? _a : {}));
return guide.format;
}
}
function channeldef_defaultType(fieldDef, channel) {
if (fieldDef.timeUnit) {
return 'temporal';
}
if (bin_isBinning(fieldDef.bin)) {
return 'quantitative';
}
switch (channel_rangeType(channel)) {
case 'continuous':
return 'quantitative';
case 'discrete':
return 'nominal';
case 'flexible': // color
return 'nominal';
default:
return 'quantitative';
}
}
/**
* Returns the fieldDef -- either from the outer channelDef or from the condition of channelDef.
* @param channelDef
*/
function channeldef_getFieldDef(channelDef) {
if (channeldef_isFieldDef(channelDef)) {
return channelDef;
}
else if (channeldef_hasConditionalFieldDef(channelDef)) {
return channelDef.condition;
}
return undefined;
}
function channeldef_getTypedFieldDef(channelDef) {
if (channeldef_isFieldDef(channelDef)) {
return channelDef;
}
else if (channeldef_hasConditionalFieldDef(channelDef)) {
return channelDef.condition;
}
return undefined;
}
/**
* Convert type to full, lowercase type, or augment the fieldDef with a default type if missing.
*/
function channeldef_normalize(channelDef, channel) {
if (isString(channelDef) || src_isNumber(channelDef) || src_isBoolean(channelDef)) {
const primitiveType = isString(channelDef) ? 'string' : src_isNumber(channelDef) ? 'number' : 'boolean';
src_log_warn(log_message.primitiveChannelDef(channel, primitiveType, channelDef));
return { value: channelDef };
}
// If a fieldDef contains a field, we need type.
if (channeldef_isFieldDef(channelDef)) {
return channeldef_normalizeFieldDef(channelDef, channel);
}
else if (channeldef_hasConditionalFieldDef(channelDef)) {
return Object.assign(Object.assign({}, channelDef), {
// Need to cast as normalizeFieldDef normally return FieldDef, but here we know that it is definitely Condition<FieldDef>
condition: channeldef_normalizeFieldDef(channelDef.condition, channel) });
}
return channelDef;
}
function channeldef_normalizeFieldDef(fd, channel) {
const { aggregate, timeUnit, bin, field } = fd;
const fieldDef = Object.assign({}, fd);
// Drop invalid aggregate
if (aggregate && !aggregate_isAggregateOp(aggregate) && !aggregate_isArgmaxDef(aggregate) && !aggregate_isArgminDef(aggregate)) {
src_log_warn(log_message.invalidAggregate(aggregate));
delete fieldDef.aggregate;
}
// Normalize Time Unit
if (timeUnit) {
fieldDef.timeUnit = timeunit_normalizeTimeUnit(timeUnit);
}
if (field) {
fieldDef.field = `${field}`;
}
// Normalize bin
if (bin_isBinning(bin)) {
fieldDef.bin = channeldef_normalizeBin(bin, channel);
}
if (bin_isBinned(bin) && !util_contains(channel_POSITION_SCALE_CHANNELS, channel)) {
src_log_warn(`Channel ${channel} should not be used with "binned" bin`);
}
// Normalize Type
if (channeldef_isTypedFieldDef(fieldDef)) {
const { type } = fieldDef;
const fullType = getFullName(type);
if (type !== fullType) {
// convert short type to full type
fieldDef.type = fullType;
}
if (type !== 'quantitative') {
if (aggregate_isCountingAggregateOp(aggregate)) {
src_log_warn(log_message.invalidFieldTypeForCountAggregate(type, aggregate));
fieldDef.type = 'quantitative';
}
}
}
else if (!channel_isSecondaryRangeChannel(channel)) {
// If type is empty / invalid, then augment with default type
const newType = channeldef_defaultType(fieldDef, channel);
src_log_warn(log_message.missingFieldType(channel, newType));
fieldDef['type'] = newType;
}
if (channeldef_isTypedFieldDef(fieldDef)) {
const { compatible, warning } = channeldef_channelCompatibility(fieldDef, channel);
if (!compatible) {
src_log_warn(warning);
}
}
if (channeldef_isSortableFieldDef(fieldDef) && isString(fieldDef.sort)) {
const { sort } = fieldDef;
if (sort_isSortByChannel(sort)) {
return Object.assign(Object.assign({}, fieldDef), { sort: { encoding: sort } });
}
const sub = sort.substr(1);
if (sort.charAt(0) === '-' && sort_isSortByChannel(sub)) {
return Object.assign(Object.assign({}, fieldDef), { sort: { encoding: sub, order: 'descending' } });
}
}
return fieldDef;
}
function channeldef_normalizeBin(bin, channel) {
if (src_isBoolean(bin)) {
return { maxbins: bin_autoMaxBins(channel) };
}
else if (bin === 'binned') {
return {
binned: true
};
}
else if (!bin.maxbins && !bin.step) {
return Object.assign(Object.assign({}, bin), { maxbins: bin_autoMaxBins(channel) });
}
else {
return bin;
}
}
const channeldef_COMPATIBLE = { compatible: true };
function channeldef_channelCompatibility(fieldDef, channel) {
const type = fieldDef.type;
if (type === 'geojson' && channel !== 'shape') {
return {
compatible: false,
warning: `Channel ${channel} should not be used with a geojson data.`
};
}
switch (channel) {
case 'row':
case 'column':
case 'facet':
if (channeldef_isContinuous(fieldDef)) {
return {
compatible: false,
warning: log_message.facetChannelShouldBeDiscrete(channel)
};
}
return channeldef_COMPATIBLE;
case 'x':
case 'y':
case 'color':
case 'fill':
case 'stroke':
case 'text':
case 'detail':
case 'key':
case 'tooltip':
case 'href':
case 'url':
return channeldef_COMPATIBLE;
case 'longitude':
case 'longitude2':
case 'latitude':
case 'latitude2':
if (type !== QUANTITATIVE) {
return {
compatible: false,
warning: `Channel ${channel} should be used with a quantitative field only, not ${fieldDef.type} field.`
};
}
return channeldef_COMPATIBLE;
case 'opacity':
case 'fillOpacity':
case 'strokeOpacity':
case 'strokeWidth':
case 'size':
case 'x2':
case 'y2':
if (type === 'nominal' && !fieldDef['sort']) {
return {
compatible: false,
warning: `Channel ${channel} should not be used with an unsorted discrete field.`
};
}
return channeldef_COMPATIBLE;
case 'shape':
if (!util_contains(['ordinal', 'nominal', 'geojson'], fieldDef.type)) {
return {
compatible: false,
warning: 'Shape channel should be used with only either discrete or geojson data.'
};
}
return channeldef_COMPATIBLE;
case 'order':
if (fieldDef.type === 'nominal' && !('sort' in fieldDef)) {
return {
compatible: false,
warning: `Channel order is inappropriate for nominal field, which has no inherent order.`
};
}
return channeldef_COMPATIBLE;
}
throw new Error('channelCompatability not implemented for channel ' + channel);
}
/**
* Check if the field def uses a time format or does not use any format but is temporal
* (this does not cover field defs that are temporal but use a number format).
*/
function channeldef_isTimeFormatFieldDef(fieldDef) {
const guide = channeldef_getGuide(fieldDef);
const formatType = (guide && guide.formatType) || (channeldef_isTextFieldDef(fieldDef) && fieldDef.formatType);
return formatType === 'time' || (!formatType && channeldef_isTimeFieldDef(fieldDef));
}
/**
* Check if field def has tye `temporal`. If you want to also cover field defs that use a time format, use `isTimeFormatFieldDef`.
*/
function channeldef_isTimeFieldDef(fieldDef) {
return fieldDef.type === 'temporal' || !!fieldDef.timeUnit;
}
/**
* Getting a value associated with a fielddef.
* Convert the value to Vega expression if applicable (for datetime object, or string if the field def is temporal or has timeUnit)
*/
function channeldef_valueExpr(v, { timeUnit, type, time, undefinedIfExprNotRequired }) {
let expr;
if (datetime_isDateTime(v)) {
expr = datetime_dateTimeExpr(v, true);
}
else if (isString(v) || src_isNumber(v)) {
if (timeUnit || type === 'temporal') {
if (timeunit_isLocalSingleTimeUnit(timeUnit)) {
expr = datetime_dateTimeExpr({ [timeUnit]: v }, true);
}
else if (timeunit_isUtcSingleTimeUnit(timeUnit)) {
// FIXME is this really correct?
expr = channeldef_valueExpr(v, { timeUnit: timeunit_getLocalTimeUnit(timeUnit) });
}
else {
// just pass the string to date function (which will call JS Date.parse())
expr = `datetime(${JSON.stringify(v)})`;
}
}
}
if (expr) {
return time ? `time(${expr})` : expr;
}
// number or boolean or normal string
return undefinedIfExprNotRequired ? undefined : JSON.stringify(v);
}
/**
* Standardize value array -- convert each value to Vega expression if applicable
*/
function channeldef_valueArray(fieldDef, values) {
const { timeUnit, type } = fieldDef;
return values.map(v => {
const expr = channeldef_valueExpr(v, { timeUnit, type, undefinedIfExprNotRequired: true });
// return signal for the expression if we need an expression
if (expr !== undefined) {
return { signal: expr };
}
// otherwise just return the original value
return v;
});
}
/**
* Checks whether a fieldDef for a particular channel requires a computed bin range.
*/
function channeldef_binRequiresRange(fieldDef, channel) {
if (!bin_isBinning(fieldDef.bin)) {
console.warn('Only use this method with binned field defs');
return false;
}
// We need the range only when the user explicitly forces a binned field to be use discrete scale. In this case, bin range is used in axis and legend labels.
// We could check whether the axis or legend exists (not disabled) but that seems overkill.
return channel_isScaleChannel(channel) && util_contains(['ordinal', 'nominal'], fieldDef.type);
}
//# sourceMappingURL=channeldef.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/bin.js
/**
* Create a key for the bin configuration. Not for prebinned bin.
*/
function bin_binToString(bin) {
if (src_isBoolean(bin)) {
bin = channeldef_normalizeBin(bin, undefined);
}
return ('bin' +
util_keys(bin)
.map(p => (bin_isSelectionExtent(bin[p]) ? util_varName(`_${p}_${Object.entries(bin[p])}`) : util_varName(`_${p}_${bin[p]}`)))
.join(''));
}
/**
* Vega-Lite should bin the data.
*/
function bin_isBinning(bin) {
return bin === true || (bin_isBinParams(bin) && !bin.binned);
}
/**
* The data is already binned and so Vega-Lite should not bin it again.
*/
function bin_isBinned(bin) {
return bin === 'binned' || (bin_isBinParams(bin) && bin.binned === true);
}
function bin_isBinParams(bin) {
return isObject(bin);
}
function bin_isSelectionExtent(extent) {
var _a;
return (_a = extent) === null || _a === void 0 ? void 0 : _a['selection'];
}
function bin_autoMaxBins(channel) {
switch (channel) {
case channel_ROW:
case channel_COLUMN:
case channel_SIZE:
case channel_COLOR:
case channel_FILL:
case channel_STROKE:
case channel_STROKEWIDTH:
case channel_OPACITY:
case channel_FILLOPACITY:
case channel_STROKEOPACITY:
// Facets and Size shouldn't have too many bins
// We choose 6 like shape to simplify the rule [falls through]
case channel_SHAPE:
return 6; // Vega's "shape" has 6 distinct values
default:
return 10;
}
}
//# sourceMappingURL=bin.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/encoding.js
function encoding_channelHasField(encoding, channel) {
const channelDef = encoding && encoding[channel];
if (channelDef) {
if (isArray(channelDef)) {
return util_some(channelDef, fieldDef => !!fieldDef.field);
}
else {
return channeldef_isFieldDef(channelDef) || channeldef_hasConditionalFieldDef(channelDef);
}
}
return false;
}
function encoding_isAggregate(encoding) {
return util_some(channel_CHANNELS, channel => {
if (encoding_channelHasField(encoding, channel)) {
const channelDef = encoding[channel];
if (isArray(channelDef)) {
return util_some(channelDef, fieldDef => !!fieldDef.aggregate);
}
else {
const fieldDef = channeldef_getFieldDef(channelDef);
return fieldDef && !!fieldDef.aggregate;
}
}
return false;
});
}
function encoding_extractTransformsFromEncoding(oldEncoding, config) {
const groupby = [];
const bins = [];
const timeUnits = [];
const aggregate = [];
const encoding = {};
encoding_forEach(oldEncoding, (channelDef, channel) => {
// Extract potential embedded transformations along with remaining properties
if (channeldef_isFieldDef(channelDef)) {
const { field, aggregate: aggOp, timeUnit, bin } = channelDef, remaining = tslib_es6_rest(channelDef, ["field", "aggregate", "timeUnit", "bin"]);
if (aggOp || timeUnit || bin) {
const guide = channeldef_getGuide(channelDef);
const isTitleDefined = guide && guide.title;
let newField = channeldef_vgField(channelDef, { forAs: true });
const newFieldDef = Object.assign(Object.assign(Object.assign({}, (isTitleDefined ? [] : { title: channeldef_title(channelDef, config, { allowDisabling: true }) })), remaining), {
// Always overwrite field
field: newField });
const isPositionChannel = channel === 'x' || channel === 'y';
if (aggOp) {
let op;
if (aggregate_isArgmaxDef(aggOp)) {
op = 'argmax';
newField = channeldef_vgField({ op: 'argmax', field: aggOp.argmax }, { forAs: true });
newFieldDef.field = `${newField}.${field}`;
}
else if (aggregate_isArgminDef(aggOp)) {
op = 'argmin';
newField = channeldef_vgField({ op: 'argmin', field: aggOp.argmin }, { forAs: true });
newFieldDef.field = `${newField}.${field}`;
}
else if (aggOp !== 'boxplot' && aggOp !== 'errorbar' && aggOp !== 'errorband') {
op = aggOp;
}
if (op) {
const aggregateEntry = {
op,
as: newField
};
if (field) {
aggregateEntry.field = field;
}
aggregate.push(aggregateEntry);
}
}
else {
groupby.push(newField);
if (channeldef_isTypedFieldDef(channelDef) && bin_isBinning(bin)) {
bins.push({ bin, field, as: newField });
// Add additional groupbys for range and end of bins
groupby.push(channeldef_vgField(channelDef, { binSuffix: 'end' }));
if (channeldef_binRequiresRange(channelDef, channel)) {
groupby.push(channeldef_vgField(channelDef, { binSuffix: 'range' }));
}
// Create accompanying 'x2' or 'y2' field if channel is 'x' or 'y' respectively
if (isPositionChannel) {
const secondaryChannel = {
field: newField + '_end'
};
encoding[channel + '2'] = secondaryChannel;
}
newFieldDef.bin = 'binned';
if (!channel_isSecondaryRangeChannel(channel)) {
newFieldDef['type'] = 'quantitative';
}
}
else if (timeUnit) {
timeUnits.push({ timeUnit, field, as: newField });
// define the format type for later compilation
const formatType = channeldef_isTypedFieldDef(channelDef) && channelDef.type !== TEMPORAL && 'time';
if (formatType) {
if (channel === 'text' || channel === 'tooltip') {
newFieldDef['formatType'] = formatType;
}
else if (channel_isNonPositionScaleChannel(channel)) {
newFieldDef['legend'] = Object.assign({ formatType }, newFieldDef['legend']);
}
else if (isPositionChannel) {
newFieldDef['axis'] = Object.assign({ formatType }, newFieldDef['axis']);
}
}
}
}
// now the field should refer to post-transformed field instead
encoding[channel] = newFieldDef;
}
else {
groupby.push(field);
encoding[channel] = oldEncoding[channel];
}
}
else {
// For value def, just copy
encoding[channel] = oldEncoding[channel];
}
});
return {
bins,
timeUnits,
aggregate,
groupby,
encoding
};
}
function encoding_markChannelCompatible(encoding, channel, mark) {
const markSupported = channel_supportMark(channel, mark);
if (!markSupported) {
return false;
}
else if (markSupported === 'binned') {
const primaryFieldDef = encoding[channel === 'x2' ? 'x' : 'y'];
// circle, point, square and tick only support x2/y2 when their corresponding x/y fieldDef
// has "binned" data and thus need x2/y2 to specify the bin-end field.
if (channeldef_isFieldDef(primaryFieldDef) && channeldef_isFieldDef(encoding[channel]) && bin_isBinned(primaryFieldDef.bin)) {
return true;
}
else {
return false;
}
}
return true;
}
function encoding_normalizeEncoding(encoding, markDef) {
const mark = markDef.type;
return util_keys(encoding).reduce((normalizedEncoding, channel) => {
var _a;
if (!channel_isChannel(channel)) {
// Drop invalid channel
src_log_warn(log_message.invalidEncodingChannel(channel));
return normalizedEncoding;
}
if (!encoding_markChannelCompatible(encoding, channel, mark)) {
// Drop unsupported channel
src_log_warn(log_message.incompatibleChannel(channel, mark));
return normalizedEncoding;
}
// Drop line's size if the field is aggregated.
if (channel === 'size' && mark === 'line') {
const fieldDef = channeldef_getTypedFieldDef(encoding[channel]);
if ((_a = fieldDef) === null || _a === void 0 ? void 0 : _a.aggregate) {
src_log_warn(log_message.LINE_WITH_VARYING_SIZE);
return normalizedEncoding;
}
}
// Drop color if either fill or stroke is specified
if (channel === 'color' && (markDef.filled ? 'fill' in encoding : 'stroke' in encoding)) {
src_log_warn(log_message.droppingColor('encoding', { fill: 'fill' in encoding, stroke: 'stroke' in encoding }));
return normalizedEncoding;
}
const channelDef = encoding[channel];
if (channel === 'detail' ||
(channel === 'order' && !isArray(channelDef) && !channeldef_isValueDef(channelDef)) ||
(channel === 'tooltip' && isArray(channelDef))) {
if (channelDef) {
// Array of fieldDefs for detail channel (or production rule)
normalizedEncoding[channel] = (isArray(channelDef) ? channelDef : [channelDef]).reduce((defs, fieldDef) => {
if (!channeldef_isFieldDef(fieldDef)) {
src_log_warn(log_message.emptyFieldDef(fieldDef, channel));
}
else {
defs.push(channeldef_normalizeFieldDef(fieldDef, channel));
}
return defs;
}, []);
}
}
else {
if (channel === 'tooltip' && channelDef === null) {
// Preserve null so we can use it to disable tooltip
normalizedEncoding[channel] = null;
}
else if (!channeldef_isFieldDef(channelDef) && !channeldef_isValueDef(channelDef) && !channeldef_isConditionalDef(channelDef)) {
src_log_warn(log_message.emptyFieldDef(channelDef, channel));
return normalizedEncoding;
}
normalizedEncoding[channel] = channeldef_normalize(channelDef, channel);
}
return normalizedEncoding;
}, {});
}
function encoding_fieldDefs(encoding) {
const arr = [];
for (const channel of util_keys(encoding)) {
if (encoding_channelHasField(encoding, channel)) {
const channelDef = encoding[channel];
const channelDefArray = isArray(channelDef) ? channelDef : [channelDef];
for (const def of channelDefArray) {
if (channeldef_isFieldDef(def)) {
arr.push(def);
}
else if (channeldef_hasConditionalFieldDef(def)) {
arr.push(def.condition);
}
}
}
}
return arr;
}
function encoding_forEach(mapping, f, thisArg) {
if (!mapping) {
return;
}
for (const channel of util_keys(mapping)) {
const el = mapping[channel];
if (isArray(el)) {
el.forEach((channelDef) => {
f.call(thisArg, channelDef, channel);
});
}
else {
f.call(thisArg, el, channel);
}
}
}
function encoding_reduce(mapping, f, init, thisArg) {
if (!mapping) {
return init;
}
return util_keys(mapping).reduce((r, channel) => {
const map = mapping[channel];
if (isArray(map)) {
return map.reduce((r1, channelDef) => {
return f.call(thisArg, r1, channelDef, channel);
}, r);
}
else {
return f.call(thisArg, r, map, channel);
}
}, init);
}
/**
* Returns list of path grouping fields for the given encoding
*/
function encoding_pathGroupingFields(mark, encoding) {
return util_keys(encoding).reduce((details, channel) => {
switch (channel) {
// x, y, x2, y2, lat, long, lat1, long2, order, tooltip, href, cursor should not cause lines to group
case 'x':
case 'y':
case 'href':
case 'url':
case 'x2':
case 'y2':
// falls through
case 'latitude':
case 'longitude':
case 'latitude2':
case 'longitude2':
// TODO: case 'cursor':
// text, shape, shouldn't be a part of line/trail/area [falls through]
case 'text':
case 'shape':
// falls through
// tooltip fields should not be added to group by [falls through]
case 'tooltip':
return details;
case 'order':
// order should not group line / trail
if (mark === 'line' || mark === 'trail') {
return details;
}
// but order should group area for stacking (falls through)
case 'detail':
case 'key': {
const channelDef = encoding[channel];
if (isArray(channelDef) || channeldef_isFieldDef(channelDef)) {
(isArray(channelDef) ? channelDef : [channelDef]).forEach(fieldDef => {
if (!fieldDef.aggregate) {
details.push(channeldef_vgField(fieldDef, {}));
}
});
}
return details;
}
case 'size':
if (mark === 'trail') {
// For trail, size should not group trail lines.
return details;
}
// For line, size should group lines.
// falls through
case 'color':
case 'fill':
case 'stroke':
case 'opacity':
case 'fillOpacity':
case 'strokeOpacity':
case 'strokeWidth': {
// TODO strokeDashOffset:
// falls through
const fieldDef = channeldef_getTypedFieldDef(encoding[channel]);
if (fieldDef && !fieldDef.aggregate) {
details.push(channeldef_vgField(fieldDef, {}));
}
return details;
}
}
}, []);
}
//# sourceMappingURL=encoding.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compositemark/common.js
function common_filterTooltipWithAggregatedField(oldEncoding) {
const { tooltip } = oldEncoding, filteredEncoding = tslib_es6_rest(oldEncoding, ["tooltip"]);
if (!tooltip) {
return { filteredEncoding: oldEncoding };
}
let customTooltipWithAggregatedField;
let customTooltipWithoutAggregatedField;
if (isArray(tooltip)) {
tooltip.forEach((t) => {
if (t.aggregate) {
if (!customTooltipWithAggregatedField) {
customTooltipWithAggregatedField = [];
}
customTooltipWithAggregatedField.push(t);
}
else {
if (!customTooltipWithoutAggregatedField) {
customTooltipWithoutAggregatedField = [];
}
customTooltipWithoutAggregatedField.push(t);
}
});
if (customTooltipWithAggregatedField) {
filteredEncoding.tooltip = customTooltipWithAggregatedField;
}
}
else {
if (tooltip['aggregate']) {
filteredEncoding.tooltip = tooltip;
}
else {
customTooltipWithoutAggregatedField = tooltip;
}
}
if (isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {
customTooltipWithoutAggregatedField = customTooltipWithoutAggregatedField[0];
}
return { customTooltipWithoutAggregatedField, filteredEncoding };
}
function common_getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, withFieldName = true) {
if ('tooltip' in encodingWithoutContinuousAxis) {
return { tooltip: encodingWithoutContinuousAxis.tooltip };
}
const fiveSummaryTooltip = tooltipSummary.map(({ fieldPrefix, titlePrefix }) => ({
field: fieldPrefix + continuousAxisChannelDef.field,
type: continuousAxisChannelDef.type,
title: titlePrefix + (withFieldName ? ' of ' + continuousAxisChannelDef.field : '')
}));
return {
tooltip: [
...fiveSummaryTooltip,
// need to cast because TextFieldDef support fewer types of bin
...encoding_fieldDefs(encodingWithoutContinuousAxis)
]
};
}
function common_getTitle(continuousAxisChannelDef) {
const { axis, title, field } = continuousAxisChannelDef;
return axis && axis.title !== undefined ? undefined : util_getFirstDefined(title, field);
}
function common_makeCompositeAggregatePartFactory(compositeMarkDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, compositeMarkConfig) {
const { scale, axis } = continuousAxisChannelDef;
return ({ partName, mark, positionPrefix, endPositionPrefix = undefined, extraEncoding = {} }) => {
const title = common_getTitle(continuousAxisChannelDef);
return common_partLayerMixins(compositeMarkDef, partName, compositeMarkConfig, {
mark,
encoding: Object.assign(Object.assign(Object.assign({ [continuousAxis]: Object.assign(Object.assign(Object.assign({ field: positionPrefix + '_' + continuousAxisChannelDef.field, type: continuousAxisChannelDef.type }, (title !== undefined ? { title } : {})), (scale !== undefined ? { scale } : {})), (axis !== undefined ? { axis } : {})) }, (isString(endPositionPrefix)
? {
[continuousAxis + '2']: {
field: endPositionPrefix + '_' + continuousAxisChannelDef.field,
type: continuousAxisChannelDef.type
}
}
: {})), sharedEncoding), extraEncoding)
});
};
}
function common_partLayerMixins(markDef, part, compositeMarkConfig, partBaseSpec) {
const { clip, color, opacity } = markDef;
const mark = markDef.type;
if (markDef[part] || (markDef[part] === undefined && compositeMarkConfig[part])) {
return [
Object.assign(Object.assign({}, partBaseSpec), { mark: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, compositeMarkConfig[part]), (clip ? { clip } : {})), (color ? { color } : {})), (opacity ? { opacity } : {})), (mark_isMarkDef(partBaseSpec.mark) ? partBaseSpec.mark : { type: partBaseSpec.mark })), { style: `${mark}-${part}` }), (src_isBoolean(markDef[part]) ? {} : markDef[part])) })
];
}
return [];
}
function common_compositeMarkContinuousAxis(spec, orient, compositeMark) {
const { encoding } = spec;
const continuousAxis = orient === 'vertical' ? 'y' : 'x';
const continuousAxisChannelDef = encoding[continuousAxis]; // Safe to cast because if x is not continuous fielddef, the orient would not be horizontal.
const continuousAxisChannelDef2 = encoding[continuousAxis + '2'];
const continuousAxisChannelDefError = encoding[continuousAxis + 'Error'];
const continuousAxisChannelDefError2 = encoding[continuousAxis + 'Error2'];
return {
continuousAxisChannelDef: common_filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark),
continuousAxisChannelDef2: common_filterAggregateFromChannelDef(continuousAxisChannelDef2, compositeMark),
continuousAxisChannelDefError: common_filterAggregateFromChannelDef(continuousAxisChannelDefError, compositeMark),
continuousAxisChannelDefError2: common_filterAggregateFromChannelDef(continuousAxisChannelDefError2, compositeMark),
continuousAxis
};
}
function common_filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark) {
if (continuousAxisChannelDef && continuousAxisChannelDef.aggregate) {
const { aggregate } = continuousAxisChannelDef, continuousAxisWithoutAggregate = tslib_es6_rest(continuousAxisChannelDef, ["aggregate"]);
if (aggregate !== compositeMark) {
src_log_warn(log_message.errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark));
}
return continuousAxisWithoutAggregate;
}
else {
return continuousAxisChannelDef;
}
}
function common_compositeMarkOrient(spec, compositeMark) {
const { mark, encoding } = spec;
if (channeldef_isFieldDef(encoding.x) && channeldef_isContinuous(encoding.x)) {
// x is continuous
if (channeldef_isFieldDef(encoding.y) && channeldef_isContinuous(encoding.y)) {
// both x and y are continuous
if (encoding.x.aggregate === undefined && encoding.y.aggregate === compositeMark) {
return 'vertical';
}
else if (encoding.y.aggregate === undefined && encoding.x.aggregate === compositeMark) {
return 'horizontal';
}
else if (encoding.x.aggregate === compositeMark && encoding.y.aggregate === compositeMark) {
throw new Error('Both x and y cannot have aggregate');
}
else {
if (mark_isMarkDef(mark) && mark.orient) {
return mark.orient;
}
// default orientation = vertical
return 'vertical';
}
}
// x is continuous but y is not
return 'horizontal';
}
else if (channeldef_isFieldDef(encoding.y) && channeldef_isContinuous(encoding.y)) {
// y is continuous but x is not
return 'vertical';
}
else {
// Neither x nor y is continuous.
throw new Error('Need a valid continuous axis for ' + compositeMark + 's');
}
}
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compositemark/boxplot.js
const boxplot_BOXPLOT = 'boxplot';
const boxplot_BOXPLOT_PART_INDEX = {
box: 1,
median: 1,
outliers: 1,
rule: 1,
ticks: 1
};
const boxplot_BOXPLOT_PARTS = util_keys(boxplot_BOXPLOT_PART_INDEX);
const boxplot_boxPlotNormalizer = new base_CompositeMarkNormalizer(boxplot_BOXPLOT, boxplot_normalizeBoxPlot);
function boxplot_getBoxPlotType(extent) {
if (src_isNumber(extent)) {
return 'tukey';
}
// Ham: If we ever want to, we could add another extent syntax `{kIQR: number}` for the original [Q1-k*IQR, Q3+k*IQR] whisker and call this boxPlotType = `kIQR`. However, I'm not exposing this for now.
return extent;
}
function boxplot_normalizeBoxPlot(spec, { config }) {
var _a, _b;
// TODO: use selection
const { mark, encoding: _encoding, selection, projection: _p } = spec, outerSpec = tslib_es6_rest(spec, ["mark", "encoding", "selection", "projection"]);
const markDef = mark_isMarkDef(mark) ? mark : { type: mark };
// TODO(https://github.com/vega/vega-lite/issues/3702): add selection support
if (selection) {
src_log_warn(log_message.selectionNotSupported('boxplot'));
}
const extent = (_a = markDef.extent, (_a !== null && _a !== void 0 ? _a : config.boxplot.extent));
const sizeValue = util_getFirstDefined(markDef.size, config.boxplot.size);
const boxPlotType = boxplot_getBoxPlotType(extent);
const { transform, continuousAxisChannelDef, continuousAxis, groupby, aggregate, encodingWithoutContinuousAxis, ticksOrient, boxOrient, customTooltipWithoutAggregatedField } = boxplot_boxParams(spec, extent, config);
const { color, size } = encodingWithoutContinuousAxis, encodingWithoutSizeColorAndContinuousAxis = tslib_es6_rest(encodingWithoutContinuousAxis, ["color", "size"]);
const makeBoxPlotPart = (sharedEncoding) => {
return common_makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, config.boxplot);
};
const makeBoxPlotExtent = makeBoxPlotPart(encodingWithoutSizeColorAndContinuousAxis);
const makeBoxPlotBox = makeBoxPlotPart(encodingWithoutContinuousAxis);
const makeBoxPlotMidTick = makeBoxPlotPart(Object.assign(Object.assign({}, encodingWithoutSizeColorAndContinuousAxis), (size ? { size } : {})));
const fiveSummaryTooltipEncoding = common_getCompositeMarkTooltip([
{ fieldPrefix: boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_', titlePrefix: 'Max' },
{ fieldPrefix: 'upper_box_', titlePrefix: 'Q3' },
{ fieldPrefix: 'mid_box_', titlePrefix: 'Median' },
{ fieldPrefix: 'lower_box_', titlePrefix: 'Q1' },
{ fieldPrefix: boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_', titlePrefix: 'Min' }
], continuousAxisChannelDef, encodingWithoutContinuousAxis);
// ## Whisker Layers
const endTick = { type: 'tick', color: 'black', opacity: 1, orient: ticksOrient, invalid: null };
const whiskerTooltipEncoding = boxPlotType === 'min-max'
? fiveSummaryTooltipEncoding // for min-max, show five-summary tooltip for whisker
: // for tukey / k-IQR, just show upper/lower-whisker
common_getCompositeMarkTooltip([
{ fieldPrefix: 'upper_whisker_', titlePrefix: 'Upper Whisker' },
{ fieldPrefix: 'lower_whisker_', titlePrefix: 'Lower Whisker' }
], continuousAxisChannelDef, encodingWithoutContinuousAxis);
const whiskerLayers = [
...makeBoxPlotExtent({
partName: 'rule',
mark: { type: 'rule', invalid: null },
positionPrefix: 'lower_whisker',
endPositionPrefix: 'lower_box',
extraEncoding: whiskerTooltipEncoding
}),
...makeBoxPlotExtent({
partName: 'rule',
mark: { type: 'rule', invalid: null },
positionPrefix: 'upper_box',
endPositionPrefix: 'upper_whisker',
extraEncoding: whiskerTooltipEncoding
}),
...makeBoxPlotExtent({
partName: 'ticks',
mark: endTick,
positionPrefix: 'lower_whisker',
extraEncoding: whiskerTooltipEncoding
}),
...makeBoxPlotExtent({
partName: 'ticks',
mark: endTick,
positionPrefix: 'upper_whisker',
extraEncoding: whiskerTooltipEncoding
})
];
// ## Box Layers
// TODO: support hiding certain mark parts
const boxLayers = [
...(boxPlotType !== 'tukey' ? whiskerLayers : []),
...makeBoxPlotBox({
partName: 'box',
mark: Object.assign(Object.assign({ type: 'bar' }, (sizeValue ? { size: sizeValue } : {})), { orient: boxOrient, invalid: null }),
positionPrefix: 'lower_box',
endPositionPrefix: 'upper_box',
extraEncoding: fiveSummaryTooltipEncoding
}),
...makeBoxPlotMidTick({
partName: 'median',
mark: Object.assign(Object.assign(Object.assign({ type: 'tick', invalid: null }, (isObject(config.boxplot.median) && config.boxplot.median.color ? { color: config.boxplot.median.color } : {})), (sizeValue ? { size: sizeValue } : {})), { orient: ticksOrient }),
positionPrefix: 'mid_box',
extraEncoding: fiveSummaryTooltipEncoding
})
];
// ## Filtered Layers
let filteredLayersMixins;
if (boxPlotType !== 'min-max') {
const lowerBoxExpr = `datum["lower_box_${continuousAxisChannelDef.field}"]`;
const upperBoxExpr = `datum["upper_box_${continuousAxisChannelDef.field}"]`;
const iqrExpr = `(${upperBoxExpr} - ${lowerBoxExpr})`;
const lowerWhiskerExpr = `${lowerBoxExpr} - ${extent} * ${iqrExpr}`;
const upperWhiskerExpr = `${upperBoxExpr} + ${extent} * ${iqrExpr}`;
const fieldExpr = `datum["${continuousAxisChannelDef.field}"]`;
const joinaggregateTransform = {
joinaggregate: boxplot_boxParamsQuartiles(continuousAxisChannelDef.field),
groupby
};
let filteredWhiskerSpec = undefined;
if (boxPlotType === 'tukey') {
filteredWhiskerSpec = {
transform: [
{
filter: `(${lowerWhiskerExpr} <= ${fieldExpr}) && (${fieldExpr} <= ${upperWhiskerExpr})`
},
{
aggregate: [
{
op: 'min',
field: continuousAxisChannelDef.field,
as: 'lower_whisker_' + continuousAxisChannelDef.field
},
{
op: 'max',
field: continuousAxisChannelDef.field,
as: 'upper_whisker_' + continuousAxisChannelDef.field
},
// preserve lower_box / upper_box
{
op: 'min',
field: 'lower_box_' + continuousAxisChannelDef.field,
as: 'lower_box_' + continuousAxisChannelDef.field
},
{
op: 'max',
field: 'upper_box_' + continuousAxisChannelDef.field,
as: 'upper_box_' + continuousAxisChannelDef.field
},
...aggregate
],
groupby
}
],
layer: whiskerLayers
};
}
const { tooltip } = encodingWithoutSizeColorAndContinuousAxis, encodingWithoutSizeColorContinuousAxisAndTooltip = tslib_es6_rest(encodingWithoutSizeColorAndContinuousAxis, ["tooltip"]);
const { scale, axis } = continuousAxisChannelDef;
const title = common_getTitle(continuousAxisChannelDef);
const outlierLayersMixins = common_partLayerMixins(markDef, 'outliers', config.boxplot, {
transform: [{ filter: `(${fieldExpr} < ${lowerWhiskerExpr}) || (${fieldExpr} > ${upperWhiskerExpr})` }],
mark: 'point',
encoding: Object.assign(Object.assign({ [continuousAxis]: Object.assign(Object.assign(Object.assign({ field: continuousAxisChannelDef.field, type: continuousAxisChannelDef.type }, (title !== undefined ? { title } : {})), (scale !== undefined ? { scale } : {})), (axis !== undefined ? { axis } : {})) }, encodingWithoutSizeColorContinuousAxisAndTooltip), (customTooltipWithoutAggregatedField ? { tooltip: customTooltipWithoutAggregatedField } : {}))
})[0];
if (outlierLayersMixins && filteredWhiskerSpec) {
filteredLayersMixins = {
transform: [joinaggregateTransform],
layer: [outlierLayersMixins, filteredWhiskerSpec]
};
}
else if (outlierLayersMixins) {
filteredLayersMixins = outlierLayersMixins;
filteredLayersMixins.transform.unshift(joinaggregateTransform);
}
else if (filteredWhiskerSpec) {
filteredLayersMixins = filteredWhiskerSpec;
filteredLayersMixins.transform.unshift(joinaggregateTransform);
}
}
if (filteredLayersMixins) {
// tukey box plot with outliers included
return Object.assign(Object.assign({}, outerSpec), { layer: [
filteredLayersMixins,
{
// boxplot
transform,
layer: boxLayers
}
] });
}
return Object.assign(Object.assign({}, outerSpec), { transform: (_b = outerSpec.transform, (_b !== null && _b !== void 0 ? _b : [])).concat(transform), layer: boxLayers });
}
function boxplot_boxParamsQuartiles(continousAxisField) {
return [
{
op: 'q1',
field: continousAxisField,
as: 'lower_box_' + continousAxisField
},
{
op: 'q3',
field: continousAxisField,
as: 'upper_box_' + continousAxisField
}
];
}
function boxplot_boxParams(spec, extent, config) {
const orient = common_compositeMarkOrient(spec, boxplot_BOXPLOT);
const { continuousAxisChannelDef, continuousAxis } = common_compositeMarkContinuousAxis(spec, orient, boxplot_BOXPLOT);
const continuousFieldName = continuousAxisChannelDef.field;
const boxPlotType = boxplot_getBoxPlotType(extent);
const boxplotSpecificAggregate = [
...boxplot_boxParamsQuartiles(continuousFieldName),
{
op: 'median',
field: continuousFieldName,
as: 'mid_box_' + continuousFieldName
},
{
op: 'min',
field: continuousFieldName,
as: (boxPlotType === 'min-max' ? 'lower_whisker_' : 'min_') + continuousFieldName
},
{
op: 'max',
field: continuousFieldName,
as: (boxPlotType === 'min-max' ? 'upper_whisker_' : 'max_') + continuousFieldName
}
];
const postAggregateCalculates = boxPlotType === 'min-max' || boxPlotType === 'tukey'
? []
: [
// This is for the original k-IQR, which we do not expose
{
calculate: `datum["upper_box_${continuousFieldName}"] - datum["lower_box_${continuousFieldName}"]`,
as: 'iqr_' + continuousFieldName
},
{
calculate: `min(datum["upper_box_${continuousFieldName}"] + datum["iqr_${continuousFieldName}"] * ${extent}, datum["max_${continuousFieldName}"])`,
as: 'upper_whisker_' + continuousFieldName
},
{
calculate: `max(datum["lower_box_${continuousFieldName}"] - datum["iqr_${continuousFieldName}"] * ${extent}, datum["min_${continuousFieldName}"])`,
as: 'lower_whisker_' + continuousFieldName
}
];
const _a = spec.encoding, _b = continuousAxis, oldContinuousAxisChannelDef = _a[_b], oldEncodingWithoutContinuousAxis = tslib_es6_rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
const { customTooltipWithoutAggregatedField, filteredEncoding } = common_filterTooltipWithAggregatedField(oldEncodingWithoutContinuousAxis);
const { bins, timeUnits, aggregate, groupby, encoding: encodingWithoutContinuousAxis } = encoding_extractTransformsFromEncoding(filteredEncoding, config);
const ticksOrient = orient === 'vertical' ? 'horizontal' : 'vertical';
const boxOrient = orient;
const transform = [
...bins,
...timeUnits,
{
aggregate: [...aggregate, ...boxplotSpecificAggregate],
groupby
},
...postAggregateCalculates
];
return {
transform,
groupby,
aggregate,
continuousAxisChannelDef,
continuousAxis,
encodingWithoutContinuousAxis,
ticksOrient,
boxOrient,
customTooltipWithoutAggregatedField
};
}
//# sourceMappingURL=boxplot.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compositemark/errorbar.js
const errorbar_ERRORBAR = 'errorbar';
const errorbar_ERRORBAR_PART_INDEX = {
ticks: 1,
rule: 1
};
const errorbar_ERRORBAR_PARTS = util_keys(errorbar_ERRORBAR_PART_INDEX);
const errorbar_errorBarNormalizer = new base_CompositeMarkNormalizer(errorbar_ERRORBAR, errorbar_normalizeErrorBar);
function errorbar_normalizeErrorBar(spec, { config }) {
const { transform, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, ticksOrient, markDef, outerSpec, tooltipEncoding } = errorbar_errorBarParams(spec, errorbar_ERRORBAR, config);
const makeErrorBarPart = common_makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorbar);
const tick = { type: 'tick', orient: ticksOrient };
return Object.assign(Object.assign({}, outerSpec), { transform, layer: [
...makeErrorBarPart({
partName: 'ticks',
mark: tick,
positionPrefix: 'lower',
extraEncoding: tooltipEncoding
}),
...makeErrorBarPart({
partName: 'ticks',
mark: tick,
positionPrefix: 'upper',
extraEncoding: tooltipEncoding
}),
...makeErrorBarPart({
partName: 'rule',
mark: 'rule',
positionPrefix: 'lower',
endPositionPrefix: 'upper',
extraEncoding: tooltipEncoding
})
] });
}
function errorbar_errorBarOrientAndInputType(spec, compositeMark) {
const { encoding } = spec;
if (errorbar_errorBarIsInputTypeRaw(encoding)) {
return {
orient: common_compositeMarkOrient(spec, compositeMark),
inputType: 'raw'
};
}
const isTypeAggregatedUpperLower = errorbar_errorBarIsInputTypeAggregatedUpperLower(encoding);
const isTypeAggregatedError = errorbar_errorBarIsInputTypeAggregatedError(encoding);
const x = encoding.x;
const y = encoding.y;
if (isTypeAggregatedUpperLower) {
// type is aggregated-upper-lower
if (isTypeAggregatedError) {
throw new Error(compositeMark + ' cannot be both type aggregated-upper-lower and aggregated-error');
}
const x2 = encoding.x2;
const y2 = encoding.y2;
if (channeldef_isFieldDef(x2) && channeldef_isFieldDef(y2)) {
// having both x, x2 and y, y2
throw new Error(compositeMark + ' cannot have both x2 and y2');
}
else if (channeldef_isFieldDef(x2)) {
if (channeldef_isFieldDef(x) && channeldef_isContinuous(x)) {
// having x, x2 quantitative and field y, y2 are not specified
return { orient: 'horizontal', inputType: 'aggregated-upper-lower' };
}
else {
// having x, x2 that are not both quantitative
throw new Error('Both x and x2 have to be quantitative in ' + compositeMark);
}
}
else if (channeldef_isFieldDef(y2)) {
// y2 is a FieldDef
if (channeldef_isFieldDef(y) && channeldef_isContinuous(y)) {
// having y, y2 quantitative and field x, x2 are not specified
return { orient: 'vertical', inputType: 'aggregated-upper-lower' };
}
else {
// having y, y2 that are not both quantitative
throw new Error('Both y and y2 have to be quantitative in ' + compositeMark);
}
}
throw new Error('No ranged axis');
}
else {
// type is aggregated-error
const xError = encoding.xError;
const xError2 = encoding.xError2;
const yError = encoding.yError;
const yError2 = encoding.yError2;
if (channeldef_isFieldDef(xError2) && !channeldef_isFieldDef(xError)) {
// having xError2 without xError
throw new Error(compositeMark + ' cannot have xError2 without xError');
}
if (channeldef_isFieldDef(yError2) && !channeldef_isFieldDef(yError)) {
// having yError2 without yError
throw new Error(compositeMark + ' cannot have yError2 without yError');
}
if (channeldef_isFieldDef(xError) && channeldef_isFieldDef(yError)) {
// having both xError and yError
throw new Error(compositeMark + ' cannot have both xError and yError with both are quantiative');
}
else if (channeldef_isFieldDef(xError)) {
if (channeldef_isFieldDef(x) && channeldef_isContinuous(x)) {
// having x and xError that are all quantitative
return { orient: 'horizontal', inputType: 'aggregated-error' };
}
else {
// having x, xError, and xError2 that are not all quantitative
throw new Error('All x, xError, and xError2 (if exist) have to be quantitative');
}
}
else if (channeldef_isFieldDef(yError)) {
if (channeldef_isFieldDef(y) && channeldef_isContinuous(y)) {
// having y and yError that are all quantitative
return { orient: 'vertical', inputType: 'aggregated-error' };
}
else {
// having y, yError, and yError2 that are not all quantitative
throw new Error('All y, yError, and yError2 (if exist) have to be quantitative');
}
}
throw new Error('No ranged axis');
}
}
function errorbar_errorBarIsInputTypeRaw(encoding) {
return ((channeldef_isFieldDef(encoding.x) || channeldef_isFieldDef(encoding.y)) &&
!channeldef_isFieldDef(encoding.x2) &&
!channeldef_isFieldDef(encoding.y2) &&
!channeldef_isFieldDef(encoding.xError) &&
!channeldef_isFieldDef(encoding.xError2) &&
!channeldef_isFieldDef(encoding.yError) &&
!channeldef_isFieldDef(encoding.yError2));
}
function errorbar_errorBarIsInputTypeAggregatedUpperLower(encoding) {
return channeldef_isFieldDef(encoding.x2) || channeldef_isFieldDef(encoding.y2);
}
function errorbar_errorBarIsInputTypeAggregatedError(encoding) {
return (channeldef_isFieldDef(encoding.xError) ||
channeldef_isFieldDef(encoding.xError2) ||
channeldef_isFieldDef(encoding.yError) ||
channeldef_isFieldDef(encoding.yError2));
}
function errorbar_errorBarParams(spec, compositeMark, config) {
var _a;
// TODO: use selection
const { mark, encoding, selection, projection: _p } = spec, outerSpec = tslib_es6_rest(spec, ["mark", "encoding", "selection", "projection"]);
const markDef = mark_isMarkDef(mark) ? mark : { type: mark };
// TODO(https://github.com/vega/vega-lite/issues/3702): add selection support
if (selection) {
src_log_warn(log_message.selectionNotSupported(compositeMark));
}
const { orient, inputType } = errorbar_errorBarOrientAndInputType(spec, compositeMark);
const { continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, continuousAxis } = common_compositeMarkContinuousAxis(spec, orient, compositeMark);
const { errorBarSpecificAggregate, postAggregateCalculates, tooltipSummary, tooltipTitleWithFieldName } = errorbar_errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config);
const _b = continuousAxis, oldContinuousAxisChannelDef = encoding[_b], _c = continuousAxis === 'x' ? 'x2' : 'y2', oldContinuousAxisChannelDef2 = encoding[_c], _d = continuousAxis === 'x' ? 'xError' : 'yError', oldContinuousAxisChannelDefError = encoding[_d], _e = continuousAxis === 'x' ? 'xError2' : 'yError2', oldContinuousAxisChannelDefError2 = encoding[_e], oldEncodingWithoutContinuousAxis = tslib_es6_rest(encoding, [typeof _b === "symbol" ? _b : _b + "", typeof _c === "symbol" ? _c : _c + "", typeof _d === "symbol" ? _d : _d + "", typeof _e === "symbol" ? _e : _e + ""]);
const { bins, timeUnits, aggregate: oldAggregate, groupby: oldGroupBy, encoding: encodingWithoutContinuousAxis } = encoding_extractTransformsFromEncoding(oldEncodingWithoutContinuousAxis, config);
const aggregate = [...oldAggregate, ...errorBarSpecificAggregate];
const groupby = inputType !== 'raw' ? [] : oldGroupBy;
const tooltipEncoding = common_getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, tooltipTitleWithFieldName);
return {
transform: [
...(_a = outerSpec.transform, (_a !== null && _a !== void 0 ? _a : [])),
...bins,
...timeUnits,
...(aggregate.length === 0 ? [] : [{ aggregate, groupby }]),
...postAggregateCalculates
],
groupby,
continuousAxisChannelDef,
continuousAxis,
encodingWithoutContinuousAxis,
ticksOrient: orient === 'vertical' ? 'horizontal' : 'vertical',
markDef,
outerSpec,
tooltipEncoding
};
}
function errorbar_errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config) {
let errorBarSpecificAggregate = [];
let postAggregateCalculates = [];
const continuousFieldName = continuousAxisChannelDef.field;
let tooltipSummary;
let tooltipTitleWithFieldName = false;
if (inputType === 'raw') {
const center = markDef.center
? markDef.center
: markDef.extent
? markDef.extent === 'iqr'
? 'median'
: 'mean'
: config.errorbar.center;
const extent = markDef.extent ? markDef.extent : center === 'mean' ? 'stderr' : 'iqr';
if ((center === 'median') !== (extent === 'iqr')) {
src_log_warn(log_message.errorBarCenterIsUsedWithWrongExtent(center, extent, compositeMark));
}
if (extent === 'stderr' || extent === 'stdev') {
errorBarSpecificAggregate = [
{ op: extent, field: continuousFieldName, as: 'extent_' + continuousFieldName },
{ op: center, field: continuousFieldName, as: 'center_' + continuousFieldName }
];
postAggregateCalculates = [
{
calculate: `datum["center_${continuousFieldName}"] + datum["extent_${continuousFieldName}"]`,
as: 'upper_' + continuousFieldName
},
{
calculate: `datum["center_${continuousFieldName}"] - datum["extent_${continuousFieldName}"]`,
as: 'lower_' + continuousFieldName
}
];
tooltipSummary = [
{ fieldPrefix: 'center_', titlePrefix: util_titlecase(center) },
{ fieldPrefix: 'upper_', titlePrefix: errorbar_getTitlePrefix(center, extent, '+') },
{ fieldPrefix: 'lower_', titlePrefix: errorbar_getTitlePrefix(center, extent, '-') }
];
tooltipTitleWithFieldName = true;
}
else {
if (markDef.center && markDef.extent) {
src_log_warn(log_message.errorBarCenterIsNotNeeded(markDef.extent, compositeMark));
}
let centerOp;
let lowerExtentOp;
let upperExtentOp;
if (extent === 'ci') {
centerOp = 'mean';
lowerExtentOp = 'ci0';
upperExtentOp = 'ci1';
}
else {
centerOp = 'median';
lowerExtentOp = 'q1';
upperExtentOp = 'q3';
}
errorBarSpecificAggregate = [
{ op: lowerExtentOp, field: continuousFieldName, as: 'lower_' + continuousFieldName },
{ op: upperExtentOp, field: continuousFieldName, as: 'upper_' + continuousFieldName },
{ op: centerOp, field: continuousFieldName, as: 'center_' + continuousFieldName }
];
tooltipSummary = [
{
fieldPrefix: 'upper_',
titlePrefix: channeldef_title({ field: continuousFieldName, aggregate: upperExtentOp, type: 'quantitative' }, config, {
allowDisabling: false
})
},
{
fieldPrefix: 'lower_',
titlePrefix: channeldef_title({ field: continuousFieldName, aggregate: lowerExtentOp, type: 'quantitative' }, config, {
allowDisabling: false
})
},
{
fieldPrefix: 'center_',
titlePrefix: channeldef_title({ field: continuousFieldName, aggregate: centerOp, type: 'quantitative' }, config, {
allowDisabling: false
})
}
];
}
}
else {
if (markDef.center || markDef.extent) {
src_log_warn(log_message.errorBarCenterAndExtentAreNotNeeded(markDef.center, markDef.extent));
}
if (inputType === 'aggregated-upper-lower') {
tooltipSummary = [];
postAggregateCalculates = [
{ calculate: `datum["${continuousAxisChannelDef2.field}"]`, as: 'upper_' + continuousFieldName },
{ calculate: `datum["${continuousFieldName}"]`, as: 'lower_' + continuousFieldName }
];
}
else if (inputType === 'aggregated-error') {
tooltipSummary = [{ fieldPrefix: '', titlePrefix: continuousFieldName }];
postAggregateCalculates = [
{
calculate: `datum["${continuousFieldName}"] + datum["${continuousAxisChannelDefError.field}"]`,
as: 'upper_' + continuousFieldName
}
];
if (continuousAxisChannelDefError2) {
postAggregateCalculates.push({
calculate: `datum["${continuousFieldName}"] + datum["${continuousAxisChannelDefError2.field}"]`,
as: 'lower_' + continuousFieldName
});
}
else {
postAggregateCalculates.push({
calculate: `datum["${continuousFieldName}"] - datum["${continuousAxisChannelDefError.field}"]`,
as: 'lower_' + continuousFieldName
});
}
}
for (const postAggregateCalculate of postAggregateCalculates) {
tooltipSummary.push({
fieldPrefix: postAggregateCalculate.as.substring(0, 6),
titlePrefix: util_replaceAll(util_replaceAll(postAggregateCalculate.calculate, 'datum["', ''), '"]', '')
});
}
}
return { postAggregateCalculates, errorBarSpecificAggregate, tooltipSummary, tooltipTitleWithFieldName };
}
function errorbar_getTitlePrefix(center, extent, operation) {
return util_titlecase(center) + ' ' + operation + ' ' + extent;
}
//# sourceMappingURL=errorbar.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compositemark/errorband.js
const errorband_ERRORBAND = 'errorband';
const errorband_ERRORBAND_PART_INDEX = {
band: 1,
borders: 1
};
const errorband_ERRORBAND_PARTS = util_keys(errorband_ERRORBAND_PART_INDEX);
const errorband_errorBandNormalizer = new base_CompositeMarkNormalizer(errorband_ERRORBAND, errorband_normalizeErrorBand);
function errorband_normalizeErrorBand(spec, { config }) {
const { transform, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, markDef, outerSpec, tooltipEncoding } = errorbar_errorBarParams(spec, errorband_ERRORBAND, config);
const errorBandDef = markDef;
const makeErrorBandPart = common_makeCompositeAggregatePartFactory(errorBandDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorband);
const is2D = spec.encoding.x !== undefined && spec.encoding.y !== undefined;
let bandMark = { type: is2D ? 'area' : 'rect' };
let bordersMark = { type: is2D ? 'line' : 'rule' };
const interpolate = Object.assign(Object.assign({}, (errorBandDef.interpolate ? { interpolate: errorBandDef.interpolate } : {})), (errorBandDef.tension && errorBandDef.interpolate ? { interpolate: errorBandDef.tension } : {}));
if (is2D) {
bandMark = Object.assign(Object.assign({}, bandMark), interpolate);
bordersMark = Object.assign(Object.assign({}, bordersMark), interpolate);
}
else if (errorBandDef.interpolate) {
src_log_warn(log_message.errorBand1DNotSupport('interpolate'));
}
else if (errorBandDef.tension) {
src_log_warn(log_message.errorBand1DNotSupport('tension'));
}
return Object.assign(Object.assign({}, outerSpec), { transform, layer: [
...makeErrorBandPart({
partName: 'band',
mark: bandMark,
positionPrefix: 'lower',
endPositionPrefix: 'upper',
extraEncoding: tooltipEncoding
}),
...makeErrorBandPart({
partName: 'borders',
mark: bordersMark,
positionPrefix: 'lower',
extraEncoding: tooltipEncoding
}),
...makeErrorBandPart({
partName: 'borders',
mark: bordersMark,
positionPrefix: 'upper',
extraEncoding: tooltipEncoding
})
] });
}
//# sourceMappingURL=errorband.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compositemark/index.js
/**
* Registry index for all composite mark's normalizer
*/
const compositemark_compositeMarkRegistry = {};
function compositemark_add(mark, run, parts) {
const normalizer = new base_CompositeMarkNormalizer(mark, run);
compositemark_compositeMarkRegistry[mark] = { normalizer, parts };
}
function compositemark_remove(mark) {
delete compositemark_compositeMarkRegistry[mark];
}
function compositemark_getAllCompositeMarks() {
return util_keys(compositemark_compositeMarkRegistry);
}
compositemark_add(boxplot_BOXPLOT, boxplot_normalizeBoxPlot, boxplot_BOXPLOT_PARTS);
compositemark_add(errorbar_ERRORBAR, errorbar_normalizeErrorBar, errorbar_ERRORBAR_PARTS);
compositemark_add(errorband_ERRORBAND, errorband_normalizeErrorBand, errorband_ERRORBAND_PARTS);
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/guide.js
const VL_ONLY_LEGEND_CONFIG = [
'gradientHorizontalMaxLength',
'gradientHorizontalMinLength',
'gradientVerticalMaxLength',
'gradientVerticalMinLength',
'unselectedOpacity'
];
//# sourceMappingURL=guide.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/legend.js
const legend_defaultLegendConfig = {
gradientHorizontalMaxLength: 200,
gradientHorizontalMinLength: 100,
gradientVerticalMaxLength: 200,
gradientVerticalMinLength: 64,
unselectedOpacity: 0.35
};
const legend_COMMON_LEGEND_PROPERTY_INDEX = {
clipHeight: 1,
columnPadding: 1,
columns: 1,
cornerRadius: 1,
direction: 1,
fillColor: 1,
format: 1,
formatType: 1,
gradientLength: 1,
gradientOpacity: 1,
gradientStrokeColor: 1,
gradientStrokeWidth: 1,
gradientThickness: 1,
gridAlign: 1,
labelAlign: 1,
labelBaseline: 1,
labelColor: 1,
labelFont: 1,
labelFontSize: 1,
labelFontStyle: 1,
labelFontWeight: 1,
labelLimit: 1,
labelOffset: 1,
labelOpacity: 1,
labelOverlap: 1,
labelPadding: 1,
labelSeparation: 1,
legendX: 1,
legendY: 1,
offset: 1,
orient: 1,
padding: 1,
rowPadding: 1,
strokeColor: 1,
symbolDash: 1,
symbolDashOffset: 1,
symbolFillColor: 1,
symbolLimit: 1,
symbolOffset: 1,
symbolOpacity: 1,
symbolSize: 1,
symbolStrokeColor: 1,
symbolStrokeWidth: 1,
symbolType: 1,
tickCount: 1,
tickMinStep: 1,
title: 1,
titleAlign: 1,
titleAnchor: 1,
titleBaseline: 1,
titleColor: 1,
titleFont: 1,
titleFontSize: 1,
titleFontStyle: 1,
titleFontWeight: 1,
titleLimit: 1,
titleLineHeight: 1,
titleOpacity: 1,
titleOrient: 1,
titlePadding: 1,
type: 1,
values: 1,
zindex: 1
};
const legend_LEGEND_PROPERTIES = util_keys(legend_COMMON_LEGEND_PROPERTY_INDEX);
//# sourceMappingURL=legend.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/selection.js
const selection_SELECTION_ID = '_vgsid_';
const selection_defaultConfig = {
single: {
on: 'click',
fields: [selection_SELECTION_ID],
resolve: 'global',
empty: 'all',
clear: 'dblclick'
},
multi: {
on: 'click',
fields: [selection_SELECTION_ID],
toggle: 'event.shiftKey',
resolve: 'global',
empty: 'all',
clear: 'dblclick'
},
interval: {
on: '[mousedown, window:mouseup] > window:mousemove!',
encodings: ['x', 'y'],
translate: '[mousedown, window:mouseup] > window:mousemove!',
zoom: 'wheel!',
mark: { fill: '#333', fillOpacity: 0.125, stroke: 'white' },
resolve: 'global',
clear: 'dblclick'
}
};
function selection_isLegendBinding(bind) {
return !!bind && (bind === 'legend' || !!bind.legend);
}
function selection_isLegendStreamBinding(bind) {
return selection_isLegendBinding(bind) && isObject(bind);
}
//# sourceMappingURL=selection.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/concat.js
function isAnyConcatSpec(spec) {
return isVConcatSpec(spec) || isHConcatSpec(spec) || isConcatSpec(spec);
}
function isConcatSpec(spec) {
return spec['concat'] !== undefined;
}
function isVConcatSpec(spec) {
return spec['vconcat'] !== undefined;
}
function isHConcatSpec(spec) {
return spec['hconcat'] !== undefined;
}
//# sourceMappingURL=concat.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/repeat.js
function isRepeatSpec(spec) {
return spec['repeat'] !== undefined;
}
//# sourceMappingURL=repeat.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/base.js
function base_isStep(size) {
return isObject(size) && size['step'] !== undefined;
}
const base_DEFAULT_SPACING = 20;
const base_COMPOSITION_LAYOUT_INDEX = {
align: 1,
bounds: 1,
center: 1,
columns: 1,
spacing: 1
};
const base_COMPOSITION_LAYOUT_PROPERTIES = util_keys(base_COMPOSITION_LAYOUT_INDEX);
function base_extractCompositionLayout(spec, specType, config) {
var _a, _b;
const compositionConfig = config[specType];
const layout = {};
// Apply config first
const { spacing: spacingConfig, columns } = compositionConfig;
if (spacingConfig !== undefined) {
layout.spacing = spacingConfig;
}
if (columns !== undefined) {
if ((isFacetSpec(spec) && !isFacetMapping(spec.facet)) ||
(isRepeatSpec(spec) && isArray(spec.repeat)) ||
isConcatSpec(spec)) {
layout.columns = columns;
}
}
// Then copy properties from the spec
for (const prop of base_COMPOSITION_LAYOUT_PROPERTIES) {
if (spec[prop] !== undefined) {
if (prop === 'spacing') {
const spacing = spec[prop];
layout[prop] = src_isNumber(spacing)
? spacing
: {
row: (_a = spacing.row, (_a !== null && _a !== void 0 ? _a : spacingConfig)),
column: (_b = spacing.column, (_b !== null && _b !== void 0 ? _b : spacingConfig))
};
}
else {
layout[prop] = spec[prop];
}
}
}
return layout;
}
//# sourceMappingURL=base.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/config.js
function config_getViewConfigContinuousSize(viewConfig, channel) {
var _a;
return _a = viewConfig[channel], (_a !== null && _a !== void 0 ? _a : viewConfig[channel === 'width' ? 'continuousWidth' : 'continuousHeight']); // get width/height for backwards compatibility
}
function config_getViewConfigDiscreteStep(viewConfig, channel) {
const size = config_getViewConfigDiscreteSize(viewConfig, channel);
return base_isStep(size) ? size.step : config_DEFAULT_STEP;
}
function config_getViewConfigDiscreteSize(viewConfig, channel) {
var _a;
const size = (_a = viewConfig[channel], (_a !== null && _a !== void 0 ? _a : viewConfig[channel === 'width' ? 'discreteWidth' : 'discreteHeight'])); // get width/height for backwards compatibility
return util_getFirstDefined(size, { step: viewConfig.step });
}
const config_DEFAULT_STEP = 20;
const config_defaultViewConfig = {
continuousWidth: 200,
continuousHeight: 200,
step: config_DEFAULT_STEP
};
function config_isVgScheme(rangeScheme) {
return rangeScheme && !!rangeScheme['scheme'];
}
const config_defaultConfig = {
background: 'white',
padding: 5,
timeFormat: '%b %d, %Y',
countTitle: 'Count of Records',
view: config_defaultViewConfig,
mark: mark_defaultMarkConfig,
area: {},
bar: mark_defaultBarConfig,
circle: {},
geoshape: {},
image: {},
line: {},
point: {},
rect: mark_defaultRectConfig,
rule: { color: 'black' },
square: {},
text: { color: 'black' },
tick: mark_defaultTickConfig,
trail: {},
boxplot: {
size: 14,
extent: 1.5,
box: {},
median: { color: 'white' },
outliers: {},
rule: {},
ticks: null
},
errorbar: {
center: 'mean',
rule: true,
ticks: false
},
errorband: {
band: {
opacity: 0.3
},
borders: false
},
scale: scale_defaultScaleConfig,
projection: {},
axis: {},
axisX: {},
axisY: {},
axisLeft: {},
axisRight: {},
axisTop: {},
axisBottom: {},
axisBand: {},
legend: legend_defaultLegendConfig,
header: { titlePadding: 10, labelPadding: 10 },
headerColumn: {},
headerRow: {},
headerFacet: {},
selection: selection_defaultConfig,
style: {},
title: {},
facet: { spacing: base_DEFAULT_SPACING },
repeat: { spacing: base_DEFAULT_SPACING },
concat: { spacing: base_DEFAULT_SPACING }
};
function config_initConfig(config) {
return mergeConfig_mergeConfig({}, config_defaultConfig, config);
}
const config_MARK_STYLES = ['view', ...mark_PRIMITIVE_MARKS];
const config_VL_ONLY_CONFIG_PROPERTIES = [
'background',
'padding',
'facet',
'concat',
'repeat',
'numberFormat',
'timeFormat',
'countTitle',
'header',
'scale',
'selection',
'overlay' // FIXME: Redesign and unhide this
];
const config_VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = Object.assign({ view: ['continuousWidth', 'continuousHeight', 'discreteWidth', 'discreteHeight', 'step'] }, mark_VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX);
function config_stripAndRedirectConfig(config) {
config = util_duplicate(config);
for (const prop of config_VL_ONLY_CONFIG_PROPERTIES) {
delete config[prop];
}
if (config.legend) {
for (const prop of VL_ONLY_LEGEND_CONFIG) {
delete config.legend[prop];
}
}
// Remove Vega-Lite only generic mark config
if (config.mark) {
for (const prop of mark_VL_ONLY_MARK_CONFIG_PROPERTIES) {
delete config.mark[prop];
}
}
for (const markType of config_MARK_STYLES) {
// Remove Vega-Lite-only mark config
for (const prop of mark_VL_ONLY_MARK_CONFIG_PROPERTIES) {
delete config[markType][prop];
}
// Remove Vega-Lite only mark-specific config
const vlOnlyMarkSpecificConfigs = config_VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX[markType];
if (vlOnlyMarkSpecificConfigs) {
for (const prop of vlOnlyMarkSpecificConfigs) {
delete config[markType][prop];
}
}
// Redirect mark config to config.style so that mark config only affect its own mark type
// without affecting other marks that share the same underlying Vega marks.
// For example, config.rect should not affect bar marks.
config_redirectConfig(config, markType);
}
for (const m of compositemark_getAllCompositeMarks()) {
// Clean up the composite mark config as we don't need them in the output specs anymore
delete config[m];
}
// Redirect config.title -- so that title config do not
// affect header labels, which also uses `title` directive to implement.
config_redirectConfig(config, 'title', 'group-title');
// Remove empty config objects.
for (const prop in config) {
if (isObject(config[prop]) && util_keys(config[prop]).length === 0) {
delete config[prop];
}
}
return util_keys(config).length > 0 ? config : undefined;
}
function config_redirectConfig(config, prop, // string = composite mark
toProp, compositeMarkPart) {
const propConfig = prop === 'title'
? title_extractTitleConfig(config.title).mark
: compositeMarkPart
? config[prop][compositeMarkPart]
: config[prop];
if (prop === 'view') {
toProp = 'cell'; // View's default style is "cell"
}
const style = Object.assign(Object.assign({}, propConfig), config.style[prop]);
// set config.style if it is not an empty object
if (util_keys(style).length > 0) {
config.style[(toProp !== null && toProp !== void 0 ? toProp : prop)] = style;
}
if (!compositeMarkPart) {
// For composite mark, so don't delete the whole config yet as we have to do multiple redirections.
delete config[prop];
}
}
//# sourceMappingURL=config.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/layer.js
function isLayerSpec(spec) {
return spec['layer'] !== undefined;
}
//# sourceMappingURL=layer.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/index.js
/**
* Definition for specifications in Vega-Lite. In general, there are 3 variants of specs for each type of specs:
* - Generic specs are generic versions of specs and they are parameterized differently for internal and external specs.
* - The external specs (no prefix) would allow composite marks, row/column encodings, and mark macros like point/line overlay.
* - The internal specs (with `Normalized` prefix) would only support primitive marks and support no macros/shortcuts.
*/
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/map.js
class map_SpecMapper {
map(spec, params) {
if (isFacetSpec(spec)) {
return this.mapFacet(spec, params);
}
else if (isRepeatSpec(spec)) {
return this.mapRepeat(spec, params);
}
else if (isHConcatSpec(spec)) {
return this.mapHConcat(spec, params);
}
else if (isVConcatSpec(spec)) {
return this.mapVConcat(spec, params);
}
else if (isConcatSpec(spec)) {
return this.mapConcat(spec, params);
}
else {
return this.mapLayerOrUnit(spec, params);
}
}
mapLayerOrUnit(spec, params) {
if (isLayerSpec(spec)) {
return this.mapLayer(spec, params);
}
else if (isUnitSpec(spec)) {
return this.mapUnit(spec, params);
}
throw new Error(log_message.invalidSpec(spec));
}
mapLayer(spec, params) {
return Object.assign(Object.assign({}, spec), { layer: spec.layer.map(subspec => this.mapLayerOrUnit(subspec, params)) });
}
mapHConcat(spec, params) {
return Object.assign(Object.assign({}, spec), { hconcat: spec.hconcat.map(subspec => this.map(subspec, params)) });
}
mapVConcat(spec, params) {
return Object.assign(Object.assign({}, spec), { vconcat: spec.vconcat.map(subspec => this.map(subspec, params)) });
}
mapConcat(spec, params) {
const { concat } = spec, rest = tslib_es6_rest(spec, ["concat"]);
return Object.assign(Object.assign({}, rest), { concat: concat.map(subspec => this.map(subspec, params)) });
}
mapFacet(spec, params) {
return Object.assign(Object.assign({}, spec), {
// TODO: remove "any" once we support all facet listed in https://github.com/vega/vega-lite/issues/2760
spec: this.map(spec.spec, params) });
}
mapRepeat(spec, params) {
return Object.assign(Object.assign({}, spec), { spec: this.map(spec.spec, params) });
}
}
//# sourceMappingURL=map.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/stack.js
const stack_STACK_OFFSET_INDEX = {
zero: 1,
center: 1,
normalize: 1
};
function stack_isStackOffset(s) {
return !!stack_STACK_OFFSET_INDEX[s];
}
const stack_STACKABLE_MARKS = [mark_BAR, mark_AREA, mark_RULE, mark_POINT, mark_CIRCLE, mark_SQUARE, mark_LINE, mark_TEXT, mark_TICK];
const stack_STACK_BY_DEFAULT_MARKS = [mark_BAR, mark_AREA];
function stack_potentialStackedChannel(encoding) {
const xDef = encoding.x;
const yDef = encoding.y;
if (channeldef_isFieldDef(xDef) && channeldef_isFieldDef(yDef)) {
if (xDef.type === 'quantitative' && yDef.type === 'quantitative') {
if (xDef.stack) {
return 'x';
}
else if (yDef.stack) {
return 'y';
}
// if there is no explicit stacking, only apply stack if there is only one aggregate for x or y
if (!!xDef.aggregate !== !!yDef.aggregate) {
return xDef.aggregate ? 'x' : 'y';
}
}
else if (xDef.type === 'quantitative') {
return 'x';
}
else if (yDef.type === 'quantitative') {
return 'y';
}
}
else if (channeldef_isFieldDef(xDef) && xDef.type === 'quantitative') {
return 'x';
}
else if (channeldef_isFieldDef(yDef) && yDef.type === 'quantitative') {
return 'y';
}
return undefined;
}
// Note: CompassQL uses this method and only passes in required properties of each argument object.
// If required properties change, make sure to update CompassQL.
function stack_stack(m, encoding, opt = {}) {
const mark = mark_isMarkDef(m) ? m.type : m;
// Should have stackable mark
if (!util_contains(stack_STACKABLE_MARKS, mark)) {
return null;
}
const fieldChannel = stack_potentialStackedChannel(encoding);
if (!fieldChannel) {
return null;
}
const stackedFieldDef = encoding[fieldChannel];
const stackedField = channeldef_isStringFieldDef(stackedFieldDef) ? channeldef_vgField(stackedFieldDef, {}) : undefined;
const dimensionChannel = fieldChannel === 'x' ? 'y' : 'x';
const dimensionDef = encoding[dimensionChannel];
const dimensionField = channeldef_isStringFieldDef(dimensionDef) ? channeldef_vgField(dimensionDef, {}) : undefined;
// Should have grouping level of detail that is different from the dimension field
const stackBy = channel_NONPOSITION_CHANNELS.reduce((sc, channel) => {
// Ignore tooltip in stackBy (https://github.com/vega/vega-lite/issues/4001)
if (channel !== 'tooltip' && encoding_channelHasField(encoding, channel)) {
const channelDef = encoding[channel];
(isArray(channelDef) ? channelDef : [channelDef]).forEach(cDef => {
const fieldDef = channeldef_getTypedFieldDef(cDef);
if (fieldDef.aggregate) {
return;
}
// Check whether the channel's field is identical to x/y's field or if the channel is a repeat
const f = channeldef_isStringFieldDef(fieldDef) ? channeldef_vgField(fieldDef, {}) : undefined;
if (
// if fielddef is a repeat, just include it in the stack by
!f ||
// otherwise, the field must be different from x and y fields.
(f !== dimensionField && f !== stackedField)) {
sc.push({ channel, fieldDef });
}
});
}
return sc;
}, []);
// Automatically determine offset
let offset;
if (stackedFieldDef.stack !== undefined) {
if (src_isBoolean(stackedFieldDef.stack)) {
offset = stackedFieldDef.stack ? 'zero' : null;
}
else {
offset = stackedFieldDef.stack;
}
}
else if (stackBy.length > 0 && util_contains(stack_STACK_BY_DEFAULT_MARKS, mark)) {
// Bar and Area with sum ops are automatically stacked by default
offset = 'zero';
}
if (!offset || !stack_isStackOffset(offset)) {
return null;
}
if (encoding_isAggregate(encoding) && stackBy.length === 0) {
return null;
}
// warn when stacking non-linear
if (stackedFieldDef.scale && stackedFieldDef.scale.type && stackedFieldDef.scale.type !== scale_ScaleType.LINEAR) {
if (opt.disallowNonLinearStack) {
return null;
}
else {
src_log_warn(log_message.cannotStackNonLinearScale(stackedFieldDef.scale.type));
}
}
// Check if it is a ranged mark
if (encoding_channelHasField(encoding, fieldChannel === channel_X ? channel_X2 : channel_Y2)) {
if (stackedFieldDef.stack !== undefined) {
src_log_warn(log_message.cannotStackRangedMark(fieldChannel));
}
return null;
}
// Warn if stacking non-summative aggregate
if (stackedFieldDef.aggregate && !util_contains(aggregate_SUM_OPS, stackedFieldDef.aggregate)) {
src_log_warn(log_message.stackNonSummativeAggregate(stackedFieldDef.aggregate));
}
return {
groupbyChannel: dimensionDef ? dimensionChannel : undefined,
fieldChannel,
impute: stackedFieldDef.impute === null ? false : mark_isPathMark(mark),
stackBy,
offset
};
}
//# sourceMappingURL=stack.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/normalize/pathoverlay.js
function pathoverlay_dropLineAndPoint(markDef) {
const { point: _point, line: _line } = markDef, mark = tslib_es6_rest(markDef, ["point", "line"]);
return util_keys(mark).length > 1 ? mark : mark.type;
}
function pathoverlay_dropLineAndPointFromConfig(config) {
for (const mark of ['line', 'area', 'rule', 'trail']) {
if (config[mark]) {
config = Object.assign(Object.assign({}, config), {
// TODO: remove as any
[mark]: util_omit(config[mark], ['point', 'line']) });
}
}
return config;
}
function pathoverlay_getPointOverlay(markDef, markConfig = {}, encoding) {
if (markDef.point === 'transparent') {
return { opacity: 0 };
}
else if (markDef.point) {
// truthy : true or object
return isObject(markDef.point) ? markDef.point : {};
}
else if (markDef.point !== undefined) {
// false or null
return null;
}
else {
// undefined (not disabled)
if (markConfig.point || encoding.shape) {
// enable point overlay if config[mark].point is truthy or if encoding.shape is provided
return isObject(markConfig.point) ? markConfig.point : {};
}
// markDef.point is defined as falsy
return undefined;
}
}
function pathoverlay_getLineOverlay(markDef, markConfig = {}) {
if (markDef.line) {
// true or object
return markDef.line === true ? {} : markDef.line;
}
else if (markDef.line !== undefined) {
// false or null
return null;
}
else {
// undefined (not disabled)
if (markConfig.line) {
// enable line overlay if config[mark].line is truthy
return markConfig.line === true ? {} : markConfig.line;
}
// markDef.point is defined as falsy
return undefined;
}
}
class pathoverlay_PathOverlayNormalizer {
constructor() {
this.name = 'path-overlay';
}
hasMatchingType(spec, config) {
if (isUnitSpec(spec)) {
const { mark, encoding } = spec;
const markDef = mark_isMarkDef(mark) ? mark : { type: mark };
switch (markDef.type) {
case 'line':
case 'rule':
case 'trail':
return !!pathoverlay_getPointOverlay(markDef, config[markDef.type], encoding);
case 'area':
return (
// false / null are also included as we want to remove the properties
!!pathoverlay_getPointOverlay(markDef, config[markDef.type], encoding) ||
!!pathoverlay_getLineOverlay(markDef, config[markDef.type]));
}
}
return false;
}
run(spec, params, normalize) {
const { config } = params;
const { selection, projection, encoding, mark } = spec, outerSpec = tslib_es6_rest(spec, ["selection", "projection", "encoding", "mark"]);
const markDef = mark_isMarkDef(mark) ? mark : { type: mark };
const pointOverlay = pathoverlay_getPointOverlay(markDef, config[markDef.type], encoding);
const lineOverlay = markDef.type === 'area' && pathoverlay_getLineOverlay(markDef, config[markDef.type]);
const layer = [
Object.assign(Object.assign({}, (selection ? { selection } : {})), {
// Do not include point / line overlay in the normalize spec
mark: pathoverlay_dropLineAndPoint(Object.assign(Object.assign({}, markDef), (markDef.type === 'area' ? { opacity: 0.7 } : {}))),
// drop shape from encoding as this might be used to trigger point overlay
encoding: util_omit(encoding, ['shape']) })
];
// FIXME: determine rules for applying selections.
// Need to copy stack config to overlayed layer
const stackProps = stack_stack(markDef, encoding);
let overlayEncoding = encoding;
if (stackProps) {
const { fieldChannel: stackFieldChannel, offset } = stackProps;
overlayEncoding = Object.assign(Object.assign({}, encoding), { [stackFieldChannel]: Object.assign(Object.assign({}, encoding[stackFieldChannel]), (offset ? { stack: offset } : {})) });
}
if (lineOverlay) {
layer.push(Object.assign(Object.assign({}, (projection ? { projection } : {})), { mark: Object.assign(Object.assign({ type: 'line' }, util_pick(markDef, ['clip', 'interpolate', 'tension', 'tooltip'])), lineOverlay), encoding: overlayEncoding }));
}
if (pointOverlay) {
layer.push(Object.assign(Object.assign({}, (projection ? { projection } : {})), { mark: Object.assign(Object.assign({ type: 'point', opacity: 1, filled: true }, util_pick(markDef, ['clip', 'tooltip'])), pointOverlay), encoding: overlayEncoding }));
}
return normalize(Object.assign(Object.assign({}, outerSpec), { layer }), Object.assign(Object.assign({}, params), { config: pathoverlay_dropLineAndPointFromConfig(config) }));
}
}
//# sourceMappingURL=pathoverlay.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/normalize/rangestep.js
class rangestep_RangeStepNormalizer {
constructor() {
this.name = 'RangeStep';
}
hasMatchingType(spec) {
var _a, _b;
if (isUnitSpec(spec) && spec.encoding) {
for (const channel of channel_POSITION_SCALE_CHANNELS) {
const def = spec.encoding[channel];
if (def && channeldef_isFieldDef(def)) {
if ((_b = (_a = def) === null || _a === void 0 ? void 0 : _a.scale) === null || _b === void 0 ? void 0 : _b['rangeStep']) {
return true;
}
}
}
}
return false;
}
run(spec) {
var _a, _b;
const sizeMixins = {};
let encoding = Object.assign({}, spec.encoding);
for (const channel of channel_POSITION_SCALE_CHANNELS) {
const sizeType = channel_getSizeType(channel);
const def = encoding[channel];
if (def && channeldef_isFieldDef(def)) {
if ((_b = (_a = def) === null || _a === void 0 ? void 0 : _a.scale) === null || _b === void 0 ? void 0 : _b['rangeStep']) {
const { scale } = def, defWithoutScale = tslib_es6_rest(def, ["scale"]);
const _c = scale, { rangeStep } = _c, scaleWithoutRangeStep = tslib_es6_rest(_c, ["rangeStep"]);
sizeMixins[sizeType] = { step: scale['rangeStep'] };
src_log_warn(log_message.RANGE_STEP_DEPRECATED);
encoding = Object.assign(Object.assign({}, encoding), { [channel]: Object.assign(Object.assign({}, defWithoutScale), (util_keys(scaleWithoutRangeStep).length > 0 ? { scale: scaleWithoutRangeStep } : {})) });
}
}
}
return Object.assign(Object.assign(Object.assign({}, sizeMixins), spec), { encoding });
}
}
//# sourceMappingURL=rangestep.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/normalize/ruleforrangedline.js
class ruleforrangedline_RuleForRangedLineNormalizer {
constructor() {
this.name = 'RuleForRangedLine';
}
hasMatchingType(spec) {
if (isUnitSpec(spec)) {
const { encoding, mark } = spec;
if (mark === 'line') {
for (const channel of channel_SECONDARY_RANGE_CHANNEL) {
const mainChannel = channel_getMainRangeChannel(channel);
const mainChannelDef = encoding[mainChannel];
if (!!encoding[channel] && channeldef_isFieldDef(mainChannelDef) && !bin_isBinned(mainChannelDef.bin)) {
return true;
}
}
}
}
return false;
}
run(spec, params, normalize) {
const { encoding } = spec;
src_log_warn(log_message.lineWithRange(!!encoding.x2, !!encoding.y2));
return normalize(Object.assign(Object.assign({}, spec), { mark: 'rule' }), params);
}
}
//# sourceMappingURL=ruleforrangedline.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/normalize/core.js
class core_CoreNormalizer extends map_SpecMapper {
constructor() {
super(...arguments);
this.nonFacetUnitNormalizers = [
boxplot_boxPlotNormalizer,
errorbar_errorBarNormalizer,
errorband_errorBandNormalizer,
new pathoverlay_PathOverlayNormalizer(),
new ruleforrangedline_RuleForRangedLineNormalizer(),
new rangestep_RangeStepNormalizer()
];
}
map(spec, params) {
// Special handling for a faceted unit spec as it can return a facet spec, not just a layer or unit spec like a normal unit spec.
if (isUnitSpec(spec)) {
const hasRow = encoding_channelHasField(spec.encoding, channel_ROW);
const hasColumn = encoding_channelHasField(spec.encoding, channel_COLUMN);
const hasFacet = encoding_channelHasField(spec.encoding, channel_FACET);
if (hasRow || hasColumn || hasFacet) {
return this.mapFacetedUnit(spec, params);
}
}
return super.map(spec, params);
}
// This is for normalizing non-facet unit
mapUnit(spec, params) {
const { parentEncoding, parentProjection } = params;
if (parentEncoding || parentProjection) {
return this.mapUnitWithParentEncodingOrProjection(spec, params);
}
const normalizeLayerOrUnit = this.mapLayerOrUnit.bind(this);
for (const unitNormalizer of this.nonFacetUnitNormalizers) {
if (unitNormalizer.hasMatchingType(spec, params.config)) {
return unitNormalizer.run(spec, params, normalizeLayerOrUnit);
}
}
return spec;
}
mapRepeat(spec, params) {
const { repeat } = spec;
if (!isArray(repeat) && spec.columns) {
// is repeat with row/column
spec = util_omit(spec, ['columns']);
src_log_warn(log_message.columnsNotSupportByRowCol('repeat'));
}
return Object.assign(Object.assign({}, spec), { spec: this.map(spec.spec, params) });
}
mapFacet(spec, params) {
const { facet } = spec;
if (isFacetMapping(facet) && spec.columns) {
// is facet with row/column
spec = util_omit(spec, ['columns']);
src_log_warn(log_message.columnsNotSupportByRowCol('facet'));
}
return super.mapFacet(spec, params);
}
mapUnitWithParentEncodingOrProjection(spec, params) {
const { encoding, projection } = spec;
const { parentEncoding, parentProjection, config } = params;
const mergedProjection = core_mergeProjection({ parentProjection, projection });
const mergedEncoding = core_mergeEncoding({ parentEncoding, encoding });
return this.mapUnit(Object.assign(Object.assign(Object.assign({}, spec), (mergedProjection ? { projection: mergedProjection } : {})), (mergedEncoding ? { encoding: mergedEncoding } : {})), { config });
}
mapFacetedUnit(spec, params) {
// New encoding in the inside spec should not contain row / column
// as row/column should be moved to facet
const _a = spec.encoding, { row, column, facet } = _a, encoding = tslib_es6_rest(_a, ["row", "column", "facet"]);
// Mark and encoding should be moved into the inner spec
const { mark, width, projection, height, selection, encoding: _ } = spec, outerSpec = tslib_es6_rest(spec, ["mark", "width", "projection", "height", "selection", "encoding"]);
const { facetMapping, layout } = this.getFacetMappingAndLayout({ row, column, facet });
return this.mapFacet(Object.assign(Object.assign(Object.assign({}, outerSpec), layout), {
// row / column has higher precedence than facet
facet: facetMapping, spec: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (projection ? { projection } : {})), { mark }), (width ? { width } : {})), (height ? { height } : {})), { encoding }), (selection ? { selection } : {})) }), params);
}
getFacetMappingAndLayout(facets) {
var _a;
const { row, column, facet } = facets;
if (row || column) {
if (facet) {
src_log_warn(log_message.facetChannelDropped([...(row ? [channel_ROW] : []), ...(column ? [channel_COLUMN] : [])]));
}
const facetMapping = {};
const layout = {};
for (const channel of [channel_ROW, channel_COLUMN]) {
const def = facets[channel];
if (def) {
const { align, center, spacing, columns } = def, defWithoutLayout = tslib_es6_rest(def, ["align", "center", "spacing", "columns"]);
facetMapping[channel] = defWithoutLayout;
for (const prop of ['align', 'center', 'spacing']) {
if (def[prop] !== undefined) {
layout[prop] = (_a = layout[prop], (_a !== null && _a !== void 0 ? _a : {}));
layout[prop][channel] = def[prop];
}
}
}
}
return { facetMapping, layout };
}
else {
const { align, center, spacing, columns } = facet, facetMapping = tslib_es6_rest(facet, ["align", "center", "spacing", "columns"]);
return {
facetMapping,
layout: Object.assign(Object.assign(Object.assign(Object.assign({}, (align ? { align } : {})), (center ? { center } : {})), (spacing ? { spacing } : {})), (columns ? { columns } : {}))
};
}
}
mapLayer(spec, _a) {
// Special handling for extended layer spec
var { parentEncoding, parentProjection } = _a, otherParams = tslib_es6_rest(_a, ["parentEncoding", "parentProjection"]);
const { encoding, projection } = spec, rest = tslib_es6_rest(spec, ["encoding", "projection"]);
const params = Object.assign(Object.assign({}, otherParams), { parentEncoding: core_mergeEncoding({ parentEncoding, encoding }), parentProjection: core_mergeProjection({ parentProjection, projection }) });
return super.mapLayer(rest, params);
}
}
function core_mergeEncoding(opt) {
const { parentEncoding, encoding } = opt;
if (parentEncoding && encoding) {
const overriden = util_keys(parentEncoding).reduce((o, key) => {
if (encoding[key]) {
o.push(key);
}
return o;
}, []);
if (overriden.length > 0) {
src_log_warn(log_message.encodingOverridden(overriden));
}
}
const merged = Object.assign(Object.assign({}, ((parentEncoding !== null && parentEncoding !== void 0 ? parentEncoding : {}))), ((encoding !== null && encoding !== void 0 ? encoding : {})));
return util_keys(merged).length > 0 ? merged : undefined;
}
function core_mergeProjection(opt) {
const { parentProjection, projection } = opt;
if (parentProjection && projection) {
src_log_warn(log_message.projectionOverridden({ parentProjection, projection }));
}
return (projection !== null && projection !== void 0 ? projection : parentProjection);
}
//# sourceMappingURL=core.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/normalize/index.js
function normalize_normalize(spec, config) {
if (config === undefined) {
config = config_initConfig(spec.config);
}
const normalizedSpec = normalize_normalizeGenericSpec(spec, config);
const { width, height } = spec;
const autosize = src_normalize_normalizeAutoSize(normalizedSpec, { width, height, autosize: spec.autosize }, config);
return Object.assign(Object.assign({}, normalizedSpec), (autosize ? { autosize } : {}));
}
const normalize_normalizer = new core_CoreNormalizer();
/**
* Decompose extended unit specs into composition of pure unit specs.
*/
function normalize_normalizeGenericSpec(spec, config = {}) {
return normalize_normalizer.map(spec, { config });
}
function normalize_normalizeAutoSize(autosize) {
return isString(autosize) ? { type: autosize } : (autosize !== null && autosize !== void 0 ? autosize : {});
}
/**
* Normalize autosize and deal with width or height == "container".
*/
function src_normalize_normalizeAutoSize(spec, sizeInfo, config) {
let { width, height } = sizeInfo;
const isFitCompatible = isUnitSpec(spec) || isLayerSpec(spec);
const autosizeDefault = {};
if (!isFitCompatible) {
// If spec is not compatible with autosize == "fit", discard width/height == container
if (width == 'container') {
src_log_warn(log_message.containerSizeNonSingle('width'));
width = undefined;
}
if (height == 'container') {
src_log_warn(log_message.containerSizeNonSingle('height'));
height = undefined;
}
}
else {
// Default autosize parameters to fit when width/height is "container"
if (width == 'container' && height == 'container') {
autosizeDefault.type = 'fit';
autosizeDefault.contains = 'padding';
}
else if (width == 'container') {
autosizeDefault.type = 'fit-x';
autosizeDefault.contains = 'padding';
}
else if (height == 'container') {
autosizeDefault.type = 'fit-y';
autosizeDefault.contains = 'padding';
}
}
const autosize = Object.assign(Object.assign(Object.assign({ type: 'pad' }, autosizeDefault), (config ? normalize_normalizeAutoSize(config.autosize) : {})), normalize_normalizeAutoSize(spec.autosize));
if (autosize.type === 'fit' && !isFitCompatible) {
src_log_warn(log_message.FIT_NON_SINGLE);
autosize.type = 'pad';
}
if (width == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-x')) {
src_log_warn(log_message.containerSizeNotCompatibleWithAutosize('width'));
}
if (height == 'container' && !(autosize.type == 'fit' || autosize.type == 'fit-y')) {
src_log_warn(log_message.containerSizeNotCompatibleWithAutosize('height'));
}
// Delete autosize property if it's Vega's default
if (util_deepEqual(autosize, { type: 'pad' })) {
return undefined;
}
return autosize;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/spec/toplevel.js
function toplevel_isFitType(autoSizeType) {
return autoSizeType === 'fit' || autoSizeType === 'fit-x' || autoSizeType === 'fit-y';
}
function toplevel_getFitType(sizeType) {
return sizeType ? `fit-${channel_getPositionScaleChannel(sizeType)}` : 'fit';
}
const toplevel_TOP_LEVEL_PROPERTIES = [
'background',
'padding'
// We do not include "autosize" here as it is supported by only unit and layer specs and thus need to be normalized
];
function toplevel_extractTopLevelProperties(t) {
return toplevel_TOP_LEVEL_PROPERTIES.reduce((o, p) => {
if (t && t[p] !== undefined) {
o[p] = t[p];
}
return o;
}, {});
}
//# sourceMappingURL=toplevel.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/data.js
function isUrlData(data) {
return !!data['url'];
}
function isInlineData(data) {
return !!data['values'];
}
function isNamedData(data) {
return !!data['name'] && !isUrlData(data) && !isInlineData(data) && !isGenerator(data);
}
function isGenerator(data) {
return data && (isSequenceGenerator(data) || isSphereGenerator(data) || isGraticuleGenerator(data));
}
function isSequenceGenerator(data) {
return !!data['sequence'];
}
function isSphereGenerator(data) {
return !!data['sphere'];
}
function isGraticuleGenerator(data) {
return !!data['graticule'];
}
const MAIN = 'main';
const RAW = 'raw';
//# sourceMappingURL=data.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/transform.js
function transform_isFilter(t) {
return t['filter'] !== undefined;
}
function transform_isImputeSequence(t) {
var _a;
return ((_a = t) === null || _a === void 0 ? void 0 : _a['stop']) !== undefined;
}
function transform_isLookup(t) {
return t['lookup'] !== undefined;
}
function transform_isLookupData(from) {
return from['data'] !== undefined;
}
function transform_isLookupSelection(from) {
return from['selection'] !== undefined;
}
function transform_isPivot(t) {
return t['pivot'] !== undefined;
}
function transform_isDensity(t) {
return t['density'] !== undefined;
}
function transform_isQuantile(t) {
return t['quantile'] !== undefined;
}
function transform_isRegression(t) {
return t['regression'] !== undefined;
}
function transform_isLoess(t) {
return t['loess'] !== undefined;
}
function transform_isSample(t) {
return t['sample'] !== undefined;
}
function transform_isWindow(t) {
return t['window'] !== undefined;
}
function transform_isJoinAggregate(t) {
return t['joinaggregate'] !== undefined;
}
function transform_isFlatten(t) {
return t['flatten'] !== undefined;
}
function transform_isCalculate(t) {
return t['calculate'] !== undefined;
}
function transform_isBin(t) {
return !!t['bin'];
}
function transform_isImpute(t) {
return t['impute'] !== undefined;
}
function transform_isTimeUnit(t) {
return t['timeUnit'] !== undefined;
}
function transform_isAggregate(t) {
return t['aggregate'] !== undefined;
}
function transform_isStack(t) {
return t['stack'] !== undefined;
}
function transform_isFold(t) {
return t['fold'] !== undefined;
}
function transform_normalizeTransform(transform) {
return transform.map(t => {
if (transform_isFilter(t)) {
return {
filter: normalizeLogicalOperand(t.filter, predicate_normalizePredicate)
};
}
return t;
});
}
//# sourceMappingURL=transform.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/vega.schema.js
function vega_schema_isSignalRef(o) {
return !!o['signal'];
}
function vega_schema_isVgRangeStep(range) {
return !!range['step'];
}
function vega_schema_isDataRefUnionedDomain(domain) {
if (!isArray(domain)) {
return 'fields' in domain && !('data' in domain);
}
return false;
}
function vega_schema_isFieldRefUnionDomain(domain) {
if (!isArray(domain)) {
return 'fields' in domain && 'data' in domain;
}
return false;
}
function vega_schema_isDataRefDomain(domain) {
if (!isArray(domain)) {
return 'field' in domain && 'data' in domain;
}
return false;
}
const vega_schema_VG_MARK_CONFIG_INDEX = {
opacity: 1,
fill: 1,
fillOpacity: 1,
stroke: 1,
strokeCap: 1,
strokeWidth: 1,
strokeOpacity: 1,
strokeDash: 1,
strokeDashOffset: 1,
strokeJoin: 1,
strokeMiterLimit: 1,
size: 1,
shape: 1,
interpolate: 1,
tension: 1,
orient: 1,
align: 1,
baseline: 1,
text: 1,
dir: 1,
dx: 1,
dy: 1,
ellipsis: 1,
limit: 1,
radius: 1,
theta: 1,
angle: 1,
font: 1,
fontSize: 1,
fontWeight: 1,
fontStyle: 1,
lineBreak: 1,
lineHeight: 1,
cursor: 1,
href: 1,
tooltip: 1,
cornerRadius: 1,
cornerRadiusTopLeft: 1,
cornerRadiusTopRight: 1,
cornerRadiusBottomLeft: 1,
cornerRadiusBottomRight: 1,
x: 1,
y: 1,
x2: 1,
y2: 1,
width: 1,
height: 1,
aspect: 1
// commented below are vg channel that do not have mark config.
// xc'|'yc'
// clip: 1,
// endAngle: 1,
// innerRadius: 1,
// outerRadius: 1,
// path: 1,
// startAngle: 1,
// url: 1,
};
const vega_schema_VG_MARK_CONFIGS = util_keys(vega_schema_VG_MARK_CONFIG_INDEX);
// Vega's cornerRadius channels.
const vega_schema_VG_CORNERRADIUS_CHANNELS = [
'cornerRadius',
'cornerRadiusTopLeft',
'cornerRadiusTopRight',
'cornerRadiusBottomLeft',
'cornerRadiusBottomRight'
];
//# sourceMappingURL=vega.schema.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/axis.js
const axis_CONDITIONAL_AXIS_PROP_INDEX = {
labelAlign: {
part: 'labels',
vgProp: 'align'
},
labelBaseline: {
part: 'labels',
vgProp: 'baseline'
},
labelColor: {
part: 'labels',
vgProp: 'fill'
},
labelFont: {
part: 'labels',
vgProp: 'font'
},
labelFontSize: {
part: 'labels',
vgProp: 'fontSize'
},
labelFontStyle: {
part: 'labels',
vgProp: 'fontStyle'
},
labelFontWeight: {
part: 'labels',
vgProp: 'fontWeight'
},
labelOpacity: {
part: 'labels',
vgProp: 'opacity'
},
gridColor: {
part: 'grid',
vgProp: 'stroke'
},
gridDash: {
part: 'grid',
vgProp: 'strokeDash'
},
gridDashOffset: {
part: 'grid',
vgProp: 'strokeDash'
},
gridOpacity: {
part: 'grid',
vgProp: 'opacity'
},
gridWidth: {
part: 'grid',
vgProp: 'strokeWidth'
},
tickColor: {
part: 'ticks',
vgProp: 'stroke'
},
tickDash: {
part: 'ticks',
vgProp: 'strokeDash'
},
tickDashOffset: {
part: 'ticks',
vgProp: 'strokeDash'
},
tickOpacity: {
part: 'ticks',
vgProp: 'opacity'
},
tickWidth: {
part: 'ticks',
vgProp: 'strokeWidth'
}
};
function axis_isConditionalAxisValue(v) {
return v['condition'];
}
const axis_AXIS_PARTS = ['domain', 'grid', 'labels', 'ticks', 'title'];
/**
* A dictionary listing whether a certain axis property is applicable for only main axes or only grid axes.
* (Properties not listed are applicable for both)
*/
const axis_AXIS_PROPERTY_TYPE = {
grid: 'grid',
gridColor: 'grid',
gridDash: 'grid',
gridOpacity: 'grid',
gridScale: 'grid',
gridWidth: 'grid',
orient: 'main',
bandPosition: 'both',
domain: 'main',
domainColor: 'main',
domainOpacity: 'main',
domainWidth: 'main',
format: 'main',
formatType: 'main',
labelAlign: 'main',
labelAngle: 'main',
labelBaseline: 'main',
labelBound: 'main',
labelColor: 'main',
labelFlush: 'main',
labelFlushOffset: 'main',
labelFont: 'main',
labelFontSize: 'main',
labelFontWeight: 'main',
labelLimit: 'main',
labelOpacity: 'main',
labelOverlap: 'main',
labelPadding: 'main',
labels: 'main',
maxExtent: 'main',
minExtent: 'main',
offset: 'main',
position: 'main',
tickColor: 'main',
tickExtra: 'main',
tickOffset: 'both',
tickOpacity: 'main',
tickRound: 'main',
ticks: 'main',
tickSize: 'main',
title: 'main',
titleAlign: 'main',
titleAngle: 'main',
titleBaseline: 'main',
titleColor: 'main',
titleFont: 'main',
titleFontSize: 'main',
titleFontWeight: 'main',
titleLimit: 'main',
titleLineHeight: 'main',
titleOpacity: 'main',
titlePadding: 'main',
titleX: 'main',
titleY: 'main',
tickWidth: 'both',
tickCount: 'both',
values: 'both',
scale: 'both',
zindex: 'both' // this is actually set afterward, so it doesn't matter
};
const axis_COMMON_AXIS_PROPERTIES_INDEX = {
orient: 1,
bandPosition: 1,
domain: 1,
domainColor: 1,
domainDash: 1,
domainDashOffset: 1,
domainOpacity: 1,
domainWidth: 1,
format: 1,
formatType: 1,
grid: 1,
gridColor: 1,
gridDash: 1,
gridDashOffset: 1,
gridOpacity: 1,
gridWidth: 1,
labelAlign: 1,
labelAngle: 1,
labelBaseline: 1,
labelBound: 1,
labelColor: 1,
labelFlush: 1,
labelFlushOffset: 1,
labelFont: 1,
labelFontSize: 1,
labelFontStyle: 1,
labelFontWeight: 1,
labelLimit: 1,
labelOpacity: 1,
labelOverlap: 1,
labelPadding: 1,
labels: 1,
labelSeparation: 1,
maxExtent: 1,
minExtent: 1,
offset: 1,
position: 1,
tickBand: 1,
tickColor: 1,
tickCount: 1,
tickDash: 1,
tickDashOffset: 1,
tickExtra: 1,
tickMinStep: 1,
tickOffset: 1,
tickOpacity: 1,
tickRound: 1,
ticks: 1,
tickSize: 1,
tickWidth: 1,
title: 1,
titleAlign: 1,
titleAnchor: 1,
titleAngle: 1,
titleBaseline: 1,
titleColor: 1,
titleFont: 1,
titleFontSize: 1,
titleFontStyle: 1,
titleFontWeight: 1,
titleLimit: 1,
titleLineHeight: 1,
titleOpacity: 1,
titlePadding: 1,
titleX: 1,
titleY: 1,
values: 1,
translate: 1,
zindex: 1
};
const axis_AXIS_PROPERTIES_INDEX = Object.assign(Object.assign({}, axis_COMMON_AXIS_PROPERTIES_INDEX), { labelExpr: 1, encoding: 1 });
function axis_isAxisProperty(prop) {
return !!axis_AXIS_PROPERTIES_INDEX[prop];
}
// Export for dependent projects
const axis_AXIS_PROPERTIES = util_keys(axis_AXIS_PROPERTIES_INDEX);
//# sourceMappingURL=axis.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/conditional.js
/**
* Return a mixin that includes a Vega production rule for a Vega-Lite conditional channel definition.
* or a simple mixin if channel def has no condition.
*/
function conditional_wrapCondition(model, channelDef, vgChannel, refFn) {
const condition = channelDef && channelDef.condition;
const valueRef = refFn(channelDef);
if (condition) {
const conditions = vega_util_src_array(condition);
const vgConditions = conditions.map(c => {
const conditionValueRef = refFn(c);
const test = channeldef_isConditionalSelection(c) ? parse_parseSelectionPredicate(model, c.selection) : predicate_expression(model, c.test);
return Object.assign({ test }, conditionValueRef);
});
return {
[vgChannel]: [...vgConditions, ...(valueRef !== undefined ? [valueRef] : [])]
};
}
else {
return valueRef !== undefined ? { [vgChannel]: valueRef } : {};
}
}
//# sourceMappingURL=conditional.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/valueref.js
/**
* Utility files for producing Vega ValueRef for marks
*/
function valueref_midPointRefWithPositionInvalidTest(params) {
const { channel, channelDef, markDef, scale } = params;
const ref = valueref_midPoint(params);
// Wrap to check if the positional value is invalid, if so, plot the point on the min value
if (
// Only this for field def without counting aggregate (as count wouldn't be null)
channeldef_isFieldDef(channelDef) &&
!aggregate_isCountingAggregateOp(channelDef.aggregate) &&
// and only for continuous scale without zero (otherwise, null / invalid will be interpreted as zero, which doesn't cause layout problem)
scale &&
scale_isContinuousToContinuous(scale.get('type')) &&
scale.get('zero') === false) {
return valueref_wrapPositionInvalidTest({
fieldDef: channelDef,
channel,
markDef,
ref
});
}
return ref;
}
function valueref_wrapPositionInvalidTest({ fieldDef, channel, markDef, ref }) {
if (!mark_isPathMark(markDef.type)) {
// Only do this for non-path mark (as path marks will already use "defined" to skip points)
return [valueref_fieldInvalidTestValueRef(fieldDef, channel), ref];
}
return ref;
}
function valueref_fieldInvalidTestValueRef(fieldDef, channel) {
const test = valueref_fieldInvalidPredicate(fieldDef, true);
const mainChannel = channel_getMainRangeChannel(channel);
const zeroValueRef = mainChannel === 'x' ? { value: 0 } : { field: { group: 'height' } };
return Object.assign({ test }, zeroValueRef);
}
function valueref_fieldInvalidPredicate(field, invalid = true) {
return predicate_fieldValidPredicate(isString(field) ? field : channeldef_vgField(field, { expr: 'datum' }), !invalid);
}
function valueref_fieldRef(fieldDef, scaleName, opt, encode) {
const ref = Object.assign(Object.assign({}, (scaleName ? { scale: scaleName } : {})), { field: channeldef_vgField(fieldDef, opt) });
if (encode) {
const { offset, band } = encode;
return Object.assign(Object.assign(Object.assign({}, ref), (offset ? { offset } : {})), (band ? { band } : {}));
}
return ref;
}
/**
* Signal that returns the middle of a bin from start and end field. Should only be used with x and y.
*/
function valueref_interpolatedSignalRef({ scaleName, fieldDef, fieldDef2, offset, startSuffix, band = 0.5 }) {
const expr = 0 < band && band < 1 ? 'datum' : undefined;
const start = channeldef_vgField(fieldDef, { expr, suffix: startSuffix });
const end = fieldDef2 !== undefined ? channeldef_vgField(fieldDef2, { expr }) : channeldef_vgField(fieldDef, { suffix: 'end', expr });
if (band === 0) {
return Object.assign({ scale: scaleName, field: start }, (offset ? { offset } : {}));
}
else if (band === 1) {
return Object.assign({ scale: scaleName, field: end }, (offset ? { offset } : {}));
}
else {
const datum = `${band} * ${start} + ${1 - band} * ${end}`;
return Object.assign({ signal: `scale("${scaleName}", ${datum})` }, (offset ? { offset } : {}));
}
}
/**
* @returns {VgValueRef} Value Ref for xc / yc or mid point for other channels.
*/
function valueref_midPoint({ channel, channelDef, channel2Def, markDef, config, scaleName, scale, stack, offset, defaultRef }) {
// TODO: datum support
if (channelDef) {
/* istanbul ignore else */
if (channeldef_isFieldDef(channelDef)) {
if (channeldef_isTypedFieldDef(channelDef)) {
const band = channeldef_getBand(channel, channelDef, channel2Def, markDef, config, { isMidPoint: true });
if (bin_isBinning(channelDef.bin) || (band && channelDef.timeUnit)) {
// Use middle only for x an y to place marks in the center between start and end of the bin range.
// We do not use the mid point for other channels (e.g. size) so that properties of legends and marks match.
if (util_contains([channel_X, channel_Y], channel) && util_contains([QUANTITATIVE, TEMPORAL], channelDef.type)) {
if (stack && stack.impute) {
// For stack, we computed bin_mid so we can impute.
return valueref_fieldRef(channelDef, scaleName, { binSuffix: 'mid' }, { offset });
}
// For non-stack, we can just calculate bin mid on the fly using signal.
return valueref_interpolatedSignalRef({ scaleName, fieldDef: channelDef, band, offset });
}
return valueref_fieldRef(channelDef, scaleName, channeldef_binRequiresRange(channelDef, channel) ? { binSuffix: 'range' } : {}, {
offset
});
}
else if (bin_isBinned(channelDef.bin)) {
if (channeldef_isFieldDef(channel2Def)) {
return valueref_interpolatedSignalRef({ scaleName, fieldDef: channelDef, fieldDef2: channel2Def, band, offset });
}
else {
const channel2 = channel === channel_X ? channel_X2 : channel_Y2;
src_log_warn(log_message.channelRequiredForBinned(channel2));
}
}
}
if (scale) {
const scaleType = scale.get('type');
if (scale_hasDiscreteDomain(scaleType)) {
if (scaleType === 'band') {
// For band, to get mid point, need to offset by half of the band
const band = util_getFirstDefined(channeldef_isPositionFieldDef(channelDef) ? channelDef.band : undefined, 0.5);
return valueref_fieldRef(channelDef, scaleName, { binSuffix: 'range' }, { band, offset });
}
return valueref_fieldRef(channelDef, scaleName, { binSuffix: 'range' }, { offset });
}
}
return valueref_fieldRef(channelDef, scaleName, {}, { offset }); // no need for bin suffix
}
else if (channeldef_isValueDef(channelDef)) {
const value = channelDef.value;
const offsetMixins = offset ? { offset } : {};
return Object.assign(Object.assign({}, valueref_widthHeightValueRef(channel, value)), offsetMixins);
}
// If channelDef is neither field def or value def, it's a condition-only def.
// In such case, we will use default ref.
}
const ref = isFunction(defaultRef) ? Object.assign(Object.assign({}, defaultRef()), (offset ? { offset } : {})) : defaultRef;
if (ref) {
// for non-position, ref could be undefined.
return Object.assign(Object.assign({}, ref), (offset ? { offset } : {}));
}
return ref;
}
/**
* Convert special "width" and "height" values in Vega-Lite into Vega value ref.
*/
function valueref_widthHeightValueRef(channel, value) {
if (util_contains(['x', 'x2'], channel) && value === 'width') {
return { field: { group: 'width' } };
}
else if (util_contains(['y', 'y2'], channel) && value === 'height') {
return { field: { group: 'height' } };
}
return { value };
}
//# sourceMappingURL=valueref.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/nonposition.js
/**
* Return encodoing encode for non-positional channels with scales. (Text doesn't have scale.)
*/
function nonposition_nonPosition(channel, model, opt = {}) {
const { markDef, encoding, config } = model;
const { vgChannel = channel } = opt;
let { defaultRef, defaultValue } = opt;
if (defaultRef === undefined) {
// prettier-ignore
defaultValue = (defaultValue !== null && defaultValue !== void 0 ? defaultValue : (vgChannel === channel
? // When vl channel is the same as Vega's, no need to read from config as Vega will apply them correctly
markDef[channel]
: // However, when they are different (e.g, vl's text size is vg fontSize), need to read "size" from configs
util_getFirstDefined(markDef[channel], markDef[vgChannel], common_getMarkConfig(channel, markDef, config, { vgChannel }))));
defaultRef = defaultValue ? { value: defaultValue } : undefined;
}
const channelDef = encoding[channel];
return conditional_wrapCondition(model, channelDef, vgChannel, cDef => {
return valueref_midPoint({
channel,
channelDef: cDef,
markDef,
config,
scaleName: model.scaleName(channel),
scale: model.getScaleComponent(channel),
stack: null,
defaultRef
});
});
}
//# sourceMappingURL=nonposition.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/color.js
function encode_color_color(model) {
const { markDef, encoding, config } = model;
const { filled, type: markType } = markDef;
const configValue = {
fill: common_getMarkConfig('fill', markDef, config),
stroke: common_getMarkConfig('stroke', markDef, config),
color: common_getMarkConfig('color', markDef, config)
};
const transparentIfNeeded = util_contains(['bar', 'point', 'circle', 'square', 'geoshape'], markType)
? 'transparent'
: undefined;
const defaultFill = util_getFirstDefined(markDef.fill, filled === true ? markDef.color : undefined, configValue.fill, filled === true ? configValue.color : undefined,
// If there is no fill, always fill symbols, bar, geoshape
// with transparent fills https://github.com/vega/vega-lite/issues/1316
transparentIfNeeded);
const defaultStroke = util_getFirstDefined(markDef.stroke, filled === false ? markDef.color : undefined, configValue.stroke, filled === false ? configValue.color : undefined);
const colorVgChannel = filled ? 'fill' : 'stroke';
const fillStrokeMarkDefAndConfig = Object.assign(Object.assign({}, (defaultFill ? { fill: { value: defaultFill } } : {})), (defaultStroke ? { stroke: { value: defaultStroke } } : {}));
if (markDef.color && (filled ? markDef.fill : markDef.stroke)) {
src_log_warn(log_message.droppingColor('property', { fill: 'fill' in markDef, stroke: 'stroke' in markDef }));
}
return Object.assign(Object.assign(Object.assign(Object.assign({}, fillStrokeMarkDefAndConfig), nonposition_nonPosition('color', model, {
vgChannel: colorVgChannel,
defaultValue: filled ? defaultFill : defaultStroke
})), nonposition_nonPosition('fill', model, {
// if there is encoding.fill, include default fill just in case we have conditional-only fill encoding
defaultValue: encoding.fill ? defaultFill : undefined
})), nonposition_nonPosition('stroke', model, {
// if there is encoding.stroke, include default fill just in case we have conditional-only stroke encoding
defaultValue: encoding.stroke ? defaultStroke : undefined
}));
}
//# sourceMappingURL=color.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/text.js
function text_text(model, channel = 'text') {
const channelDef = model.encoding[channel];
return conditional_wrapCondition(model, channelDef, channel, cDef => text_textRef(cDef, model.config));
}
function text_textRef(channelDef, config, expr = 'datum') {
// text
if (channelDef) {
if (channeldef_isValueDef(channelDef)) {
return { value: channelDef.value };
}
if (channeldef_isTypedFieldDef(channelDef)) {
return common_formatSignalRef(channelDef, channeldef_format(channelDef), expr, config);
}
}
return undefined;
}
//# sourceMappingURL=text.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/tooltip.js
function tooltip_tooltip(model, opt = {}) {
const { encoding, markDef, config } = model;
const channelDef = encoding.tooltip;
if (isArray(channelDef)) {
return { tooltip: tooltip_tooltipRefForEncoding({ tooltip: channelDef }, config, opt) };
}
else {
return conditional_wrapCondition(model, channelDef, 'tooltip', cDef => {
// use valueRef based on channelDef first
const tooltipRefFromChannelDef = text_textRef(cDef, model.config, opt.reactiveGeom ? 'datum.datum' : 'datum');
if (tooltipRefFromChannelDef) {
return tooltipRefFromChannelDef;
}
if (cDef === null) {
// Allow using encoding.tooltip = null to disable tooltip
return undefined;
}
// If tooltipDef does not exist, then use value from markDef or config
let markTooltip = util_getFirstDefined(markDef.tooltip, common_getMarkConfig('tooltip', markDef, config));
if (markTooltip === true) {
markTooltip = { content: 'encoding' };
}
if (isString(markTooltip)) {
return { value: markTooltip };
}
else if (isObject(markTooltip)) {
// `tooltip` is `{fields: 'encodings' | 'fields'}`
if (markTooltip.content === 'encoding') {
return tooltip_tooltipRefForEncoding(encoding, config, opt);
}
else {
return { signal: 'datum' };
}
}
return undefined;
});
}
}
function tooltip_tooltipRefForEncoding(encoding, config, { reactiveGeom } = {}) {
const keyValues = [];
const usedKey = {};
const toSkip = {};
const expr = reactiveGeom ? 'datum.datum' : 'datum';
const tooltipTuples = [];
function add(fDef, channel) {
const mainChannel = channel_getMainRangeChannel(channel);
const fieldDef = channeldef_isTypedFieldDef(fDef)
? fDef
: Object.assign(Object.assign({}, fDef), { type: encoding[mainChannel].type // for secondary field def, copy type from main channel
});
const key = vega_util_src_array(channeldef_title(fieldDef, config, { allowDisabling: false })).join(', ');
let value = text_textRef(fieldDef, config, expr).signal;
if (channel === 'x' || channel === 'y') {
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef2 = channeldef_getFieldDef(encoding[channel2]);
if (bin_isBinned(fieldDef.bin) && fieldDef2) {
const startField = channeldef_vgField(fieldDef, { expr });
const endField = channeldef_vgField(fieldDef2, { expr });
value = common_binFormatExpression(startField, endField, channeldef_format(fieldDef), config);
toSkip[channel2] = true;
}
}
tooltipTuples.push({ channel, key, value });
}
encoding_forEach(encoding, (channelDef, channel) => {
if (channeldef_isFieldDef(channelDef)) {
add(channelDef, channel);
}
else if (channeldef_hasConditionalFieldDef(channelDef)) {
add(channelDef.condition, channel);
}
});
for (const { channel, key, value } of tooltipTuples) {
if (!toSkip[channel] && !usedKey[key]) {
keyValues.push(`${stringValue_$(key)}: ${value}`);
usedKey[key] = true;
}
}
return keyValues.length > 0 ? { signal: `{${keyValues.join(', ')}}` } : undefined;
}
//# sourceMappingURL=tooltip.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/offset.js
function getOffset(channel, markDef) {
const offsetChannel = (channel + 'Offset'); // Need to cast as the type can't be inferred automatically
// TODO: in the future read from encoding channel too
const markDefOffsetValue = markDef[offsetChannel];
if (markDefOffsetValue) {
return markDefOffsetValue;
}
return undefined;
}
//# sourceMappingURL=offset.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/position-point.js
/**
* Return encode for point (non-band) position channels.
*/
function position_point_pointPosition(channel, model, { defaultPos, vgChannel }) {
// TODO: refactor how refer to scale as discussed in https://github.com/vega/vega-lite/pull/1613
const { encoding, mark, markDef, config, stack } = model;
const channelDef = encoding[channel];
const channel2Def = encoding[channel === channel_X ? channel_X2 : channel_Y2];
const scaleName = model.scaleName(channel);
const scale = model.getScaleComponent(channel);
const offset = getOffset(channel, model.markDef);
const defaultRef = position_point_pointPositionDefaultRef({
model,
markDef,
config,
defaultPos,
channel,
scaleName,
scale,
mark,
checkBarAreaWithoutZero: !channel2Def // only check for non-ranged marks
});
const valueRef = !channelDef && (encoding.latitude || encoding.longitude)
? // use geopoint output if there are lat/long and there is no point position overriding lat/long.
{ field: model.getName(channel) }
: position_point_positionRef({
channel,
channelDef,
channel2Def,
markDef,
config,
scaleName,
scale,
stack,
offset,
defaultRef
});
return {
[(vgChannel !== null && vgChannel !== void 0 ? vgChannel : channel)]: valueRef
};
}
// TODO: we need to find a way to refactor these so that scaleName is a part of scale
// but that's complicated. For now, this is a huge step moving forward.
/**
* @return Vega ValueRef for normal x- or y-position without projection
*/
function position_point_positionRef(params) {
const { channel, channelDef, scaleName, stack, offset } = params;
// This isn't a part of midPoint because we use midPoint for non-position too
if (channeldef_isFieldDef(channelDef) && stack && channel === stack.fieldChannel) {
if (channeldef_isPositionFieldDef(channelDef) && channelDef.band !== undefined) {
return valueref_interpolatedSignalRef({
scaleName,
fieldDef: channelDef,
startSuffix: 'start',
band: channelDef.band,
offset: 0
});
}
// x or y use stack_end so that stacked line's point mark use stack_end too.
return valueref_fieldRef(channelDef, scaleName, { suffix: 'end' }, { offset });
}
return valueref_midPointRefWithPositionInvalidTest(params);
}
function position_point_pointPositionDefaultRef({ model, markDef, config, defaultPos, channel, scaleName, scale, mark, checkBarAreaWithoutZero: checkBarAreaWithZero }) {
return () => {
const mainChannel = channel_getMainRangeChannel(channel);
const definedValueOrConfig = util_getFirstDefined(markDef[channel], common_getMarkConfig(channel, markDef, config));
if (definedValueOrConfig !== undefined) {
return valueref_widthHeightValueRef(channel, definedValueOrConfig);
}
if (defaultPos === 'zeroOrMin' || defaultPos === 'zeroOrMax') {
if (scaleName) {
const scaleType = scale.get('type');
if (util_contains([scale_ScaleType.LOG, scale_ScaleType.TIME, scale_ScaleType.UTC], scaleType)) {
// Log scales cannot have zero.
// Zero in time scale is arbitrary, and does not affect ratio.
// (Time is an interval level of measurement, not ratio).
// See https://en.wikipedia.org/wiki/Level_of_measurement for more info.
if (checkBarAreaWithZero && (mark === 'bar' || mark === 'area')) {
src_log_warn(log_message.nonZeroScaleUsedWithLengthMark(mark, mainChannel, { scaleType }));
}
}
else {
if (scale.domainDefinitelyIncludesZero()) {
return {
scale: scaleName,
value: 0
};
}
if (checkBarAreaWithZero && (mark === 'bar' || mark === 'area')) {
src_log_warn(log_message.nonZeroScaleUsedWithLengthMark(mark, mainChannel, { zeroFalse: scale.explicit.zero === false }));
}
}
}
if (defaultPos === 'zeroOrMin') {
return mainChannel === 'x' ? { value: 0 } : { field: { group: 'height' } };
}
else {
// zeroOrMax
return mainChannel === 'x' ? { field: { group: 'width' } } : { value: 0 };
}
}
else {
// mid
const sizeRef = model[mainChannel === 'x' ? 'width' : 'height'];
return Object.assign(Object.assign({}, sizeRef), { mult: 0.5 });
}
};
}
//# sourceMappingURL=position-point.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/position-align.js
const position_align_ALIGNED_X_CHANNEL = {
left: 'x',
center: 'xc',
right: 'x2'
};
const position_align_BASELINED_Y_CHANNEL = {
top: 'y',
middle: 'yc',
bottom: 'y2'
};
function position_align_alignedPositionChannel(channel, markDef, config) {
const alignChannel = channel === 'x' ? 'align' : 'baseline';
const align = util_getFirstDefined(markDef[alignChannel], common_getMarkConfig(alignChannel, markDef, config));
if (channel === 'x') {
return position_align_ALIGNED_X_CHANNEL[(align !== null && align !== void 0 ? align : 'center')];
}
else {
return position_align_BASELINED_Y_CHANNEL[(align !== null && align !== void 0 ? align : 'middle')];
}
}
//# sourceMappingURL=position-align.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/position-range.js
function position_range_pointOrRangePosition(channel, model, { defaultPos, defaultPos2, range }) {
if (range) {
return position_range_rangePosition(channel, model, { defaultPos, defaultPos2 });
}
return position_point_pointPosition(channel, model, { defaultPos });
}
function position_range_rangePosition(channel, model, { defaultPos, defaultPos2 }) {
const { markDef, config } = model;
const channel2 = channel === 'x' ? 'x2' : 'y2';
const sizeChannel = channel === 'x' ? 'width' : 'height';
const pos2Mixins = position_range_pointPosition2(model, defaultPos2, channel2);
const vgChannel = pos2Mixins[sizeChannel] ? position_align_alignedPositionChannel(channel, markDef, config) : channel;
return Object.assign(Object.assign({}, position_point_pointPosition(channel, model, { defaultPos, vgChannel })), pos2Mixins);
}
/**
* Return encode for x2, y2.
* If channel is not specified, return one channel based on orientation.
*/
function position_range_pointPosition2(model, defaultPos, channel) {
const { encoding, mark, markDef, stack, config } = model;
const baseChannel = channel === 'x2' ? 'x' : 'y';
const sizeChannel = channel === 'x2' ? 'width' : 'height';
const channelDef = encoding[baseChannel];
const scaleName = model.scaleName(baseChannel);
const scale = model.getScaleComponent(baseChannel);
const offset = getOffset(channel, model.markDef);
if (!channelDef && (encoding.latitude || encoding.longitude)) {
// use geopoint output if there are lat2/long2 and there is no point position2 overriding lat2/long2.
return { [channel]: { field: model.getName(channel) } };
}
const valueRef = position_range_position2Ref({
channel,
channelDef,
channel2Def: encoding[channel],
markDef,
config,
scaleName,
scale,
stack,
offset,
defaultRef: undefined
});
if (valueRef !== undefined) {
return { [channel]: valueRef };
}
const defaultRef = position_point_pointPositionDefaultRef({
model,
markDef,
config,
defaultPos,
channel,
scaleName,
scale,
mark,
checkBarAreaWithoutZero: !encoding[channel] // only check for non-ranged marks
})();
// TODO: check width/height encoding here once we add them
// no x2/y2 encoding, then try to read x2/y2 or width/height based on precedence:
// markDef > config.style > mark-specific config (config[mark]) > general mark config (config.mark)
return util_getFirstDefined(position_range_position2orSize(channel, markDef), position_range_position2orSize(channel, {
[channel]: common_getStyleConfig(channel, markDef, config.style),
[sizeChannel]: common_getStyleConfig(sizeChannel, markDef, config.style)
}), position_range_position2orSize(channel, config[mark]), position_range_position2orSize(channel, config.mark), {
[channel]: defaultRef
});
}
function position_range_position2Ref({ channel, channelDef, channel2Def, markDef, config, scaleName, scale, stack, offset, defaultRef }) {
if (channeldef_isFieldDef(channelDef) &&
stack &&
// If fieldChannel is X and channel is X2 (or Y and Y2)
channel.charAt(0) === stack.fieldChannel.charAt(0)) {
return valueref_fieldRef(channelDef, scaleName, { suffix: 'start' }, { offset });
}
return valueref_midPointRefWithPositionInvalidTest({
channel,
channelDef: channel2Def,
scaleName,
scale,
stack,
markDef,
config,
offset,
defaultRef
});
}
function position_range_position2orSize(channel, markDef) {
const sizeChannel = channel === 'x2' ? 'width' : 'height';
if (markDef[channel]) {
return { [channel]: valueref_widthHeightValueRef(channel, markDef[channel]) };
}
else if (markDef[sizeChannel]) {
return { [sizeChannel]: { value: markDef[sizeChannel] } };
}
return undefined;
}
//# sourceMappingURL=position-range.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/position-rect.js
function position_rect_rectPosition(model, channel, mark) {
var _a, _b, _c, _d;
const { config, encoding, markDef } = model;
const channel2 = channel === 'x' ? 'x2' : 'y2';
const sizeChannel = channel === 'x' ? 'width' : 'height';
const fieldDef = encoding[channel];
const fieldDef2 = encoding[channel2];
const scale = model.getScaleComponent(channel);
const scaleType = scale ? scale.get('type') : undefined;
const scaleName = model.scaleName(channel);
const orient = markDef.orient;
const hasSizeDef = (_d = (_c = (_b = (_a = encoding[sizeChannel], (_a !== null && _a !== void 0 ? _a : encoding.size)), (_b !== null && _b !== void 0 ? _b : markDef[sizeChannel])), (_c !== null && _c !== void 0 ? _c : markDef.size)), (_d !== null && _d !== void 0 ? _d : common_getMarkConfig('size', markDef, config, { vgChannel: sizeChannel })));
const isBarBand = channel === 'x' ? orient === 'vertical' : orient === 'horizontal';
// x, x2, and width -- we must specify two of these in all conditions
if (channeldef_isFieldDef(fieldDef) &&
(bin_isBinning(fieldDef.bin) || bin_isBinned(fieldDef.bin) || (fieldDef.timeUnit && !fieldDef2)) &&
!hasSizeDef &&
!scale_hasDiscreteDomain(scaleType)) {
const band = channeldef_getBand(channel, fieldDef, undefined, markDef, config);
return position_rect_rectBinPosition({
fieldDef,
fieldDef2,
channel,
markDef,
scaleName,
band,
spacing: util_getFirstDefined(markDef.binSpacing, config[mark].binSpacing),
reverse: scale.get('reverse')
});
}
else if (((channeldef_isFieldDef(fieldDef) && scale_hasDiscreteDomain(scaleType)) || isBarBand) && !fieldDef2) {
// vertical
if (channeldef_isFieldDef(fieldDef) && scaleType === scale_ScaleType.BAND) {
const band = channeldef_isPositionFieldDef(fieldDef) ? fieldDef.band : undefined;
return position_rect_rectBandPosition(fieldDef, channel, model, position_rect_defaultSizeRef(mark, markDef, sizeChannel, scaleName, scale, config, band));
}
// sized bin, normal point-ordinal axis, quantitative x-axis, or no x
return position_rect_centeredPointPositionWithSize(channel, model, position_rect_defaultSizeRef(mark, markDef, sizeChannel, scaleName, scale, config));
}
else {
return position_range_rangePosition(channel, model, { defaultPos: 'zeroOrMax', defaultPos2: 'zeroOrMin' });
}
}
function position_rect_centeredPointPositionWithSize(channel, model, sizeRef) {
const centerChannel = channel === 'x' ? 'xc' : 'yc';
const sizeChannel = channel === 'x' ? 'width' : 'height';
return Object.assign(Object.assign({}, position_point_pointPosition(channel, model, { defaultPos: 'mid', vgChannel: centerChannel })), nonposition_nonPosition('size', model, { defaultRef: sizeRef, vgChannel: sizeChannel }));
}
function position_rect_defaultSizeRef(mark, markDef, sizeChannel, scaleName, scale, config, band) {
const markPropOrConfig = util_getFirstDefined(markDef[sizeChannel], markDef.size,
// TODO: deal with sizeChannel config
common_getMarkConfig('size', markDef, config, { vgChannel: sizeChannel }));
if (markPropOrConfig !== undefined) {
return { value: markPropOrConfig };
}
if (scale) {
const scaleType = scale.get('type');
if (scaleType === 'point' || scaleType === 'band') {
if (config[mark].discreteBandSize !== undefined) {
return { value: config[mark].discreteBandSize };
}
if (scaleType === scale_ScaleType.POINT) {
const scaleRange = scale.get('range');
if (vega_schema_isVgRangeStep(scaleRange) && src_isNumber(scaleRange.step)) {
return { value: scaleRange.step - 2 };
}
return { value: config_DEFAULT_STEP - 2 };
}
else {
// BAND
return position_rect_bandRef(scaleName, band);
}
}
else {
// continuous scale
return { value: config[mark].continuousBandSize };
}
}
// No Scale
const step = config_getViewConfigDiscreteStep(config.view, sizeChannel);
const value = util_getFirstDefined(
// No scale is like discrete bar (with one item)
config[mark].discreteBandSize, step - 2);
return { value };
}
function position_rect_bandRef(scaleName, band = true) {
return {
scale: scaleName,
band: band
};
}
function position_rect_rectBandPosition(fieldDef, channel, model, sizeRef) {
var _a;
const scaleName = model.scaleName(channel);
const sizeChannel = channel === 'x' ? 'width' : 'height';
const { markDef, encoding, config } = model;
const vgChannel = position_align_alignedPositionChannel(channel, markDef, config);
const centeredBandPositionMixins = {
[vgChannel]: valueref_fieldRef(fieldDef, scaleName, {}, { band: 0.5 })
};
if (encoding.size || (markDef.size !== null && markDef.size !== undefined)) {
const orient = markDef.orient;
if (orient) {
if (channeldef_getTypedFieldDef(encoding.size) || channeldef_isValueDef(encoding.size)) {
return Object.assign(Object.assign({}, centeredBandPositionMixins), nonposition_nonPosition('size', model, { vgChannel: sizeChannel }));
}
else if (markDef.size !== undefined) {
return Object.assign(Object.assign({}, centeredBandPositionMixins), { [sizeChannel]: { value: markDef.size } });
}
}
else {
src_log_warn(log_message.cannotApplySizeToNonOrientedMark(markDef.type));
}
}
if (((_a = sizeRef) === null || _a === void 0 ? void 0 : _a.value) !== undefined) {
return Object.assign(Object.assign({}, centeredBandPositionMixins), { [sizeChannel]: sizeRef });
}
const { band = 1 } = fieldDef;
return {
// FIXME: make offset work correctly here when we support group bar (https://github.com/vega/vega-lite/issues/396)
[channel]: valueref_fieldRef(fieldDef, scaleName, { binSuffix: 'range' }, { band: (1 - band) / 2 }),
[sizeChannel]: (sizeRef !== null && sizeRef !== void 0 ? sizeRef : position_rect_bandRef(scaleName, band))
};
}
function position_rect_rectBinPosition({ fieldDef, fieldDef2, channel, band, scaleName, markDef, spacing = 0, reverse }) {
const binSpacing = {
x: reverse ? spacing : 0,
x2: reverse ? 0 : spacing,
y: reverse ? 0 : spacing,
y2: reverse ? spacing : 0
};
const channel2 = channel === channel_X ? channel_X2 : channel_Y2;
if (bin_isBinning(fieldDef.bin) || fieldDef.timeUnit) {
return {
[channel2]: position_rect_rectBinRef({
channel,
fieldDef,
scaleName,
markDef,
band: (1 - band) / 2,
offset: binSpacing[`${channel}2`]
}),
[channel]: position_rect_rectBinRef({
channel,
fieldDef,
scaleName,
markDef,
band: 1 - (1 - band) / 2,
offset: binSpacing[channel]
})
};
}
else if (bin_isBinned(fieldDef.bin) && channeldef_isFieldDef(fieldDef2)) {
return {
[channel2]: valueref_fieldRef(fieldDef, scaleName, {}, { offset: binSpacing[`${channel}2`] }),
[channel]: valueref_fieldRef(fieldDef2, scaleName, {}, { offset: binSpacing[channel] })
};
}
else {
src_log_warn(log_message.channelRequiredForBinned(channel2));
return undefined;
}
}
/**
* Value Ref for binned fields
*/
function position_rect_rectBinRef({ channel, fieldDef, scaleName, markDef, band, offset }) {
const r = valueref_interpolatedSignalRef({
scaleName,
fieldDef,
band,
offset
});
return valueref_wrapPositionInvalidTest({
fieldDef,
channel,
markDef,
ref: r
});
}
//# sourceMappingURL=position-rect.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/base.js
function base_baseEncodeEntry(model, ignore) {
const { fill = undefined, stroke = undefined } = ignore.color === 'include' ? encode_color_color(model) : {};
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, base_markDefProperties(model.markDef, ignore)), base_wrapAllFieldsInvalid(model, 'fill', fill)), base_wrapAllFieldsInvalid(model, 'stroke', stroke)), nonposition_nonPosition('opacity', model)), nonposition_nonPosition('fillOpacity', model)), nonposition_nonPosition('strokeOpacity', model)), nonposition_nonPosition('strokeWidth', model)), tooltip_tooltip(model)), text_text(model, 'href'));
}
// TODO: mark VgValueRef[] as readonly after https://github.com/vega/vega/pull/1987
function base_wrapAllFieldsInvalid(model, channel, valueRef) {
const { config, mark, markDef } = model;
const invalid = common_getMarkPropOrConfig('invalid', markDef, config);
if (invalid === 'hide' && valueRef && !mark_isPathMark(mark)) {
// For non-path marks, we have to exclude invalid values (null and NaN) for scales with continuous domains.
// For path marks, we will use "defined" property and skip these values instead.
const test = base_allFieldsInvalidPredicate(model, { invalid: true, channels: channel_SCALE_CHANNELS });
if (test) {
return {
[channel]: [
// prepend the invalid case
// TODO: support custom value
{ test, value: null },
...vega_util_src_array(valueRef)
]
};
}
}
return valueRef ? { [channel]: valueRef } : {};
}
function base_markDefProperties(mark, ignore) {
return vega_schema_VG_MARK_CONFIGS.reduce((m, prop) => {
if (mark[prop] !== undefined && ignore[prop] !== 'ignore') {
m[prop] = { value: mark[prop] };
}
return m;
}, {});
}
function base_allFieldsInvalidPredicate(model, { invalid = false, channels }) {
const filterIndex = channels.reduce((aggregator, channel) => {
const scaleComponent = model.getScaleComponent(channel);
if (scaleComponent) {
const scaleType = scaleComponent.get('type');
const field = model.vgField(channel, { expr: 'datum' });
// While discrete domain scales can handle invalid values, continuous scales can't.
if (field && scale_hasContinuousDomain(scaleType)) {
aggregator[field] = true;
}
}
return aggregator;
}, {});
const fields = util_keys(filterIndex);
if (fields.length > 0) {
const op = invalid ? '||' : '&&';
return fields.map(field => valueref_fieldInvalidPredicate(field, invalid)).join(` ${op} `);
}
return undefined;
}
//# sourceMappingURL=base.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/defined.js
function defined_defined(model) {
const { config, markDef } = model;
const invalid = common_getMarkPropOrConfig('invalid', markDef, config);
if (invalid) {
const signal = defined_allFieldsInvalidPredicate(model, { channels: ['x', 'y'] });
if (signal) {
return { defined: { signal } };
}
}
return {};
}
function defined_allFieldsInvalidPredicate(model, { invalid = false, channels }) {
const filterIndex = channels.reduce((aggregator, channel) => {
const scaleComponent = model.getScaleComponent(channel);
if (scaleComponent) {
const scaleType = scaleComponent.get('type');
const field = model.vgField(channel, { expr: 'datum' });
// While discrete domain scales can handle invalid values, continuous scales can't.
if (field && scale_hasContinuousDomain(scaleType)) {
aggregator[field] = true;
}
}
return aggregator;
}, {});
const fields = util_keys(filterIndex);
if (fields.length > 0) {
const op = invalid ? '||' : '&&';
return fields.map(field => valueref_fieldInvalidPredicate(field, invalid)).join(` ${op} `);
}
return undefined;
}
function defined_valueIfDefined(prop, value) {
if (value !== undefined) {
return { [prop]: { value: value } };
}
return undefined;
}
//# sourceMappingURL=defined.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/encode/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/nearest.js
const nearest_VORONOI = 'voronoi';
const nearest_nearest = {
has: selCmpt => {
return selCmpt.type !== 'interval' && selCmpt.nearest;
},
parse: (model, selCmpt) => {
// Scope selection events to the voronoi mark to prevent capturing
// events that occur on the group mark (https://github.com/vega/vega/issues/2112).
if (selCmpt.events) {
for (const s of selCmpt.events) {
s.markname = model.getName(nearest_VORONOI);
}
}
},
marks: (model, selCmpt, marks) => {
const { x, y } = selCmpt.project.hasChannel;
const markType = model.mark;
if (mark_isPathMark(markType)) {
src_log_warn(log_message.nearestNotSupportForContinuous(markType));
return marks;
}
const cellDef = {
name: model.getName(nearest_VORONOI),
type: 'path',
interactive: true,
from: { data: model.getName('marks') },
encode: {
update: Object.assign({ fill: { value: 'transparent' }, strokeWidth: { value: 0.35 }, stroke: { value: 'transparent' }, isVoronoi: { value: true } }, tooltip_tooltip(model, { reactiveGeom: true }))
},
transform: [
{
type: 'voronoi',
x: { expr: x || !y ? 'datum.datum.x || 0' : '0' },
y: { expr: y || !x ? 'datum.datum.y || 0' : '0' },
size: [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')]
}
]
};
let index = 0;
let exists = false;
marks.forEach((mark, i) => {
var _a;
const name = (_a = mark.name, (_a !== null && _a !== void 0 ? _a : ''));
if (name === model.component.mark[0].name) {
index = i;
}
else if (name.indexOf(nearest_VORONOI) >= 0) {
exists = true;
}
});
if (!exists) {
marks.splice(index + 1, 0, cellDef);
}
return marks;
}
};
/* harmony default export */ var transforms_nearest = (nearest_nearest);
//# sourceMappingURL=nearest.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/dataflow.js
/**
* A node in the dataflow tree.
*/
class dataflow_DataFlowNode {
constructor(parent, debugName) {
this.debugName = debugName;
this._children = [];
this._parent = null;
if (parent) {
this.parent = parent;
}
}
/**
* Clone this node with a deep copy but don't clone links to children or parents.
*/
clone() {
throw new Error('Cannot clone node');
}
get parent() {
return this._parent;
}
/**
* Set the parent of the node and also add this node to the parent's children.
*/
set parent(parent) {
this._parent = parent;
if (parent) {
parent.addChild(this);
}
}
get children() {
return this._children;
}
numChildren() {
return this._children.length;
}
addChild(child, loc) {
// do not add the same child twice
if (this._children.indexOf(child) > -1) {
console.warn('Attempt to add the same child twice.');
return;
}
if (loc !== undefined) {
this._children.splice(loc, 0, child);
}
else {
this._children.push(child);
}
}
removeChild(oldChild) {
const loc = this._children.indexOf(oldChild);
this._children.splice(loc, 1);
return loc;
}
/**
* Remove node from the dataflow.
*/
remove() {
let loc = this._parent.removeChild(this);
for (const child of this._children) {
// do not use the set method because we want to insert at a particular location
child._parent = this._parent;
this._parent.addChild(child, loc++);
}
}
/**
* Insert another node as a parent of this node.
*/
insertAsParentOf(other) {
const parent = other.parent;
parent.removeChild(this);
this.parent = parent;
other.parent = this;
}
swapWithParent() {
const parent = this._parent;
const newParent = parent.parent;
// reconnect the children
for (const child of this._children) {
child.parent = parent;
}
// remove old links
this._children = []; // equivalent to removing every child link one by one
parent.removeChild(this);
parent.parent.removeChild(parent);
// swap two nodes
this.parent = newParent;
parent.parent = this;
}
}
class dataflow_OutputNode extends dataflow_DataFlowNode {
/**
* @param source The name of the source. Will change in assemble.
* @param type The type of the output node.
* @param refCounts A global ref counter map.
*/
constructor(parent, source, type, refCounts) {
super(parent, source);
this.type = type;
this.refCounts = refCounts;
this._source = this._name = source;
if (this.refCounts && !(this._name in this.refCounts)) {
this.refCounts[this._name] = 0;
}
}
clone() {
const cloneObj = new this.constructor();
cloneObj.debugName = 'clone_' + this.debugName;
cloneObj._source = this._source;
cloneObj._name = 'clone_' + this._name;
cloneObj.type = this.type;
cloneObj.refCounts = this.refCounts;
cloneObj.refCounts[cloneObj._name] = 0;
return cloneObj;
}
dependentFields() {
return new Set();
}
producedFields() {
return new Set();
}
hash() {
if (this._hash === undefined) {
this._hash = `Output ${util_uniqueId()}`;
}
return this._hash;
}
/**
* Request the datasource name and increase the ref counter.
*
* During the parsing phase, this will return the simple name such as 'main' or 'raw'.
* It is crucial to request the name from an output node to mark it as a required node.
* If nobody ever requests the name, this datasource will not be instantiated in the assemble phase.
*
* In the assemble phase, this will return the correct name.
*/
getSource() {
this.refCounts[this._name]++;
return this._source;
}
isRequired() {
return !!this.refCounts[this._name];
}
setSource(source) {
this._source = source;
}
}
//# sourceMappingURL=dataflow.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/timeunit.js
class timeunit_TimeUnitNode extends dataflow_DataFlowNode {
constructor(parent, formula) {
super(parent);
this.formula = formula;
}
clone() {
return new timeunit_TimeUnitNode(null, util_duplicate(this.formula));
}
static makeFromEncoding(parent, model) {
const formula = model.reduceFieldDef((timeUnitComponent, fieldDef, channel) => {
const { timeUnit, field } = fieldDef;
const channelDef2 = model_isUnitModel(model) ? model.encoding[channel_getSecondaryRangeChannel(channel)] : undefined;
const band = model_isUnitModel(model) && channeldef_hasBand(channel, fieldDef, channelDef2, model.markDef, model.config);
if (timeUnit) {
const as = channeldef_vgField(fieldDef, { forAs: true });
timeUnitComponent[util_hash({ as, timeUnit, field })] = Object.assign({ as,
timeUnit,
field }, (band ? { band: true } : {}));
}
return timeUnitComponent;
}, {});
if (util_keys(formula).length === 0) {
return null;
}
return new timeunit_TimeUnitNode(parent, formula);
}
static makeFromTransform(parent, t) {
const component = Object.assign({}, t);
return new timeunit_TimeUnitNode(parent, {
[util_hash(component)]: component
});
}
/**
* Merge together TimeUnitNodes assigning the children of `other` to `this`
* and removing `other`.
*/
merge(other) {
this.formula = Object.assign({}, this.formula);
// if the same hash happen twice, merge "band"
for (const key in other.formula) {
if (!this.formula[key] || other.formula[key].band) {
// copy if it's not a duplicate or if we need to include copy band over
this.formula[key] = other.formula[key];
}
}
for (const child of other.children) {
other.removeChild(child);
child.parent = this;
}
other.remove();
}
producedFields() {
return new Set(util_vals(this.formula).map(f => f.as));
}
dependentFields() {
return new Set(util_vals(this.formula).map(f => f.field));
}
hash() {
return `TimeUnit ${util_hash(this.formula)}`;
}
assemble() {
const transforms = [];
for (const f of util_vals(this.formula)) {
const { timeUnit, field, as } = f;
transforms.push({
field,
type: 'timeunit',
units: timeunit_getTimeUnitParts(timeUnit),
as: [as, `${as}_end`]
});
}
return transforms;
}
}
//# sourceMappingURL=timeunit.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/project.js
const project_TUPLE_FIELDS = '_tuple_fields';
class project_SelectionProjectionComponent {
constructor(...items) {
this.items = items;
this.hasChannel = {};
this.hasField = {};
}
}
const project_project = {
has: () => {
return true; // This transform handles its own defaults, so always run parse.
},
parse: (model, selCmpt, selDef) => {
var _a, _b, _c;
const name = selCmpt.name;
const proj = (_a = selCmpt.project, (_a !== null && _a !== void 0 ? _a : (selCmpt.project = new project_SelectionProjectionComponent())));
const parsed = {};
const timeUnits = {};
const signals = new Set();
const signalName = (p, range) => {
const suffix = range === 'visual' ? p.channel : p.field;
let sg = util_varName(`${name}_${suffix}`);
for (let counter = 1; signals.has(sg); counter++) {
sg = util_varName(`${name}_${suffix}_${counter}`);
}
signals.add(sg);
return { [range]: sg };
};
// If no explicit projection (either fields or encodings) is specified, set some defaults.
// If an initial value is set, try to infer projections.
// Otherwise, use the default configuration.
if (!selDef.fields && !selDef.encodings) {
const cfg = model.config.selection[selDef.type];
if (selDef.init) {
for (const init of vega_util_src_array(selDef.init)) {
for (const key of util_keys(init)) {
if (channel_isSingleDefUnitChannel(key)) {
(selDef.encodings || (selDef.encodings = [])).push(key);
}
else {
if (selDef.type === 'interval') {
src_log_warn('Interval selections should be initialized using "x" and/or "y" keys.');
selDef.encodings = cfg.encodings;
}
else {
(selDef.fields || (selDef.fields = [])).push(key);
}
}
}
}
}
else {
selDef.encodings = cfg.encodings;
selDef.fields = cfg.fields;
}
}
// TODO: find a possible channel mapping for these fields.
for (const field of (_b = selDef.fields, (_b !== null && _b !== void 0 ? _b : []))) {
const p = { type: 'E', field };
p.signals = Object.assign({}, signalName(p, 'data'));
proj.items.push(p);
proj.hasField[field] = p;
}
for (const channel of (_c = selDef.encodings, (_c !== null && _c !== void 0 ? _c : []))) {
const fieldDef = model.fieldDef(channel);
if (fieldDef) {
let field = fieldDef.field;
if (fieldDef.aggregate) {
src_log_warn(log_message.cannotProjectAggregate(channel, fieldDef.aggregate));
continue;
}
else if (!field) {
src_log_warn(log_message.cannotProjectOnChannelWithoutField(channel));
continue;
}
if (fieldDef.timeUnit) {
field = model.vgField(channel);
// Construct TimeUnitComponents which will be combined into a
// TimeUnitNode. This node may need to be inserted into the
// dataflow if the selection is used across views that do not
// have these time units defined.
const component = {
as: field,
field: fieldDef.field,
timeUnit: fieldDef.timeUnit
};
timeUnits[util_hash(component)] = component;
}
// Prevent duplicate projections on the same field.
// TODO: what if the same field is bound to multiple channels (e.g., SPLOM diag).
if (!parsed[field]) {
// Determine whether the tuple will store enumerated or ranged values.
// Interval selections store ranges for continuous scales, and enumerations otherwise.
// Single/multi selections store ranges for binned fields, and enumerations otherwise.
let type = 'E';
if (selCmpt.type === 'interval') {
const scaleType = model.getScaleComponent(channel).get('type');
if (scale_hasContinuousDomain(scaleType)) {
type = 'R';
}
}
else if (fieldDef.bin) {
type = 'R-RE';
}
const p = { field, channel, type };
p.signals = Object.assign(Object.assign({}, signalName(p, 'data')), signalName(p, 'visual'));
proj.items.push((parsed[field] = p));
proj.hasField[field] = proj.hasChannel[channel] = parsed[field];
}
}
else {
src_log_warn(log_message.cannotProjectOnChannelWithoutField(channel));
}
}
if (selDef.init) {
const parseInit = (i) => {
return proj.items.map(p => (i[p.channel] !== undefined ? i[p.channel] : i[p.field]));
};
if (selDef.type === 'interval') {
selCmpt.init = parseInit(selDef.init);
}
else {
const init = isArray(selDef.init) ? selDef.init : [selDef.init];
selCmpt.init = init.map(parseInit);
}
}
if (util_keys(timeUnits).length > 0) {
proj.timeUnit = new timeunit_TimeUnitNode(null, timeUnits);
}
},
signals: (model, selCmpt, allSignals) => {
const name = selCmpt.name + project_TUPLE_FIELDS;
const hasSignal = allSignals.filter(s => s.name === name);
return hasSignal.length > 0
? allSignals
: allSignals.concat({
name,
value: selCmpt.project.items.map(proj => {
const { signals, hasLegend } = proj, rest = tslib_es6_rest(proj, ["signals", "hasLegend"]);
const p = util_duplicate(rest);
p.field = util_replacePathInField(p.field);
return p;
})
});
}
};
/* harmony default export */ var transforms_project = (project_project);
//# sourceMappingURL=project.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/inputs.js
const inputs_inputBindings = {
has: selCmpt => {
return (selCmpt.type === 'single' &&
selCmpt.resolve === 'global' &&
selCmpt.bind &&
selCmpt.bind !== 'scales' &&
!selection_isLegendBinding(selCmpt.bind));
},
parse: (model, selCmpt, selDef, origDef) => {
// Binding a selection to input widgets disables default direct manipulation interaction.
// A user can choose to re-enable it by explicitly specifying triggering input events.
if (!origDef.on)
delete selCmpt.events;
if (!origDef.clear)
delete selCmpt.clear;
},
topLevelSignals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const proj = selCmpt.project;
const bind = selCmpt.bind;
const init = selCmpt.init && selCmpt.init[0]; // Can only exist on single selections (one initial value).
const datum = transforms_nearest.has(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum';
proj.items.forEach((p, i) => {
var _a, _b;
const sgname = util_varName(`${name}_${p.field}`);
const hasSignal = signals.filter(s => s.name === sgname);
if (!hasSignal.length) {
signals.unshift(Object.assign(Object.assign({ name: sgname }, (init ? { init: assemble_assembleInit(init[i]) } : { value: null })), { on: selCmpt.events
? [
{
events: selCmpt.events,
update: `datum && item().mark.marktype !== 'group' ? ${datum}[${stringValue_$(p.field)}] : null`
}
]
: [], bind: (_b = (_a = bind[p.field], (_a !== null && _a !== void 0 ? _a : bind[p.channel])), (_b !== null && _b !== void 0 ? _b : bind)) }));
}
});
return signals;
},
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const proj = selCmpt.project;
const signal = signals.filter(s => s.name === name + selection_TUPLE)[0];
const fields = name + project_TUPLE_FIELDS;
const values = proj.items.map(p => util_varName(`${name}_${p.field}`));
const valid = values.map(v => `${v} !== null`).join(' && ');
if (values.length) {
signal.update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;
}
delete signal.value;
delete signal.on;
return signals;
}
};
/* harmony default export */ var transforms_inputs = (inputs_inputBindings);
//# sourceMappingURL=inputs.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/toggle.js
const toggle_TOGGLE = '_toggle';
const toggle_toggle = {
has: selCmpt => {
return selCmpt.type === 'multi' && !!selCmpt.toggle;
},
signals: (model, selCmpt, signals) => {
return signals.concat({
name: selCmpt.name + toggle_TOGGLE,
value: false,
on: [{ events: selCmpt.events, update: selCmpt.toggle }]
});
},
modifyExpr: (model, selCmpt) => {
const tpl = selCmpt.name + selection_TUPLE;
const signal = selCmpt.name + toggle_TOGGLE;
return (`${signal} ? null : ${tpl}, ` +
(selCmpt.resolve === 'global' ? `${signal} ? null : true, ` : `${signal} ? null : {unit: ${selection_unitName(model)}}, `) +
`${signal} ? ${tpl} : null`);
}
};
/* harmony default export */ var transforms_toggle = (toggle_toggle);
//# sourceMappingURL=toggle.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/clear.js
const clear_clear = {
has: selCmpt => {
return selCmpt.clear !== undefined && selCmpt.clear !== false;
},
parse: (model, selCmpt, selDef) => {
if (selDef.clear) {
selCmpt.clear = isString(selDef.clear) ? event_selector(selDef.clear, 'scope') : selDef.clear;
}
},
topLevelSignals: (model, selCmpt, signals) => {
if (transforms_inputs.has(selCmpt)) {
selCmpt.project.items.forEach(proj => {
const idx = signals.findIndex(n => n.name === util_varName(`${selCmpt.name}_${proj.field}`));
if (idx !== -1) {
signals[idx].on.push({ events: selCmpt.clear, update: 'null' });
}
});
}
return signals;
},
signals: (model, selCmpt, signals) => {
function addClear(idx, update) {
if (idx !== -1 && signals[idx].on) {
signals[idx].on.push({ events: selCmpt.clear, update });
}
}
// Be as minimalist as possible when adding clear triggers to minimize dataflow execution.
if (selCmpt.type === 'interval') {
selCmpt.project.items.forEach(proj => {
const vIdx = signals.findIndex(n => n.name === proj.signals.visual);
addClear(vIdx, '[0, 0]');
if (vIdx === -1) {
const dIdx = signals.findIndex(n => n.name === proj.signals.data);
addClear(dIdx, 'null');
}
});
}
else {
let tIdx = signals.findIndex(n => n.name === selCmpt.name + selection_TUPLE);
addClear(tIdx, 'null');
if (transforms_toggle.has(selCmpt)) {
tIdx = signals.findIndex(n => n.name === selCmpt.name + toggle_TOGGLE);
addClear(tIdx, 'false');
}
}
return signals;
}
};
/* harmony default export */ var transforms_clear = (clear_clear);
//# sourceMappingURL=clear.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/scales.js
const scales_scaleBindings = {
has: selCmpt => {
return selCmpt.type === 'interval' && selCmpt.resolve === 'global' && selCmpt.bind && selCmpt.bind === 'scales';
},
parse: (model, selCmpt) => {
const bound = (selCmpt.scales = []);
for (const proj of selCmpt.project.items) {
const channel = proj.channel;
if (!channel_isScaleChannel(channel)) {
continue;
}
const scale = model.getScaleComponent(channel);
const scaleType = scale ? scale.get('type') : undefined;
if (!scale || !scale_hasContinuousDomain(scaleType)) {
src_log_warn(log_message.SCALE_BINDINGS_CONTINUOUS);
continue;
}
const extent = { selection: selCmpt.name, field: proj.field };
scale.set('selectionExtent', extent, true);
bound.push(proj);
// Bind both x/y for diag plot of repeated views.
if (model.repeater && model.repeater.row === model.repeater.column) {
const scale2 = model.getScaleComponent(channel === channel_X ? channel_Y : channel_X);
scale2.set('selectionExtent', extent, true);
}
}
},
topLevelSignals: (model, selCmpt, signals) => {
const bound = selCmpt.scales.filter(proj => signals.filter(s => s.name === proj.signals.data).length === 0);
// Top-level signals are only needed for multiview displays and if this
// view's top-level signals haven't already been generated.
if (!model.parent || scales_isTopLevelLayer(model) || bound.length === 0) {
return signals;
}
// vlSelectionResolve does not account for the behavior of bound scales in
// multiview displays. Each unit view adds a tuple to the store, but the
// state of the selection is the unit selection most recently updated. This
// state is captured by the top-level signals that we insert and "push
// outer" to from within the units. We need to reassemble this state into
// the top-level named signal, except no single selCmpt has a global view.
const namedSg = signals.filter(s => s.name === selCmpt.name)[0];
let update = namedSg.update;
if (update.indexOf(selection_VL_SELECTION_RESOLVE) >= 0) {
namedSg.update = `{${bound.map(proj => `${stringValue_$(proj.field)}: ${proj.signals.data}`).join(', ')}}`;
}
else {
for (const proj of bound) {
const mapping = `${stringValue_$(proj.field)}: ${proj.signals.data}`;
if (update.indexOf(mapping) < 0) {
update = `${update.substring(0, update.length - 1)}, ${mapping}}`;
}
}
namedSg.update = update;
}
return signals.concat(bound.map(proj => ({ name: proj.signals.data })));
},
signals: (model, selCmpt, signals) => {
// Nested signals need only push to top-level signals with multiview displays.
if (model.parent && !scales_isTopLevelLayer(model)) {
for (const proj of selCmpt.scales) {
const signal = signals.filter(s => s.name === proj.signals.data)[0];
signal.push = 'outer';
delete signal.value;
delete signal.update;
}
}
return signals;
}
};
/* harmony default export */ var transforms_scales = (scales_scaleBindings);
function scales_domain(model, channel) {
const scale = stringValue_$(model.scaleName(channel));
return `domain(${scale})`;
}
function scales_isTopLevelLayer(model) {
var _a;
return model.parent && model_isLayerModel(model.parent) && (_a = !model.parent.parent, (_a !== null && _a !== void 0 ? _a : scales_isTopLevelLayer(model.parent.parent)));
}
//# sourceMappingURL=scales.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/legends.js
const legends_legendBindings = {
has: (selCmpt) => {
const spec = selCmpt.resolve === 'global' && selCmpt.bind && selection_isLegendBinding(selCmpt.bind);
const projLen = selCmpt.project.items.length === 1 && selCmpt.project.items[0].field !== selection_SELECTION_ID;
if (spec && !projLen) {
src_log_warn(log_message.LEGEND_BINDINGS_PROJECT_LENGTH);
}
return spec && projLen;
},
parse: (model, selCmpt, selDef, origDef) => {
var _a;
// Binding a selection to a legend disables default direct manipulation interaction.
// A user can choose to re-enable it by explicitly specifying triggering input events.
if (!origDef.on)
delete selCmpt.events;
if (!origDef.clear)
delete selCmpt.clear;
if (origDef.on || origDef.clear) {
const legendFilter = 'event.item && indexof(event.item.mark.role, "legend") < 0';
for (const evt of selCmpt.events) {
evt.filter = vega_util_src_array((_a = evt.filter, (_a !== null && _a !== void 0 ? _a : [])));
if (evt.filter.indexOf(legendFilter) < 0) {
evt.filter.push(legendFilter);
}
}
}
const evt = selection_isLegendStreamBinding(selCmpt.bind) ? selCmpt.bind.legend : 'click';
const stream = isString(evt) ? event_selector(evt, 'view') : vega_util_src_array(evt);
selCmpt.bind = { legend: { merge: stream } };
},
topLevelSignals: (model, selCmpt, signals) => {
const selName = selCmpt.name;
const stream = selection_isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;
const markName = (name) => (s) => {
const ds = util_duplicate(s);
ds.markname = name;
return ds;
};
for (const proj of selCmpt.project.items) {
if (!proj.hasLegend)
continue;
const prefix = `${proj.field}_legend`;
const sgName = `${selName}_${prefix}`;
const hasSignal = signals.filter(s => s.name === sgName);
if (hasSignal.length === 0) {
const events = stream.merge
.map(markName(`${prefix}_symbols`))
.concat(stream.merge.map(markName(`${prefix}_labels`)))
.concat(stream.merge.map(markName(`${prefix}_entries`)));
signals.unshift(Object.assign(Object.assign({ name: sgName }, (!selCmpt.init ? { value: null } : {})), { on: [
// Legend entries do not store values, so we need to walk the scenegraph to the symbol datum.
{ events, update: 'datum.value || item().items[0].items[0].datum.value', force: true },
{ events: stream.merge, update: `!event.item || !datum ? null : ${sgName}`, force: true }
] }));
}
}
return signals;
},
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const proj = selCmpt.project;
const tuple = signals.find(s => s.name === name + selection_TUPLE);
const fields = name + project_TUPLE_FIELDS;
const values = proj.items.filter(p => p.hasLegend).map(p => util_varName(`${name}_${p.field}_legend`));
const valid = values.map(v => `${v} !== null`).join(' && ');
const update = `${valid} ? {fields: ${fields}, values: [${values.join(', ')}]} : null`;
if (selCmpt.events && values.length > 0) {
tuple.on.push({
events: values.map(signal => ({ signal })),
update
});
}
else if (values.length > 0) {
tuple.update = update;
delete tuple.value;
delete tuple.on;
}
const toggle = signals.find(s => s.name === name + toggle_TOGGLE);
const events = selection_isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;
if (toggle) {
if (!selCmpt.events)
toggle.on[0].events = events;
else
toggle.on.push(Object.assign(Object.assign({}, toggle.on[0]), { events }));
}
return signals;
}
};
/* harmony default export */ var transforms_legends = (legends_legendBindings);
function legends_parseInteractiveLegend(model, channel, legendCmpt) {
const field = model.fieldDef(channel).field;
selection_forEachSelection(model, selCmpt => {
var _a, _b;
const proj = (_a = selCmpt.project.hasField[field], (_a !== null && _a !== void 0 ? _a : selCmpt.project.hasChannel[channel]));
if (proj && legends_legendBindings.has(selCmpt)) {
const legendSelections = (_b = legendCmpt.get('selections'), (_b !== null && _b !== void 0 ? _b : []));
legendSelections.push(selCmpt.name);
legendCmpt.set('selections', legendSelections, false);
proj.hasLegend = true;
}
});
}
//# sourceMappingURL=legends.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/translate.js
const translate_ANCHOR = '_translate_anchor';
const translate_DELTA = '_translate_delta';
const translate_translate = {
has: selCmpt => {
return selCmpt.type === 'interval' && selCmpt.translate;
},
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const hasScales = transforms_scales.has(selCmpt);
const anchor = name + translate_ANCHOR;
const { x, y } = selCmpt.project.hasChannel;
let events = event_selector(selCmpt.translate, 'scope');
if (!hasScales) {
events = events.map(e => ((e.between[0].markname = name + interval_BRUSH), e));
}
signals.push({
name: anchor,
value: {},
on: [
{
events: events.map(e => e.between[0]),
update: '{x: x(unit), y: y(unit)' +
(x !== undefined ? ', extent_x: ' + (hasScales ? scales_domain(model, channel_X) : `slice(${x.signals.visual})`) : '') +
(y !== undefined ? ', extent_y: ' + (hasScales ? scales_domain(model, channel_Y) : `slice(${y.signals.visual})`) : '') +
'}'
}
]
}, {
name: name + translate_DELTA,
value: {},
on: [
{
events: events,
update: `{x: ${anchor}.x - x(unit), y: ${anchor}.y - y(unit)}`
}
]
});
if (x !== undefined) {
translate_onDelta(model, selCmpt, x, 'width', signals);
}
if (y !== undefined) {
translate_onDelta(model, selCmpt, y, 'height', signals);
}
return signals;
}
};
/* harmony default export */ var transforms_translate = (translate_translate);
function translate_onDelta(model, selCmpt, proj, size, signals) {
var _a;
const name = selCmpt.name;
const anchor = name + translate_ANCHOR;
const delta = name + translate_DELTA;
const channel = proj.channel;
const hasScales = transforms_scales.has(selCmpt);
const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0];
const sizeSg = model.getSizeSignalRef(size).signal;
const scaleCmpt = model.getScaleComponent(channel);
const scaleType = scaleCmpt.get('type');
const sign = hasScales && channel === channel_X ? '-' : ''; // Invert delta when panning x-scales.
const extent = `${anchor}.extent_${channel}`;
const offset = `${sign}${delta}.${channel} / ` + (hasScales ? `${sizeSg}` : `span(${extent})`);
const panFn = !hasScales
? 'panLinear'
: scaleType === 'log'
? 'panLog'
: scaleType === 'pow'
? 'panPow'
: 'panLinear';
const update = `${panFn}(${extent}, ${offset}` +
(hasScales && scaleType === 'pow' ? `, ${_a = scaleCmpt.get('exponent'), (_a !== null && _a !== void 0 ? _a : 1)}` : '') +
')';
signal.on.push({
events: { signal: delta },
update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`
});
}
//# sourceMappingURL=translate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/zoom.js
const zoom_ANCHOR = '_zoom_anchor';
const zoom_DELTA = '_zoom_delta';
const zoom_zoom = {
has: selCmpt => {
return selCmpt.type === 'interval' && selCmpt.zoom;
},
signals: (model, selCmpt, signals) => {
const name = selCmpt.name;
const hasScales = transforms_scales.has(selCmpt);
const delta = name + zoom_DELTA;
const { x, y } = selCmpt.project.hasChannel;
const sx = stringValue_$(model.scaleName(channel_X));
const sy = stringValue_$(model.scaleName(channel_Y));
let events = event_selector(selCmpt.zoom, 'scope');
if (!hasScales) {
events = events.map(e => ((e.markname = name + interval_BRUSH), e));
}
signals.push({
name: name + zoom_ANCHOR,
on: [
{
events: events,
update: !hasScales
? `{x: x(unit), y: y(unit)}`
: '{' +
[sx ? `x: invert(${sx}, x(unit))` : '', sy ? `y: invert(${sy}, y(unit))` : '']
.filter(expr => !!expr)
.join(', ') +
'}'
}
]
}, {
name: delta,
on: [
{
events: events,
force: true,
update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))'
}
]
});
if (x !== undefined) {
zoom_onDelta(model, selCmpt, x, 'width', signals);
}
if (y !== undefined) {
zoom_onDelta(model, selCmpt, y, 'height', signals);
}
return signals;
}
};
/* harmony default export */ var transforms_zoom = (zoom_zoom);
function zoom_onDelta(model, selCmpt, proj, size, signals) {
var _a;
const name = selCmpt.name;
const channel = proj.channel;
const hasScales = transforms_scales.has(selCmpt);
const signal = signals.filter(s => s.name === proj.signals[hasScales ? 'data' : 'visual'])[0];
const sizeSg = model.getSizeSignalRef(size).signal;
const scaleCmpt = model.getScaleComponent(channel);
const scaleType = scaleCmpt.get('type');
const base = hasScales ? scales_domain(model, channel) : signal.name;
const delta = name + zoom_DELTA;
const anchor = `${name}${zoom_ANCHOR}.${channel}`;
const zoomFn = !hasScales
? 'zoomLinear'
: scaleType === 'log'
? 'zoomLog'
: scaleType === 'pow'
? 'zoomPow'
: 'zoomLinear';
const update = `${zoomFn}(${base}, ${anchor}, ${delta}` +
(hasScales && scaleType === 'pow' ? `, ${_a = scaleCmpt.get('exponent'), (_a !== null && _a !== void 0 ? _a : 1)}` : '') +
')';
signal.on.push({
events: { signal: delta },
update: hasScales ? update : `clampRange(${update}, 0, ${sizeSg})`
});
}
//# sourceMappingURL=zoom.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/transforms/transforms.js
const transforms_compilers = [transforms_project, transforms_toggle, transforms_scales, transforms_legends, transforms_translate, transforms_zoom, transforms_inputs, transforms_nearest, transforms_clear];
function transforms_forEachTransform(selCmpt, cb) {
for (const t of transforms_compilers) {
if (t.has(selCmpt)) {
cb(t);
}
}
}
//# sourceMappingURL=transforms.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/assemble.js
function assemble_assembleInit(init, isExpr = true, wrap = accessors_identity) {
if (isArray(init)) {
const assembled = init.map(v => assemble_assembleInit(v, isExpr, wrap));
return isExpr ? `[${assembled.join(', ')}]` : assembled;
}
else if (datetime_isDateTime(init)) {
return wrap(datetime_dateTimeExpr(init, false, !isExpr));
}
return isExpr ? wrap(JSON.stringify(init)) : init;
}
function assemble_assembleUnitSelectionSignals(model, signals) {
selection_forEachSelection(model, (selCmpt, selCompiler) => {
const name = selCmpt.name;
let modifyExpr = selCompiler.modifyExpr(model, selCmpt);
signals.push(...selCompiler.signals(model, selCmpt));
transforms_forEachTransform(selCmpt, txCompiler => {
if (txCompiler.signals) {
signals = txCompiler.signals(model, selCmpt, signals);
}
if (txCompiler.modifyExpr) {
modifyExpr = txCompiler.modifyExpr(model, selCmpt, modifyExpr);
}
});
signals.push({
name: name + selection_MODIFY,
on: [
{
events: { signal: selCmpt.name + selection_TUPLE },
update: `modify(${stringValue_$(selCmpt.name + selection_STORE)}, ${modifyExpr})`
}
]
});
});
return assemble_cleanupEmptyOnArray(signals);
}
function assemble_assembleFacetSignals(model, signals) {
if (model.component.selection && util_keys(model.component.selection).length) {
const name = stringValue_$(model.getName('cell'));
signals.unshift({
name: 'facet',
value: {},
on: [
{
events: event_selector('mousemove', 'scope'),
update: `isTuple(facet) ? facet : group(${name}).datum`
}
]
});
}
return assemble_cleanupEmptyOnArray(signals);
}
function assemble_assembleTopLevelSignals(model, signals) {
let hasSelections = false;
selection_forEachSelection(model, (selCmpt, selCompiler) => {
const name = selCmpt.name;
const store = stringValue_$(name + selection_STORE);
const hasSg = signals.filter(s => s.name === name);
if (hasSg.length === 0) {
const resolve = selCmpt.resolve === 'global' ? 'union' : selCmpt.resolve;
const isMulti = selCmpt.type === 'multi' ? ', true)' : ')';
signals.push({
name: selCmpt.name,
update: `${selection_VL_SELECTION_RESOLVE}(${store}, ${stringValue_$(resolve)}${isMulti}`
});
}
hasSelections = true;
if (selCompiler.topLevelSignals) {
signals = selCompiler.topLevelSignals(model, selCmpt, signals);
}
transforms_forEachTransform(selCmpt, txCompiler => {
if (txCompiler.topLevelSignals) {
signals = txCompiler.topLevelSignals(model, selCmpt, signals);
}
});
});
if (hasSelections) {
const hasUnit = signals.filter(s => s.name === 'unit');
if (hasUnit.length === 0) {
signals.unshift({
name: 'unit',
value: {},
on: [{ events: 'mousemove', update: 'isTuple(group()) ? group() : unit' }]
});
}
}
return assemble_cleanupEmptyOnArray(signals);
}
function assemble_assembleUnitSelectionData(model, data) {
const dataCopy = [...data];
selection_forEachSelection(model, selCmpt => {
const init = { name: selCmpt.name + selection_STORE };
if (selCmpt.init) {
const fields = selCmpt.project.items.map(proj => {
const { signals } = proj, rest = tslib_es6_rest(proj, ["signals"]);
return rest;
});
const insert = selCmpt.init.map(i => assemble_assembleInit(i, false));
init.values =
selCmpt.type === 'interval'
? [{ unit: selection_unitName(model, { escape: false }), fields, values: insert }]
: insert.map(i => ({ unit: selection_unitName(model, { escape: false }), fields, values: i }));
}
const contains = dataCopy.filter(d => d.name === selCmpt.name + selection_STORE);
if (!contains.length) {
dataCopy.push(init);
}
});
return dataCopy;
}
function assemble_assembleUnitSelectionMarks(model, marks) {
selection_forEachSelection(model, (selCmpt, selCompiler) => {
marks = selCompiler.marks ? selCompiler.marks(model, selCmpt, marks) : marks;
transforms_forEachTransform(selCmpt, txCompiler => {
if (txCompiler.marks) {
marks = txCompiler.marks(model, selCmpt, marks);
}
});
});
return marks;
}
function assemble_assembleLayerSelectionMarks(model, marks) {
for (const child of model.children) {
if (model_isUnitModel(child)) {
marks = assemble_assembleUnitSelectionMarks(child, marks);
}
}
return marks;
}
function assemble_assembleSelectionScaleDomain(model, extent) {
const name = extent.selection;
const selCmpt = model.getSelectionComponent(name, util_varName(name));
return { signal: parse_parseSelectionBinExtent(selCmpt, extent) };
}
function assemble_cleanupEmptyOnArray(signals) {
return signals.map(s => {
if (s.on && !s.on.length)
delete s.on;
return s;
});
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/interval.js
const interval_BRUSH = '_brush';
const interval_SCALE_TRIGGER = '_scale_trigger';
const interval_interval = {
signals: (model, selCmpt) => {
const name = selCmpt.name;
const fieldsSg = name + project_TUPLE_FIELDS;
const hasScales = transforms_scales.has(selCmpt);
const signals = [];
const dataSignals = [];
const scaleTriggers = [];
if (selCmpt.translate && !hasScales) {
const filterExpr = `!event.item || event.item.mark.name !== ${stringValue_$(name + interval_BRUSH)}`;
interval_events(selCmpt, (on, evt) => {
var _a;
const filters = vega_util_src_array((_a = evt.between[0].filter, (_a !== null && _a !== void 0 ? _a : (evt.between[0].filter = []))));
if (filters.indexOf(filterExpr) < 0) {
filters.push(filterExpr);
}
return on;
});
}
selCmpt.project.items.forEach((proj, i) => {
const channel = proj.channel;
if (channel !== channel_X && channel !== channel_Y) {
src_log_warn('Interval selections only support x and y encoding channels.');
return;
}
const init = selCmpt.init ? selCmpt.init[i] : null;
const cs = interval_channelSignals(model, selCmpt, proj, init);
const dname = proj.signals.data;
const vname = proj.signals.visual;
const scaleName = stringValue_$(model.scaleName(channel));
const scaleType = model.getScaleComponent(channel).get('type');
const toNum = scale_hasContinuousDomain(scaleType) ? '+' : '';
signals.push(...cs);
dataSignals.push(dname);
scaleTriggers.push({
scaleName: model.scaleName(channel),
expr: `(!isArray(${dname}) || ` +
`(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` +
`${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`
});
});
// Proxy scale reactions to ensure that an infinite loop doesn't occur
// when an interval selection filter touches the scale.
if (!hasScales) {
signals.push({
name: name + interval_SCALE_TRIGGER,
value: {},
on: [
{
events: scaleTriggers.map(t => ({ scale: t.scaleName })),
update: scaleTriggers.map(t => t.expr).join(' && ') + ` ? ${name + interval_SCALE_TRIGGER} : {}`
}
]
});
}
// Only add an interval to the store if it has valid data extents. Data extents
// are set to null if pixel extents are equal to account for intervals over
// ordinal/nominal domains which, when inverted, will still produce a valid datum.
const init = selCmpt.init;
const update = `unit: ${selection_unitName(model)}, fields: ${fieldsSg}, values`;
return signals.concat(Object.assign(Object.assign({ name: name + selection_TUPLE }, (init ? { init: `{${update}: ${assemble_assembleInit(init)}}` } : {})), { on: [
{
events: [{ signal: dataSignals.join(' || ') }],
update: dataSignals.join(' && ') + ` ? {${update}: [${dataSignals}]} : null`
}
] }));
},
modifyExpr: (model, selCmpt) => {
const tpl = selCmpt.name + selection_TUPLE;
return tpl + ', ' + (selCmpt.resolve === 'global' ? 'true' : `{unit: ${selection_unitName(model)}}`);
},
marks: (model, selCmpt, marks) => {
const name = selCmpt.name;
const { x, y } = selCmpt.project.hasChannel;
const xvname = x && x.signals.visual;
const yvname = y && y.signals.visual;
const store = `data(${stringValue_$(selCmpt.name + selection_STORE)})`;
// Do not add a brush if we're binding to scales.
if (transforms_scales.has(selCmpt)) {
return marks;
}
const update = {
x: x !== undefined ? { signal: `${xvname}[0]` } : { value: 0 },
y: y !== undefined ? { signal: `${yvname}[0]` } : { value: 0 },
x2: x !== undefined ? { signal: `${xvname}[1]` } : { field: { group: 'width' } },
y2: y !== undefined ? { signal: `${yvname}[1]` } : { field: { group: 'height' } }
};
// If the selection is resolved to global, only a single interval is in
// the store. Wrap brush mark's encodings with a production rule to test
// this based on the `unit` property. Hide the brush mark if it corresponds
// to a unit different from the one in the store.
if (selCmpt.resolve === 'global') {
for (const key of util_keys(update)) {
update[key] = [
Object.assign({ test: `${store}.length && ${store}[0].unit === ${selection_unitName(model)}` }, update[key]),
{ value: 0 }
];
}
}
// Two brush marks ensure that fill colors and other aesthetic choices do
// not interefere with the core marks, but that the brushed region can still
// be interacted with (e.g., dragging it around).
const _a = selCmpt.mark, { fill, fillOpacity } = _a, stroke = tslib_es6_rest(_a, ["fill", "fillOpacity"]);
const vgStroke = util_keys(stroke).reduce((def, k) => {
def[k] = [
{
test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`]
.filter(t => t)
.join(' && '),
value: stroke[k]
},
{ value: null }
];
return def;
}, {});
return [
{
name: name + interval_BRUSH + '_bg',
type: 'rect',
clip: true,
encode: {
enter: {
fill: { value: fill },
fillOpacity: { value: fillOpacity }
},
update: update
}
},
...marks,
{
name: name + interval_BRUSH,
type: 'rect',
clip: true,
encode: {
enter: {
fill: { value: 'transparent' }
},
update: Object.assign(Object.assign({}, update), vgStroke)
}
}
];
}
};
/* harmony default export */ var selection_interval = (interval_interval);
/**
* Returns the visual and data signals for an interval selection.
*/
function interval_channelSignals(model, selCmpt, proj, init) {
const channel = proj.channel;
const vname = proj.signals.visual;
const dname = proj.signals.data;
const hasScales = transforms_scales.has(selCmpt);
const scaleName = stringValue_$(model.scaleName(channel));
const scale = model.getScaleComponent(channel);
const scaleType = scale ? scale.get('type') : undefined;
const scaled = (str) => `scale(${scaleName}, ${str})`;
const size = model.getSizeSignalRef(channel === channel_X ? 'width' : 'height').signal;
const coord = `${channel}(unit)`;
const on = interval_events(selCmpt, (def, evt) => {
return [
...def,
{ events: evt.between[0], update: `[${coord}, ${coord}]` },
{ events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]` } // Brush End
];
});
// React to pan/zooms of continuous scales. Non-continuous scales
// (band, point) cannot be pan/zoomed and any other changes
// to their domains (e.g., filtering) should clear the brushes.
on.push({
events: { signal: selCmpt.name + interval_SCALE_TRIGGER },
update: scale_hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`
});
return hasScales
? [{ name: dname, on: [] }]
: [
Object.assign(Object.assign({ name: vname }, (init ? { init: assemble_assembleInit(init, true, scaled) } : { value: [] })), { on: on }),
Object.assign(Object.assign({ name: dname }, (init ? { init: assemble_assembleInit(init) } : {})), { on: [
{
events: { signal: vname },
update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`
}
] })
];
}
function interval_events(selCmpt, cb) {
return selCmpt.events.reduce((on, evt) => {
if (!evt.between) {
src_log_warn(`${evt} is not an ordered event stream for interval selections.`);
return on;
}
return cb(on, evt);
}, []);
}
//# sourceMappingURL=interval.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/multi.js
function multi_singleOrMultiSignals(model, selCmpt) {
const name = selCmpt.name;
const fieldsSg = name + project_TUPLE_FIELDS;
const project = selCmpt.project;
const datum = '(item().isVoronoi ? datum.datum : datum)';
const values = project.items
.map(p => {
const fieldDef = model.fieldDef(p.channel);
// Binned fields should capture extents, for a range test against the raw field.
return fieldDef && fieldDef.bin
? `[${datum}[${stringValue_$(model.vgField(p.channel, {}))}], ` +
`${datum}[${stringValue_$(model.vgField(p.channel, { binSuffix: 'end' }))}]]`
: `${datum}[${stringValue_$(p.field)}]`;
})
.join(', ');
// Only add a discrete selection to the store if a datum is present _and_
// the interaction isn't occurring on a group mark. This guards against
// polluting interactive state with invalid values in faceted displays
// as the group marks are also data-driven. We force the update to account
// for constant null states but varying toggles (e.g., shift-click in
// whitespace followed by a click in whitespace; the store should only
// be cleared on the second click).
const update = `unit: ${selection_unitName(model)}, fields: ${fieldsSg}, values`;
const events = selCmpt.events;
return [
{
name: name + selection_TUPLE,
on: events
? [
{
events,
update: `datum && item().mark.marktype !== 'group' ? {${update}: [${values}]} : null`,
force: true
}
]
: []
}
];
}
const multi_multi = {
signals: multi_singleOrMultiSignals,
modifyExpr: (model, selCmpt) => {
const tpl = selCmpt.name + selection_TUPLE;
return tpl + ', ' + (selCmpt.resolve === 'global' ? 'null' : `{unit: ${selection_unitName(model)}}`);
}
};
/* harmony default export */ var selection_multi = (multi_multi);
//# sourceMappingURL=multi.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/single.js
const single_single = {
signals: multi_singleOrMultiSignals,
modifyExpr: (model, selCmpt) => {
const tpl = selCmpt.name + selection_TUPLE;
return tpl + ', ' + (selCmpt.resolve === 'global' ? 'true' : `{unit: ${selection_unitName(model)}}`);
}
};
/* harmony default export */ var selection_single = (single_single);
//# sourceMappingURL=single.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/index.js
const selection_STORE = '_store';
const selection_TUPLE = '_tuple';
const selection_MODIFY = '_modify';
const selection_SELECTION_DOMAIN = '_selection_domain_';
const selection_VL_SELECTION_RESOLVE = 'vlSelectionResolve';
const selection_compilers = { single: selection_single, multi: selection_multi, interval: selection_interval };
function selection_forEachSelection(model, cb) {
const selections = model.component.selection;
if (selections) {
for (const name in selections) {
if (src_hasOwnProperty(selections, name)) {
const sel = selections[name];
const success = cb(sel, selection_compilers[sel.type]);
if (success === true)
break;
}
}
}
}
function selection_getFacetModel(model) {
let parent = model.parent;
while (parent) {
if (model_isFacetModel(parent)) {
break;
}
parent = parent.parent;
}
return parent;
}
function selection_unitName(model, { escape } = { escape: true }) {
let name = escape ? stringValue_$(model.name) : model.name;
const facetModel = selection_getFacetModel(model);
if (facetModel) {
const { facet } = facetModel;
for (const channel of channel_FACET_CHANNELS) {
if (facet[channel]) {
name += ` + '__facet_${channel}_' + (facet[${stringValue_$(facetModel.vgField(channel))}])`;
}
}
}
return name;
}
function selection_requiresSelectionId(model) {
let identifier = false;
selection_forEachSelection(model, selCmpt => {
identifier = identifier || selCmpt.project.items.some(proj => proj.field === selection_SELECTION_ID);
});
return identifier;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/expressions.js
function expressions_getName(node) {
const name = [];
if (node.type === 'Identifier') {
return [node.name];
}
if (node.type === 'Literal') {
return [node.value];
}
if (node.type === 'MemberExpression') {
name.push(...expressions_getName(node.object));
name.push(...expressions_getName(node.property));
}
return name;
}
function expressions_startsWithDatum(node) {
if (node.object.type === 'MemberExpression') {
return expressions_startsWithDatum(node.object);
}
return node.object.name === 'datum';
}
function expressions_getDependentFields(expression) {
const ast = parser(expression);
const dependents = new Set();
ast.visit((node) => {
if (node.type === 'MemberExpression' && expressions_startsWithDatum(node)) {
dependents.add(expressions_getName(node)
.slice(1)
.join('.'));
}
});
return dependents;
}
//# sourceMappingURL=expressions.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/filter.js
class filter_FilterNode extends dataflow_DataFlowNode {
constructor(parent, model, filter) {
super(parent);
this.model = model;
this.filter = filter;
// TODO: refactor this to not take a node and
// then add a static function makeFromOperand and make the constructor take only an expression
this.expr = predicate_expression(this.model, this.filter, this);
this._dependentFields = expressions_getDependentFields(this.expr);
}
clone() {
return new filter_FilterNode(null, this.model, util_duplicate(this.filter));
}
dependentFields() {
return this._dependentFields;
}
producedFields() {
return new Set(); // filter does not produce any new fields
}
assemble() {
return {
type: 'filter',
expr: this.expr
};
}
hash() {
return `Filter ${this.expr}`;
}
}
//# sourceMappingURL=filter.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/selection/parse.js
function parse_parseUnitSelection(model, selDefs) {
var _a;
const selCmpts = {};
const selectionConfig = model.config.selection;
for (const name in selDefs) {
if (!src_hasOwnProperty(selDefs, name)) {
continue;
}
const selDef = util_duplicate(selDefs[name]);
const _b = selectionConfig[selDef.type], { fields, encodings } = _b, cfg = tslib_es6_rest(_b, ["fields", "encodings"]); // Project transform applies its defaults.
// Set default values from config if a property hasn't been specified,
// or if it is true. E.g., "translate": true should use the default
// event handlers for translate. However, true may be a valid value for
// a property (e.g., "nearest": true).
for (const key in cfg) {
// A selection should contain either `encodings` or `fields`, only use
// default values for these two values if neither of them is specified.
if ((key === 'encodings' && selDef.fields) || (key === 'fields' && selDef.encodings)) {
continue;
}
if (key === 'mark') {
selDef[key] = Object.assign(Object.assign({}, cfg[key]), selDef[key]);
}
if (selDef[key] === undefined || selDef[key] === true) {
selDef[key] = (_a = cfg[key], (_a !== null && _a !== void 0 ? _a : selDef[key]));
}
}
const safeName = util_varName(name);
const selCmpt = (selCmpts[safeName] = Object.assign(Object.assign({}, selDef), { name: safeName, events: isString(selDef.on) ? event_selector(selDef.on, 'scope') : util_duplicate(selDef.on) }));
transforms_forEachTransform(selCmpt, txCompiler => {
if (txCompiler.has(selCmpt) && txCompiler.parse) {
txCompiler.parse(model, selCmpt, selDef, selDefs[name]);
}
});
}
return selCmpts;
}
function parse_parseSelectionPredicate(model, selections, dfnode, datum = 'datum') {
const stores = [];
function expr(name) {
const vname = util_varName(name);
const selCmpt = model.getSelectionComponent(vname, name);
const store = stringValue_$(vname + selection_STORE);
if (selCmpt.project.timeUnit) {
const child = (dfnode !== null && dfnode !== void 0 ? dfnode : model.component.data.raw);
const tunode = selCmpt.project.timeUnit.clone();
if (child.parent) {
tunode.insertAsParentOf(child);
}
else {
child.parent = tunode;
}
}
if (selCmpt.empty !== 'none') {
stores.push(store);
}
return (`vlSelectionTest(${store}, ${datum}` + (selCmpt.resolve === 'global' ? ')' : `, ${stringValue_$(selCmpt.resolve)})`));
}
const predicateStr = util_logicalExpr(selections, expr);
return ((stores.length ? '!(' + stores.map(s => `length(data(${s}))`).join(' || ') + ') || ' : '') + `(${predicateStr})`);
}
function parse_parseSelectionBinExtent(selCmpt, extent) {
const encoding = extent['encoding'];
let field = extent['field'];
if (!encoding && !field) {
field = selCmpt.project.items[0].field;
if (selCmpt.project.items.length > 1) {
src_log_warn('A "field" or "encoding" must be specified when using a selection as a scale domain. ' +
`Using "field": ${stringValue_$(field)}.`);
}
}
else if (encoding && !field) {
const encodings = selCmpt.project.items.filter(p => p.channel === encoding);
if (!encodings.length || encodings.length > 1) {
field = selCmpt.project.items[0].field;
src_log_warn((!encodings.length ? 'No ' : 'Multiple ') +
`matching ${stringValue_$(encoding)} encoding found for selection ${stringValue_$(extent.selection)}. ` +
`Using "field": ${stringValue_$(field)}.`);
}
else {
field = encodings[0].field;
}
}
return `${selCmpt.name}[${stringValue_$(field)}]`;
}
function parse_materializeSelections(model, main) {
selection_forEachSelection(model, selCmpt => {
const selection = selCmpt.name;
const lookupName = model.getName(`lookup_${selection}`);
model.component.data.outputNodes[lookupName] = selCmpt.materialized = new dataflow_OutputNode(new filter_FilterNode(main, model, { selection }), lookupName, 'lookup', model.component.data.outputNodeRefCounts);
});
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/predicate.js
/**
* Converts a predicate into an expression.
*/
// model is only used for selection filters.
function predicate_expression(model, filterOp, node) {
return util_logicalExpr(filterOp, (predicate) => {
if (isString(predicate)) {
return predicate;
}
else if (predicate_isSelectionPredicate(predicate)) {
return parse_parseSelectionPredicate(model, predicate.selection, node);
}
else {
// Filter Object
return predicate_fieldFilterExpression(predicate);
}
});
}
//# sourceMappingURL=predicate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/axis/assemble.js
function assemble_assembleTitle(title, config) {
if (!title) {
return undefined;
}
if (!title_isText(title)) {
return title.map(fieldDef => channeldef_defaultTitle(fieldDef, config)).join(', ');
}
return title;
}
function assemble_setAxisEncode(axis, part, vgProp, vgRef) {
var _a, _b, _c;
axis.encode = (_a = axis.encode, (_a !== null && _a !== void 0 ? _a : {}));
axis.encode[part] = (_b = axis.encode[part], (_b !== null && _b !== void 0 ? _b : {}));
axis.encode[part].update = (_c = axis.encode[part].update, (_c !== null && _c !== void 0 ? _c : {}));
// TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
axis.encode[part].update[vgProp] = vgRef;
}
function assemble_assembleAxis(axisCmpt, kind, config, opt = { header: false }) {
var _a, _b;
const _c = axisCmpt.combine(), { orient, scale, labelExpr, title, zindex } = _c, axis = tslib_es6_rest(_c, ["orient", "scale", "labelExpr", "title", "zindex"]);
// Remove properties that are not valid for this kind of axis
util_keys(axis).forEach(prop => {
const propType = axis_AXIS_PROPERTY_TYPE[prop];
const propValue = axis[prop];
if (propType && propType !== kind && propType !== 'both') {
delete axis[prop];
}
else if (axis_isConditionalAxisValue(propValue)) {
const { vgProp, part } = axis_CONDITIONAL_AXIS_PROP_INDEX[prop];
const { condition, value } = propValue;
const vgRef = [
...(isArray(condition) ? condition : [condition]).map(c => {
const { value: v, test } = c;
return {
test: predicate_expression(null, test),
value: v
};
}),
{ value }
];
assemble_setAxisEncode(axis, part, vgProp, vgRef);
delete axis[prop];
}
});
if (kind === 'grid') {
if (!axis.grid) {
return undefined;
}
// Remove unnecessary encode block
if (axis.encode) {
// Only need to keep encode block for grid
const { grid } = axis.encode;
axis.encode = Object.assign({}, (grid ? { grid } : {}));
if (util_keys(axis.encode).length === 0) {
delete axis.encode;
}
}
return Object.assign(Object.assign({ scale,
orient }, axis), { domain: false, labels: false,
// Always set min/maxExtent to 0 to ensure that `config.axis*.minExtent` and `config.axis*.maxExtent`
// would not affect gridAxis
maxExtent: 0, minExtent: 0, ticks: false, zindex: util_getFirstDefined(zindex, 0) // put grid behind marks by default
});
}
else {
// kind === 'main'
if (!opt.header && axisCmpt.mainExtracted) {
// if mainExtracted has been extracted to a separate facet
return undefined;
}
if (labelExpr !== undefined) {
let expr = labelExpr;
if (((_b = (_a = axis.encode) === null || _a === void 0 ? void 0 : _a.labels) === null || _b === void 0 ? void 0 : _b.update) && vega_schema_isSignalRef(axis.encode.labels.update.text)) {
expr = util_replaceAll(labelExpr, 'datum.label', axis.encode.labels.update.text.signal);
}
assemble_setAxisEncode(axis, 'labels', 'text', { signal: expr });
}
// Remove unnecessary encode block
if (axis.encode) {
for (const part of axis_AXIS_PARTS) {
if (!axisCmpt.hasAxisPart(part)) {
delete axis.encode[part];
}
}
if (util_keys(axis.encode).length === 0) {
delete axis.encode;
}
}
const titleString = assemble_assembleTitle(title, config);
return Object.assign(Object.assign(Object.assign({ scale,
orient, grid: false }, (titleString ? { title: titleString } : {})), axis), { zindex: util_getFirstDefined(zindex, 0) // put axis line above marks by default
});
}
}
/**
* Add axis signals so grid line works correctly
* (Fix https://github.com/vega/vega-lite/issues/4226)
*/
function assemble_assembleAxisSignals(model) {
const { axes } = model.component;
for (const channel of channel_POSITION_SCALE_CHANNELS) {
if (axes[channel]) {
for (const axis of axes[channel]) {
if (!axis.get('gridScale')) {
// If there is x-axis but no y-scale for gridScale, need to set height/weight so x-axis can draw the grid with the right height. Same for y-axis and width.
const sizeType = channel === 'x' ? 'height' : 'width';
return [
{
name: sizeType,
update: model.getSizeSignalRef(sizeType).signal
}
];
}
}
}
}
return [];
}
function assemble_assembleAxes(axisComponents, config) {
const { x = [], y = [] } = axisComponents;
return [
...x.map(a => assemble_assembleAxis(a, 'grid', config)),
...y.map(a => assemble_assembleAxis(a, 'grid', config)),
...x.map(a => assemble_assembleAxis(a, 'main', config)),
...y.map(a => assemble_assembleAxis(a, 'main', config))
].filter(a => a); // filter undefined
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/header.js
const header_HEADER_TITLE_PROPERTIES_MAP = {
titleAlign: 'align',
titleAnchor: 'anchor',
titleAngle: 'angle',
titleBaseline: 'baseline',
titleColor: 'color',
titleFont: 'font',
titleFontSize: 'fontSize',
titleFontStyle: 'fontStyle',
titleFontWeight: 'fontWeight',
titleLimit: 'limit',
titleLineHeight: 'lineHeight',
titleOrient: 'orient',
titlePadding: 'offset'
};
const header_HEADER_LABEL_PROPERTIES_MAP = {
labelAlign: 'align',
labelAnchor: 'anchor',
labelAngle: 'angle',
labelColor: 'color',
labelFont: 'font',
labelFontSize: 'fontSize',
labelFontStyle: 'fontStyle',
labelLimit: 'limit',
labelOrient: 'orient',
labelPadding: 'offset'
};
const header_HEADER_TITLE_PROPERTIES = util_keys(header_HEADER_TITLE_PROPERTIES_MAP);
const header_HEADER_LABEL_PROPERTIES = util_keys(header_HEADER_LABEL_PROPERTIES_MAP);
//# sourceMappingURL=header.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/axis/config.js
function getAxisConfig(property, config, channel, orient, scaleType) {
var _a;
// configTypes to loop, starting from higher precedence
const configTypes = [
...(scaleType === 'band' ? ['axisBand'] : []),
channel === 'x' ? 'axisX' : 'axisY',
// axisTop, axisBottom, ...
...(orient ? ['axis' + orient.substr(0, 1).toUpperCase() + orient.substr(1)] : []),
'axis'
];
for (const configType of configTypes) {
if (((_a = config[configType]) === null || _a === void 0 ? void 0 : _a[property]) !== undefined) {
return config[configType][property];
}
}
return undefined;
}
//# sourceMappingURL=config.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/axis/properties.js
// TODO: we need to refactor this method after we take care of config refactoring
/**
* Default rules for whether to show a grid should be shown for a channel.
* If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned
*/
function properties_defaultGrid(scaleType, fieldDef) {
return !scale_hasDiscreteDomain(scaleType) && !bin_isBinning(fieldDef.bin);
}
function properties_gridScale(model, channel) {
const gridChannel = channel === 'x' ? 'y' : 'x';
if (model.getScaleComponent(gridChannel)) {
return model.scaleName(gridChannel);
}
return undefined;
}
function properties_labelAngle(model, specifiedAxis, channel, fieldDef) {
// try axis value
if (specifiedAxis.labelAngle !== undefined) {
return util_normalizeAngle(specifiedAxis.labelAngle);
}
else {
// try axis config value
const angle = getAxisConfig('labelAngle', model.config, channel, properties_orient(channel), model.getScaleComponent(channel).get('type'));
if (angle !== undefined) {
return util_normalizeAngle(angle);
}
else {
// get default value
if (channel === channel_X && util_contains([NOMINAL, ORDINAL], fieldDef.type)) {
return 270;
}
// no default
return undefined;
}
}
}
function properties_defaultLabelBaseline(angle, axisOrient) {
if (angle !== undefined) {
angle = util_normalizeAngle(angle);
if (axisOrient === 'top' || axisOrient === 'bottom') {
if (angle <= 45 || 315 <= angle) {
return axisOrient === 'top' ? 'bottom' : 'top';
}
else if (135 <= angle && angle <= 225) {
return axisOrient === 'top' ? 'top' : 'bottom';
}
else {
return 'middle';
}
}
else {
if (angle <= 45 || 315 <= angle || (135 <= angle && angle <= 225)) {
return 'middle';
}
else if (45 <= angle && angle <= 135) {
return axisOrient === 'left' ? 'top' : 'bottom';
}
else {
return axisOrient === 'left' ? 'bottom' : 'top';
}
}
}
return undefined;
}
function properties_defaultLabelAlign(angle, axisOrient) {
if (angle !== undefined) {
angle = util_normalizeAngle(angle);
if (axisOrient === 'top' || axisOrient === 'bottom') {
if (angle % 180 === 0) {
return 'center';
}
else if (0 < angle && angle < 180) {
return axisOrient === 'top' ? 'right' : 'left';
}
else {
return axisOrient === 'top' ? 'left' : 'right';
}
}
else {
if ((angle + 90) % 180 === 0) {
return 'center';
}
else if (90 <= angle && angle < 270) {
return axisOrient === 'left' ? 'left' : 'right';
}
else {
return axisOrient === 'left' ? 'right' : 'left';
}
}
}
return undefined;
}
function properties_defaultLabelFlush(fieldDef, channel) {
if (channel === 'x' && util_contains(['quantitative', 'temporal'], fieldDef.type)) {
return true;
}
return undefined;
}
function properties_defaultLabelOverlap(fieldDef, scaleType) {
// do not prevent overlap for nominal data because there is no way to infer what the missing labels are
if (fieldDef.type !== 'nominal') {
if (scaleType === 'log') {
return 'greedy';
}
return true;
}
return undefined;
}
function properties_orient(channel) {
switch (channel) {
case channel_X:
return 'bottom';
case channel_Y:
return 'left';
}
/* istanbul ignore next: This should never happen. */
throw new Error(log_message.INVALID_CHANNEL_FOR_AXIS);
}
function properties_defaultTickCount({ fieldDef, scaleType, size }) {
if (!scale_hasDiscreteDomain(scaleType) &&
scaleType !== 'log' &&
!util_contains(['month', 'hours', 'day', 'quarter'], fieldDef.timeUnit)) {
if (bin_isBinning(fieldDef.bin)) {
// for binned data, we don't want more ticks than maxbins
return { signal: `ceil(${size.signal}/10)` };
}
return { signal: `ceil(${size.signal}/40)` };
}
return undefined;
}
function properties_values(specifiedAxis, model, fieldDef) {
const vals = specifiedAxis.values;
if (vals) {
return channeldef_valueArray(fieldDef, vals);
}
return undefined;
}
function properties_defaultZindex(mark, fieldDef) {
if (mark === 'rect' && channeldef_isDiscrete(fieldDef)) {
return 1;
}
return 0;
}
//# sourceMappingURL=properties.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/calculate.js
class calculate_CalculateNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
this._dependentFields = expressions_getDependentFields(this.transform.calculate);
}
clone() {
return new calculate_CalculateNode(null, util_duplicate(this.transform));
}
static parseAllForSortIndex(parent, model) {
// get all the encoding with sort fields from model
model.forEachFieldDef((fieldDef, channel) => {
if (!channeldef_isScaleFieldDef(fieldDef)) {
return;
}
if (sort_isSortArray(fieldDef.sort)) {
const { field, timeUnit } = fieldDef;
const sort = fieldDef.sort;
// generate `datum["a"] === val0 ? 0 : datum["a"] === val1 ? 1 : ... : n` via FieldEqualPredicate
const calculate = sort
.map((sortValue, i) => {
return `${predicate_fieldFilterExpression({ field, timeUnit, equal: sortValue })} ? ${i} : `;
})
.join('') + sort.length;
parent = new calculate_CalculateNode(parent, {
calculate,
as: calculate_sortArrayIndexField(fieldDef, channel, { forAs: true })
});
}
});
return parent;
}
producedFields() {
return new Set([this.transform.as]);
}
dependentFields() {
return this._dependentFields;
}
assemble() {
return {
type: 'formula',
expr: this.transform.calculate,
as: this.transform.as
};
}
hash() {
return `Calculate ${util_hash(this.transform)}`;
}
}
function calculate_sortArrayIndexField(fieldDef, channel, opt) {
return channeldef_vgField(fieldDef, Object.assign({ prefix: channel, suffix: 'sort_index' }, ((opt !== null && opt !== void 0 ? opt : {}))));
}
//# sourceMappingURL=calculate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/header/common.js
/**
* Get header channel, which can be different from facet channel when orient is specified or when the facet channel is facet.
*/
function common_getHeaderChannel(channel, orient) {
if (util_contains(['top', 'bottom'], orient)) {
return 'column';
}
else if (util_contains(['left', 'right'], orient)) {
return 'row';
}
return channel === 'row' ? 'row' : 'column';
}
function common_getHeaderProperty(prop, facetFieldDef, config, channel) {
const headerSpecificConfig = channel === 'row' ? config.headerRow : channel === 'column' ? config.headerColumn : config.headerFacet;
return util_getFirstDefined(facetFieldDef && facetFieldDef.header ? facetFieldDef.header[prop] : undefined, headerSpecificConfig[prop], config.header[prop]);
}
function common_getHeaderProperties(properties, facetFieldDef, config, channel) {
const props = {};
for (const prop of properties) {
const value = common_getHeaderProperty(prop, facetFieldDef, config, channel);
if (value !== undefined) {
props[prop] = value;
}
}
return props;
}
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/header/component.js
const HEADER_CHANNELS = ['row', 'column'];
const HEADER_TYPES = ['header', 'footer'];
//# sourceMappingURL=component.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/header/assemble.js
// TODO: rename to assembleHeaderTitleGroup
function assemble_assembleTitleGroup(model, channel) {
const title = model.component.layoutHeaders[channel].title;
const config = model.config ? model.config : undefined;
const facetFieldDef = model.component.layoutHeaders[channel].facetFieldDef
? model.component.layoutHeaders[channel].facetFieldDef
: undefined;
const { titleAnchor, titleAngle, titleOrient } = common_getHeaderProperties(['titleAnchor', 'titleAngle', 'titleOrient'], facetFieldDef, config, channel);
const headerChannel = common_getHeaderChannel(channel, titleOrient);
return {
name: `${channel}-title`,
type: 'group',
role: `${headerChannel}-title`,
title: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ text: title }, (channel === 'row' ? { orient: 'left' } : {})), { style: 'guide-title' }), assemble_defaultHeaderGuideBaseline(titleAngle, headerChannel)), assemble_defaultHeaderGuideAlign(headerChannel, titleAngle, titleAnchor)), assemble_assembleHeaderProperties(config, facetFieldDef, channel, header_HEADER_TITLE_PROPERTIES, header_HEADER_TITLE_PROPERTIES_MAP))
};
}
function assemble_defaultHeaderGuideAlign(headerChannel, angle, anchor = 'middle') {
switch (anchor) {
case 'start':
return { align: 'left' };
case 'end':
return { align: 'right' };
}
const align = properties_defaultLabelAlign(angle, headerChannel === 'row' ? 'left' : 'top');
return align ? { align } : {};
}
function assemble_defaultHeaderGuideBaseline(angle, channel) {
const baseline = properties_defaultLabelBaseline(angle, channel === 'row' ? 'left' : 'top');
return baseline ? { baseline } : {};
}
function assemble_assembleHeaderGroups(model, channel) {
const layoutHeader = model.component.layoutHeaders[channel];
const groups = [];
for (const headerType of HEADER_TYPES) {
if (layoutHeader[headerType]) {
for (const headerCmpt of layoutHeader[headerType]) {
groups.push(assemble_assembleHeaderGroup(model, channel, headerType, layoutHeader, headerCmpt));
}
}
}
return groups;
}
function assemble_getSort(facetFieldDef, channel) {
var _a;
const { sort } = facetFieldDef;
if (sort_isSortField(sort)) {
return {
field: channeldef_vgField(sort, { expr: 'datum' }),
order: (_a = sort.order, (_a !== null && _a !== void 0 ? _a : 'ascending'))
};
}
else if (isArray(sort)) {
return {
field: calculate_sortArrayIndexField(facetFieldDef, channel, { expr: 'datum' }),
order: 'ascending'
};
}
else {
return {
field: channeldef_vgField(facetFieldDef, { expr: 'datum' }),
order: (sort !== null && sort !== void 0 ? sort : 'ascending')
};
}
}
function assemble_assembleLabelTitle(facetFieldDef, channel, config) {
const { format, labelAngle, labelAnchor, labelOrient, labelExpr } = common_getHeaderProperties(['format', 'labelAngle', 'labelAnchor', 'labelOrient', 'labelExpr'], facetFieldDef, config, channel);
const titleTextExpr = common_formatSignalRef(facetFieldDef, format, 'parent', config).signal;
const headerChannel = common_getHeaderChannel(channel, labelOrient);
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ text: {
signal: labelExpr
? util_replaceAll(util_replaceAll(labelExpr, 'datum.label', titleTextExpr), 'datum.value', channeldef_vgField(facetFieldDef, { expr: 'parent' }))
: titleTextExpr
} }, (channel === 'row' ? { orient: 'left' } : {})), { style: 'guide-label', frame: 'group' }), assemble_defaultHeaderGuideBaseline(labelAngle, headerChannel)), assemble_defaultHeaderGuideAlign(headerChannel, labelAngle, labelAnchor)), assemble_assembleHeaderProperties(config, facetFieldDef, channel, header_HEADER_LABEL_PROPERTIES, header_HEADER_LABEL_PROPERTIES_MAP));
}
function assemble_assembleHeaderGroup(model, channel, headerType, layoutHeader, headerCmpt) {
var _a;
if (headerCmpt) {
let title = null;
const { facetFieldDef } = layoutHeader;
const config = model.config ? model.config : undefined;
if (facetFieldDef && headerCmpt.labels) {
const { labelOrient } = common_getHeaderProperties(['labelOrient'], facetFieldDef, config, channel);
// Include label title in the header if orient aligns with the channel
if ((channel === 'row' && !util_contains(['top', 'bottom'], labelOrient)) ||
(channel === 'column' && !util_contains(['left', 'right'], labelOrient))) {
title = assemble_assembleLabelTitle(facetFieldDef, channel, config);
}
}
const isFacetWithoutRowCol = model_isFacetModel(model) && !isFacetMapping(model.facet);
const axes = headerCmpt.axes;
const hasAxes = ((_a = axes) === null || _a === void 0 ? void 0 : _a.length) > 0;
if (title || hasAxes) {
const sizeChannel = channel === 'row' ? 'height' : 'width';
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: model.getName(`${channel}_${headerType}`), type: 'group', role: `${channel}-${headerType}` }, (layoutHeader.facetFieldDef
? {
from: { data: model.getName(channel + '_domain') },
sort: assemble_getSort(facetFieldDef, channel)
}
: {})), (hasAxes && isFacetWithoutRowCol
? {
from: { data: model.getName(`facet_domain_${channel}`) }
}
: {})), (title ? { title } : {})), (headerCmpt.sizeSignal
? {
encode: {
update: {
[sizeChannel]: headerCmpt.sizeSignal
}
}
}
: {})), (hasAxes ? { axes } : {}));
}
}
return null;
}
const assemble_LAYOUT_TITLE_BAND = {
column: {
start: 0,
end: 1
},
row: {
start: 1,
end: 0
}
};
function assemble_getLayoutTitleBand(titleAnchor, headerChannel) {
return assemble_LAYOUT_TITLE_BAND[headerChannel][titleAnchor];
}
function assemble_assembleLayoutTitleBand(headerComponentIndex, config) {
var _a;
const titleBand = {};
for (const channel of channel_FACET_CHANNELS) {
const headerComponent = headerComponentIndex[channel];
if ((_a = headerComponent) === null || _a === void 0 ? void 0 : _a.facetFieldDef) {
const { titleAnchor, titleOrient } = common_getHeaderProperties(['titleAnchor', 'titleOrient'], headerComponent.facetFieldDef, config, channel);
const headerChannel = common_getHeaderChannel(channel, titleOrient);
const band = assemble_getLayoutTitleBand(titleAnchor, headerChannel);
if (band !== undefined) {
titleBand[headerChannel] = band;
}
}
}
return util_keys(titleBand).length > 0 ? titleBand : undefined;
}
function assemble_assembleHeaderProperties(config, facetFieldDef, channel, properties, propertiesMap) {
const props = {};
for (const prop of properties) {
if (!propertiesMap[prop]) {
continue;
}
const value = common_getHeaderProperty(prop, facetFieldDef, config, channel);
if (value !== undefined) {
props[propertiesMap[prop]] = value;
}
}
return props;
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/layoutsize/assemble.js
function assemble_assembleLayoutSignals(model) {
return [...assemble_sizeSignals(model, 'width'), ...assemble_sizeSignals(model, 'height')];
}
function assemble_sizeSignals(model, sizeType) {
const channel = sizeType === 'width' ? 'x' : 'y';
const size = model.component.layoutSize.get(sizeType);
if (!size || size === 'merged') {
return [];
}
// Read size signal name from name map, just in case it is the top-level size signal that got renamed.
const name = model.getSizeSignalRef(sizeType).signal;
if (size === 'step') {
const scaleComponent = model.getScaleComponent(channel);
if (scaleComponent) {
const type = scaleComponent.get('type');
const range = scaleComponent.get('range');
if (scale_hasDiscreteDomain(type) && vega_schema_isVgRangeStep(range)) {
const scaleName = model.scaleName(channel);
if (model_isFacetModel(model.parent)) {
// If parent is facet and this is an independent scale, return only signal signal
// as the width/height will be calculated using the cardinality from
// facet's aggregate rather than reading from scale domain
const parentResolve = model.parent.component.resolve;
if (parentResolve.scale[channel] === 'independent') {
return [assemble_stepSignal(scaleName, range)];
}
}
return [
assemble_stepSignal(scaleName, range),
{
name,
update: assemble_sizeExpr(scaleName, scaleComponent, `domain('${scaleName}').length`)
}
];
}
}
/* istanbul ignore next: Condition should not happen -- only for warning in development. */
throw new Error('layout size is step although width/height is not step.');
}
else if (size == 'container') {
const isWidth = name.endsWith('width');
const expr = isWidth ? 'containerSize()[0]' : 'containerSize()[1]';
const defaultValue = config_getViewConfigContinuousSize(model.config.view, isWidth ? 'width' : 'height');
const safeExpr = `isFinite(${expr}) ? ${expr} : ${defaultValue}`;
return [{ name, init: safeExpr, on: [{ update: safeExpr, events: 'window:resize' }] }];
}
else {
return [
{
name,
value: size
}
];
}
}
function assemble_stepSignal(scaleName, range) {
return {
name: scaleName + '_step',
value: range.step
};
}
function assemble_sizeExpr(scaleName, scaleComponent, cardinality) {
const type = scaleComponent.get('type');
const padding = scaleComponent.get('padding');
const paddingOuter = util_getFirstDefined(scaleComponent.get('paddingOuter'), padding);
let paddingInner = scaleComponent.get('paddingInner');
paddingInner =
type === 'band'
? // only band has real paddingInner
paddingInner !== undefined
? paddingInner
: padding
: // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128,
// it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points.
1;
return `bandspace(${cardinality}, ${paddingInner}, ${paddingOuter}) * ${scaleName}_step`;
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/guide.js
function guide_guideEncodeEntry(encoding, model) {
return util_keys(encoding).reduce((encode, channel) => {
const valueDef = encoding[channel];
return Object.assign(Object.assign({}, encode), conditional_wrapCondition(model, valueDef, channel, (x) => ({ value: x.value })));
}, {});
}
//# sourceMappingURL=guide.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/resolve.js
function resolve_defaultScaleResolve(channel, model) {
if (model_isLayerModel(model) || model_isFacetModel(model)) {
return 'shared';
}
else if (model_isConcatModel(model) || model_isRepeatModel(model)) {
return util_contains(channel_POSITION_SCALE_CHANNELS, channel) ? 'independent' : 'shared';
}
/* istanbul ignore next: should never reach here. */
throw new Error('invalid model type for resolve');
}
function resolve_parseGuideResolve(resolve, channel) {
const channelScaleResolve = resolve.scale[channel];
const guide = util_contains(channel_POSITION_SCALE_CHANNELS, channel) ? 'axis' : 'legend';
if (channelScaleResolve === 'independent') {
if (resolve[guide][channel] === 'shared') {
src_log_warn(log_message.independentScaleMeansIndependentGuide(channel));
}
return 'independent';
}
return resolve[guide][channel] || 'shared';
}
//# sourceMappingURL=resolve.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/split.js
/**
* Generic class for storing properties that are explicitly specified
* and implicitly determined by the compiler.
* This is important for scale/axis/legend merging as
* we want to prioritize properties that users explicitly specified.
*/
class split_Split {
constructor(explicit = {}, implicit = {}) {
this.explicit = explicit;
this.implicit = implicit;
}
clone() {
return new split_Split(util_duplicate(this.explicit), util_duplicate(this.implicit));
}
combine() {
// FIXME remove "as any".
// Add "as any" to avoid an error "Spread types may only be created from object types".
return Object.assign(Object.assign({}, this.explicit), this.implicit);
}
get(key) {
// Explicit has higher precedence
return util_getFirstDefined(this.explicit[key], this.implicit[key]);
}
getWithExplicit(key) {
// Explicit has higher precedence
if (this.explicit[key] !== undefined) {
return { explicit: true, value: this.explicit[key] };
}
else if (this.implicit[key] !== undefined) {
return { explicit: false, value: this.implicit[key] };
}
return { explicit: false, value: undefined };
}
setWithExplicit(key, value) {
if (value.value !== undefined) {
this.set(key, value.value, value.explicit);
}
}
set(key, value, explicit) {
delete this[explicit ? 'implicit' : 'explicit'][key];
this[explicit ? 'explicit' : 'implicit'][key] = value;
return this;
}
copyKeyFromSplit(key, s) {
// Explicit has higher precedence
if (s.explicit[key] !== undefined) {
this.set(key, s.explicit[key], true);
}
else if (s.implicit[key] !== undefined) {
this.set(key, s.implicit[key], false);
}
}
copyKeyFromObject(key, s) {
// Explicit has higher precedence
if (s[key] !== undefined) {
this.set(key, s[key], true);
}
}
/**
* Merge split object into this split object. Properties from the other split
* overwrite properties from this split.
*/
copyAll(other) {
for (const key of util_keys(other.combine())) {
const val = other.getWithExplicit(key);
this.setWithExplicit(key, val);
}
}
}
function split_makeExplicit(value) {
return {
explicit: true,
value
};
}
function split_makeImplicit(value) {
return {
explicit: false,
value
};
}
function split_tieBreakByComparing(compare) {
return (v1, v2, property, propertyOf) => {
const diff = compare(v1.value, v2.value);
if (diff > 0) {
return v1;
}
else if (diff < 0) {
return v2;
}
return split_defaultTieBreaker(v1, v2, property, propertyOf);
};
}
function split_defaultTieBreaker(v1, v2, property, propertyOf) {
if (v1.explicit && v2.explicit) {
src_log_warn(log_message.mergeConflictingProperty(property, propertyOf, v1.value, v2.value));
}
// If equal score, prefer v1.
return v1;
}
function split_mergeValuesWithExplicit(v1, v2, property, propertyOf, tieBreaker = split_defaultTieBreaker) {
if (v1 === undefined || v1.value === undefined) {
// For first run
return v2;
}
if (v1.explicit && !v2.explicit) {
return v1;
}
else if (v2.explicit && !v1.explicit) {
return v2;
}
else if (util_deepEqual(v1.value, v2.value)) {
return v1;
}
else {
return tieBreaker(v1, v2, property, propertyOf);
}
}
//# sourceMappingURL=split.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/legend/component.js
const component_LEGEND_COMPONENT_PROPERTY_INDEX = Object.assign(Object.assign({}, legend_COMMON_LEGEND_PROPERTY_INDEX), { labelExpr: 1, selections: 1,
// channel scales
opacity: 1, shape: 1, stroke: 1, fill: 1, size: 1, strokeWidth: 1, strokeDash: 1,
// encode
encode: 1 });
const component_LEGEND_COMPONENT_PROPERTIES = util_keys(component_LEGEND_COMPONENT_PROPERTY_INDEX);
class component_LegendComponent extends split_Split {
}
//# sourceMappingURL=component.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/legend/properties.js
function legend_properties_values(legend, fieldDef) {
const vals = legend.values;
if (vals) {
return channeldef_valueArray(fieldDef, vals);
}
return undefined;
}
function properties_defaultSymbolType(mark, channel, shapeChannelDef, markShape) {
var _a;
if (channel !== 'shape') {
// use the value from the shape encoding or the mark config if they exist
const shape = (_a = encode_getFirstConditionValue(shapeChannelDef), (_a !== null && _a !== void 0 ? _a : markShape));
if (shape) {
return shape;
}
}
switch (mark) {
case 'bar':
case 'rect':
case 'image':
case 'square':
return 'square';
case 'line':
case 'trail':
case 'rule':
return 'stroke';
case 'point':
case 'circle':
case 'tick':
case 'geoshape':
case 'area':
case 'text':
return 'circle';
}
}
function properties_clipHeight(legendType) {
if (legendType === 'gradient') {
return 20;
}
return undefined;
}
function properties_type(params) {
const { legend } = params;
return util_getFirstDefined(legend.type, properties_defaultType(params));
}
function properties_defaultType({ channel, timeUnit, scaleType, alwaysReturn }) {
// Following the logic in https://github.com/vega/vega-parser/blob/master/src/parsers/legend.js
if (channel_isColorChannel(channel)) {
if (util_contains(['quarter', 'month', 'day'], timeUnit)) {
return 'symbol';
}
if (scale_isContinuousToContinuous(scaleType)) {
return alwaysReturn ? 'gradient' : undefined;
}
}
return alwaysReturn ? 'symbol' : undefined;
}
function properties_direction({ legend, legendConfig, timeUnit, channel, scaleType }) {
const orient = util_getFirstDefined(legend.orient, legendConfig.orient, 'right');
const legendType = properties_type({ legend, channel, timeUnit, scaleType, alwaysReturn: true });
return util_getFirstDefined(legend.direction, legendConfig[legendType ? 'gradientDirection' : 'symbolDirection'], properties_defaultDirection(orient, legendType));
}
function properties_defaultDirection(orient, legendType) {
switch (orient) {
case 'top':
case 'bottom':
return 'horizontal';
case 'left':
case 'right':
case 'none':
case undefined: // undefined = "right" in Vega
return undefined; // vertical is Vega's default
default:
// top-left / ...
// For inner legend, uses compact layout like Tableau
return legendType === 'gradient' ? 'horizontal' : undefined;
}
}
function properties_defaultGradientLength({ legend, legendConfig, model, channel, scaleType }) {
const { gradientHorizontalMaxLength, gradientHorizontalMinLength, gradientVerticalMaxLength, gradientVerticalMinLength } = legendConfig;
const dir = properties_direction({ legend, legendConfig, channel, scaleType });
if (dir === 'horizontal') {
const orient = util_getFirstDefined(legend.orient, legendConfig.orient);
if (orient === 'top' || orient === 'bottom') {
return properties_gradientLengthSignal(model, 'width', gradientHorizontalMinLength, gradientHorizontalMaxLength);
}
else {
return gradientHorizontalMinLength;
}
}
else {
// vertical / undefined (Vega uses vertical by default)
return properties_gradientLengthSignal(model, 'height', gradientVerticalMinLength, gradientVerticalMaxLength);
}
}
function properties_gradientLengthSignal(model, sizeType, min, max) {
const sizeSignal = model.getSizeSignalRef(sizeType).signal;
return { signal: `clamp(${sizeSignal}, ${min}, ${max})` };
}
function legend_properties_defaultLabelOverlap(scaleType) {
if (util_contains(['quantile', 'threshold', 'log'], scaleType)) {
return 'greedy';
}
return undefined;
}
//# sourceMappingURL=properties.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/legend/encode.js
function encode_type(legendCmp, model, channel) {
const scaleType = model.getScaleComponent(channel).get('type');
return util_getFirstDefined(legendCmp.get('type'), properties_defaultType({ channel, scaleType, alwaysReturn: true }));
}
function encode_symbols(fieldDef, symbolsSpec, model, channel, legendCmp) {
var _a, _b, _c, _d, _e;
if (encode_type(legendCmp, model, channel) !== 'symbol') {
return undefined;
}
let out = Object.assign(Object.assign({}, common_applyMarkConfig({}, model, mark_FILL_STROKE_CONFIG)), encode_color_color(model)); // FIXME: remove this when VgEncodeEntry is compatible with SymbolEncodeEntry
const { markDef, encoding, config } = model;
const filled = markDef.filled;
const opacity = (_a = encode_getMaxValue(encoding.opacity), (_a !== null && _a !== void 0 ? _a : markDef.opacity));
const condition = encode_selectedCondition(model, legendCmp, fieldDef);
if (out.fill) {
// for fill legend, we don't want any fill in symbol
if (channel === 'fill' || (filled && channel === channel_COLOR)) {
delete out.fill;
}
else {
if (out.fill['field']) {
// For others, set fill to some opaque value (or nothing if a color is already set)
if (legendCmp.get('symbolFillColor')) {
delete out.fill;
}
else {
out.fill = { value: (_b = config.legend.symbolBaseFillColor, (_b !== null && _b !== void 0 ? _b : 'black')) };
out.fillOpacity = { value: (opacity !== null && opacity !== void 0 ? opacity : 1) };
}
}
else if (isArray(out.fill)) {
const fill = (_e = (_d = encode_getFirstConditionValue((_c = encoding.fill, (_c !== null && _c !== void 0 ? _c : encoding.color))), (_d !== null && _d !== void 0 ? _d : markDef.fill)), (_e !== null && _e !== void 0 ? _e : (filled && markDef.color)));
if (fill) {
out.fill = { value: fill };
}
}
}
}
if (out.stroke) {
if (channel === 'stroke' || (!filled && channel === channel_COLOR)) {
delete out.stroke;
}
else {
if (out.stroke['field']) {
// For others, remove stroke field
delete out.stroke;
}
else if (isArray(out.stroke)) {
const stroke = util_getFirstDefined(encode_getFirstConditionValue(encoding.stroke || encoding.color), markDef.stroke, filled ? markDef.color : undefined);
if (stroke) {
out.stroke = { value: stroke };
}
}
}
}
if (channel !== channel_OPACITY) {
if (condition) {
out.opacity = [{ test: condition, value: (opacity !== null && opacity !== void 0 ? opacity : 1) }, { value: config.legend.unselectedOpacity }];
}
else if (opacity) {
out.opacity = { value: opacity };
}
}
out = Object.assign(Object.assign({}, out), symbolsSpec);
return util_keys(out).length > 0 ? out : undefined;
}
function legend_encode_gradient(fieldDef, gradientSpec, model, channel, legendCmp) {
if (encode_type(legendCmp, model, channel) !== 'gradient') {
return undefined;
}
let out = {};
const opacity = encode_getMaxValue(model.encoding.opacity) || model.markDef.opacity;
if (opacity) {
// only apply opacity if it is neither zero or undefined
out.opacity = { value: opacity };
}
out = Object.assign(Object.assign({}, out), gradientSpec);
return util_keys(out).length > 0 ? out : undefined;
}
function encode_labels(fieldDef, labelsSpec, model, channel, legendCmp) {
const legend = model.legend(channel);
const config = model.config;
const condition = encode_selectedCondition(model, legendCmp, fieldDef);
let out = {};
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
const isUTCScale = model.getScaleComponent(channel).get('type') === scale_ScaleType.UTC;
const expr = common_timeFormatExpression('datum.value', fieldDef.timeUnit, legend.format, config.timeFormat, isUTCScale);
labelsSpec = Object.assign(Object.assign({}, (expr ? { text: { signal: expr } } : {})), labelsSpec);
}
if (condition) {
labelsSpec.opacity = [{ test: condition, value: 1 }, { value: config.legend.unselectedOpacity }];
}
out = Object.assign(Object.assign({}, out), labelsSpec);
return util_keys(out).length > 0 ? out : undefined;
}
function encode_entries(fieldDef, entriesSpec, model, channel, legendCmp) {
var _a;
const selections = legendCmp.get('selections');
return ((_a = selections) === null || _a === void 0 ? void 0 : _a.length) ? { fill: { value: 'transparent' } } : undefined;
}
function encode_getMaxValue(channelDef) {
return encode_getConditionValue(channelDef, (v, conditionalDef) => Math.max(v, conditionalDef.value));
}
function encode_getFirstConditionValue(channelDef) {
return encode_getConditionValue(channelDef, (v, conditionalDef) => {
return util_getFirstDefined(v, conditionalDef.value);
});
}
function encode_getConditionValue(channelDef, reducer) {
if (channeldef_hasConditionalValueDef(channelDef)) {
return (isArray(channelDef.condition) ? channelDef.condition : [channelDef.condition]).reduce(reducer, channelDef.value);
}
else if (channeldef_isValueDef(channelDef)) {
return channelDef.value;
}
return undefined;
}
function encode_selectedCondition(model, legendCmp, fieldDef) {
var _a;
const selections = legendCmp.get('selections');
if (!((_a = selections) === null || _a === void 0 ? void 0 : _a.length))
return undefined;
const field = stringValue_$(fieldDef.field);
return selections
.map(name => {
const store = stringValue_$(util_varName(name) + selection_STORE);
return `(!length(data(${store})) || (${name}[${field}] && indexof(${name}[${field}], datum.value) >= 0))`;
})
.join(' || ');
}
//# sourceMappingURL=encode.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/legend/parse.js
function parse_parseLegend(model) {
if (model_isUnitModel(model)) {
model.component.legends = parse_parseUnitLegend(model);
}
else {
model.component.legends = parse_parseNonUnitLegend(model);
}
}
function parse_parseUnitLegend(model) {
const { encoding } = model;
return [channel_COLOR, channel_FILL, channel_STROKE, channel_STROKEWIDTH, channel_SIZE, channel_SHAPE, channel_OPACITY, channel_FILLOPACITY, channel_STROKEOPACITY].reduce((legendComponent, channel) => {
const def = encoding[channel];
if (model.legend(channel) &&
model.getScaleComponent(channel) &&
!(channeldef_isFieldDef(def) && channel === channel_SHAPE && def.type === GEOJSON)) {
legendComponent[channel] = parse_parseLegendForChannel(model, channel);
}
return legendComponent;
}, {});
}
function parse_getLegendDefWithScale(model, channel) {
const scale = model.scaleName(channel_COLOR);
if (channel === 'color') {
return model.markDef.filled ? { fill: scale } : { stroke: scale };
}
return { [channel]: model.scaleName(channel) };
}
function parse_isExplicit(value, property, legend, fieldDef) {
switch (property) {
case 'values':
// specified legend.values is already respected, but may get transformed.
return !!legend.values;
case 'title':
// title can be explicit if fieldDef.title is set
if (property === 'title' && value === fieldDef.title) {
return true;
}
}
// Otherwise, things are explicit if the returned value matches the specified property
return value === legend[property];
}
function parse_parseLegendForChannel(model, channel) {
var _a;
const fieldDef = model.fieldDef(channel);
const legend = model.legend(channel);
const legendCmpt = new component_LegendComponent({}, parse_getLegendDefWithScale(model, channel));
legends_parseInteractiveLegend(model, channel, legendCmpt);
for (const property of component_LEGEND_COMPONENT_PROPERTIES) {
const value = parse_getProperty(property, legend, channel, model);
if (value !== undefined) {
const explicit = parse_isExplicit(value, property, legend, fieldDef);
if (explicit || model.config.legend[property] === undefined) {
legendCmpt.set(property, value, explicit);
}
}
}
const legendEncoding = (_a = legend.encoding, (_a !== null && _a !== void 0 ? _a : {}));
const selections = legendCmpt.get('selections');
const legendEncode = ['labels', 'legend', 'title', 'symbols', 'gradient', 'entries'].reduce((e, part) => {
var _a, _b, _c;
const legendEncodingPart = guide_guideEncodeEntry((_a = legendEncoding[part], (_a !== null && _a !== void 0 ? _a : {})), model);
const value = legend_encode_namespaceObject[part]
? legend_encode_namespaceObject[part](fieldDef, legendEncodingPart, model, channel, legendCmpt) // apply rule
: legendEncodingPart; // no rule -- just default values
if (value !== undefined && util_keys(value).length > 0) {
e[part] = Object.assign(Object.assign(Object.assign({}, (((_b = selections) === null || _b === void 0 ? void 0 : _b.length) ? { name: `${fieldDef.field}_legend_${part}` } : {})), (((_c = selections) === null || _c === void 0 ? void 0 : _c.length) ? { interactive: !!selections } : {})), { update: value });
}
return e;
}, {});
if (util_keys(legendEncode).length > 0) {
legendCmpt.set('encode', legendEncode, !!legend.encoding);
}
return legendCmpt;
}
function parse_getProperty(property, legend, channel, model) {
const { encoding, mark } = model;
const fieldDef = channeldef_getTypedFieldDef(encoding[channel]);
const legendConfig = model.config.legend;
const { timeUnit } = fieldDef;
const scaleType = model.getScaleComponent(channel).get('type');
switch (property) {
// TODO: enable when https://github.com/vega/vega/issues/1351 is fixed
// case 'clipHeight':
// return getFirstDefined(specifiedLegend.clipHeight, properties.clipHeight(properties.type(...)));
case 'direction':
return properties_direction({
legend,
legendConfig,
timeUnit,
channel,
scaleType
});
case 'format':
// We don't include temporal field here as we apply format in encode block
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
return undefined;
}
return common_numberFormat(fieldDef, legend.format, model.config);
case 'formatType':
// As with format, we don't include temporal field here as we apply format in encode block
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
return undefined;
}
return legend.formatType;
case 'gradientLength':
return util_getFirstDefined(
// do specified gradientLength first
legend.gradientLength, legendConfig.gradientLength,
// Otherwise, use smart default based on plot height
properties_defaultGradientLength({
model,
legend,
legendConfig,
channel,
scaleType
}));
case 'labelOverlap':
return util_getFirstDefined(legend.labelOverlap, legend_properties_defaultLabelOverlap(scaleType));
case 'symbolType':
return util_getFirstDefined(legend.symbolType, properties_defaultSymbolType(mark, channel, encoding.shape, model.markDef.shape));
case 'title':
return (channeldef_title(fieldDef, model.config, { allowDisabling: true }) || undefined);
case 'type':
return properties_type({ legend, channel, timeUnit, scaleType, alwaysReturn: false });
case 'values':
return legend_properties_values(legend, fieldDef);
}
// Otherwise, return specified property.
return legend[property];
}
function parse_parseNonUnitLegend(model) {
const { legends, resolve } = model.component;
for (const child of model.children) {
parse_parseLegend(child);
util_keys(child.component.legends).forEach((channel) => {
resolve.legend[channel] = resolve_parseGuideResolve(model.component.resolve, channel);
if (resolve.legend[channel] === 'shared') {
// If the resolve says shared (and has not been overridden)
// We will try to merge and see if there is a conflict
legends[channel] = parse_mergeLegendComponent(legends[channel], child.component.legends[channel]);
if (!legends[channel]) {
// If merge returns nothing, there is a conflict so we cannot make the legend shared.
// Thus, mark legend as independent and remove the legend component.
resolve.legend[channel] = 'independent';
delete legends[channel];
}
}
});
}
util_keys(legends).forEach((channel) => {
for (const child of model.children) {
if (!child.component.legends[channel]) {
// skip if the child does not have a particular legend
continue;
}
if (resolve.legend[channel] === 'shared') {
// After merging shared legend, make sure to remove legend from child
delete child.component.legends[channel];
}
}
});
return legends;
}
function parse_mergeLegendComponent(mergedLegend, childLegend) {
var _a, _b, _c, _d, _e, _f;
if (!mergedLegend) {
return childLegend.clone();
}
const mergedOrient = mergedLegend.getWithExplicit('orient');
const childOrient = childLegend.getWithExplicit('orient');
if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {
// TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)
// Cannot merge due to inconsistent orient
return undefined;
}
let typeMerged = false;
// Otherwise, let's merge
for (const prop of component_LEGEND_COMPONENT_PROPERTIES) {
const mergedValueWithExplicit = split_mergeValuesWithExplicit(mergedLegend.getWithExplicit(prop), childLegend.getWithExplicit(prop), prop, 'legend',
// Tie breaker function
(v1, v2) => {
switch (prop) {
case 'symbolType':
return parse_mergeSymbolType(v1, v2);
case 'title':
return common_mergeTitleComponent(v1, v2);
case 'type':
// There are only two types. If we have different types, then prefer symbol over gradient.
typeMerged = true;
return split_makeImplicit('symbol');
}
return split_defaultTieBreaker(v1, v2, prop, 'legend');
});
mergedLegend.setWithExplicit(prop, mergedValueWithExplicit);
}
if (typeMerged) {
if (_c = (_b = (_a = mergedLegend.implicit) === null || _a === void 0 ? void 0 : _a.encode) === null || _b === void 0 ? void 0 : _b.gradient, (_c !== null && _c !== void 0 ? _c : {})) {
util_deleteNestedProperty(mergedLegend.implicit, ['encode', 'gradient']);
}
if (_f = (_e = (_d = mergedLegend.explicit) === null || _d === void 0 ? void 0 : _d.encode) === null || _e === void 0 ? void 0 : _e.gradient, (_f !== null && _f !== void 0 ? _f : {})) {
util_deleteNestedProperty(mergedLegend.explicit, ['encode', 'gradient']);
}
}
return mergedLegend;
}
function parse_mergeSymbolType(st1, st2) {
if (st2.value === 'circle') {
// prefer "circle" over "stroke"
return st2;
}
return st1;
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/legend/assemble.js
function assemble_setLegendEncode(legend, part, vgProp, vgRef) {
var _a, _b, _c;
legend.encode = (_a = legend.encode, (_a !== null && _a !== void 0 ? _a : {}));
legend.encode[part] = (_b = legend.encode[part], (_b !== null && _b !== void 0 ? _b : {}));
legend.encode[part].update = (_c = legend.encode[part].update, (_c !== null && _c !== void 0 ? _c : {}));
// TODO: remove as any after https://github.com/prisma/nexus-prisma/issues/291
legend.encode[part].update[vgProp] = vgRef;
}
function assemble_assembleLegends(model) {
const legendComponentIndex = model.component.legends;
const legendByDomain = {};
for (const channel of util_keys(legendComponentIndex)) {
const scaleComponent = model.getScaleComponent(channel);
const domainHash = util_stringify(scaleComponent.get('domains'));
if (legendByDomain[domainHash]) {
for (const mergedLegendComponent of legendByDomain[domainHash]) {
const merged = parse_mergeLegendComponent(mergedLegendComponent, legendComponentIndex[channel]);
if (!merged) {
// If cannot merge, need to add this legend separately
legendByDomain[domainHash].push(legendComponentIndex[channel]);
}
}
}
else {
legendByDomain[domainHash] = [legendComponentIndex[channel].clone()];
}
}
return util_vals(legendByDomain)
.flat()
.map((legendCmpt) => {
var _a, _b, _c, _d;
const _e = legendCmpt.combine(), { labelExpr, selections } = _e, legend = tslib_es6_rest(_e, ["labelExpr", "selections"]);
if ((_a = legend.encode) === null || _a === void 0 ? void 0 : _a.symbols) {
const out = legend.encode.symbols.update;
if (out.fill && out.fill['value'] !== 'transparent' && !out.stroke && !legend.stroke) {
// For non color channel's legend, we need to override symbol stroke config from Vega config if stroke channel is not used.
out.stroke = { value: 'transparent' };
}
if (legend.fill) {
// If top-level fill is defined, for non color channel's legend, we need remove fill.
delete out.fill;
}
}
if (labelExpr !== undefined) {
let expr = labelExpr;
if (((_d = (_c = (_b = legend.encode) === null || _b === void 0 ? void 0 : _b.labels) === null || _c === void 0 ? void 0 : _c.update) === null || _d === void 0 ? void 0 : _d.text) && vega_schema_isSignalRef(legend.encode.labels.update.text)) {
expr = util_replaceAll(labelExpr, 'datum.label', legend.encode.labels.update.text.signal);
}
assemble_setLegendEncode(legend, 'labels', 'text', { signal: expr });
}
return legend;
});
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/projection/assemble.js
function assemble_assembleProjections(model) {
if (model_isLayerModel(model) || model_isConcatModel(model) || model_isRepeatModel(model)) {
return assemble_assembleProjectionsForModelAndChildren(model);
}
else {
return assemble_assembleProjectionForModel(model);
}
}
function assemble_assembleProjectionsForModelAndChildren(model) {
return model.children.reduce((projections, child) => {
return projections.concat(child.assembleProjections());
}, assemble_assembleProjectionForModel(model));
}
function assemble_assembleProjectionForModel(model) {
const component = model.component.projection;
if (!component || component.merged) {
return [];
}
const projection = component.combine();
const { name } = projection, rest = tslib_es6_rest(projection, ["name"]); // we need to extract name so that it is always present in the output and pass TS type validation
if (!component.data) {
// generate custom projection, no automatic fitting
return [
Object.assign(Object.assign({ name }, { translate: { signal: '[width / 2, height / 2]' } }), rest)
];
}
else {
// generate projection that uses extent fitting
const size = {
signal: `[${component.size.map(ref => ref.signal).join(', ')}]`
};
const fit = component.data.reduce((sources, data) => {
const source = vega_schema_isSignalRef(data) ? data.signal : `data('${model.lookupDataSource(data)}')`;
if (!util_contains(sources, source)) {
// build a unique list of sources
sources.push(source);
}
return sources;
}, []);
if (fit.length <= 0) {
throw new Error("Projection's fit didn't find any data sources");
}
return [
Object.assign({ name,
size, fit: {
signal: fit.length > 1 ? `[${fit.join(', ')}]` : fit[0]
} }, rest)
];
}
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/projection.js
const PROJECTION_PROPERTIES = [
'type',
'clipAngle',
'clipExtent',
'center',
'rotate',
'precision',
'reflectX',
'reflectY',
'coefficient',
'distance',
'fraction',
'lobes',
'parallel',
'radius',
'ratio',
'spacing',
'tilt'
];
//# sourceMappingURL=projection.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/projection/component.js
class component_ProjectionComponent extends split_Split {
constructor(name, specifiedProjection, size, data) {
super(Object.assign({}, specifiedProjection), // all explicit properties of projection
{ name } // name as initial implicit property
);
this.specifiedProjection = specifiedProjection;
this.size = size;
this.data = data;
this.merged = false;
}
/**
* Whether the projection parameters should fit provided data.
*/
get isFit() {
return !!this.data;
}
}
//# sourceMappingURL=component.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/projection/parse.js
function parse_parseProjection(model) {
model.component.projection = model_isUnitModel(model) ? parse_parseUnitProjection(model) : parse_parseNonUnitProjections(model);
}
function parse_parseUnitProjection(model) {
var _a;
if (model.hasProjection) {
const proj = model.specifiedProjection;
const fit = !(proj && (proj.scale != null || proj.translate != null));
const size = fit ? [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')] : undefined;
const data = fit ? parse_gatherFitData(model) : undefined;
return new component_ProjectionComponent(model.projectionName(true), Object.assign(Object.assign({}, (_a = model.config.projection, (_a !== null && _a !== void 0 ? _a : {}))), ((proj !== null && proj !== void 0 ? proj : {}))), size, data);
}
return undefined;
}
function parse_gatherFitData(model) {
const data = [];
for (const posssiblePair of [
[channel_LONGITUDE, channel_LATITUDE],
[channel_LONGITUDE2, channel_LATITUDE2]
]) {
if (model.channelHasField(posssiblePair[0]) || model.channelHasField(posssiblePair[1])) {
data.push({
signal: model.getName(`geojson_${data.length}`)
});
}
}
if (model.channelHasField(channel_SHAPE) && model.fieldDef(channel_SHAPE).type === GEOJSON) {
data.push({
signal: model.getName(`geojson_${data.length}`)
});
}
if (data.length === 0) {
// main source is geojson, so we can just use that
data.push(model.requestDataName(MAIN));
}
return data;
}
function parse_mergeIfNoConflict(first, second) {
const allPropertiesShared = util_every(PROJECTION_PROPERTIES, prop => {
// neither has the property
if (!src_hasOwnProperty(first.explicit, prop) && !src_hasOwnProperty(second.explicit, prop)) {
return true;
}
// both have property and an equal value for property
if (src_hasOwnProperty(first.explicit, prop) &&
src_hasOwnProperty(second.explicit, prop) &&
// some properties might be signals or objects and require hashing for comparison
util_stringify(first.get(prop)) === util_stringify(second.get(prop))) {
return true;
}
return false;
});
const size = util_stringify(first.size) === util_stringify(second.size);
if (size) {
if (allPropertiesShared) {
return first;
}
else if (util_stringify(first.explicit) === util_stringify({})) {
return second;
}
else if (util_stringify(second.explicit) === util_stringify({})) {
return first;
}
}
// if all properties don't match, let each unit spec have its own projection
return null;
}
function parse_parseNonUnitProjections(model) {
if (model.children.length === 0) {
return undefined;
}
let nonUnitProjection;
// parse all children first
model.children.forEach(child => parse_parseProjection(child));
// analyze parsed projections, attempt to merge
const mergable = util_every(model.children, child => {
const projection = child.component.projection;
if (!projection) {
// child layer does not use a projection
return true;
}
else if (!nonUnitProjection) {
// cached 'projection' is null, cache this one
nonUnitProjection = projection;
return true;
}
else {
const merge = parse_mergeIfNoConflict(nonUnitProjection, projection);
if (merge) {
nonUnitProjection = merge;
}
return !!merge;
}
});
// if cached one and all other children share the same projection,
if (nonUnitProjection && mergable) {
// so we can elevate it to the layer level
const name = model.projectionName(true);
const modelProjection = new component_ProjectionComponent(name, nonUnitProjection.specifiedProjection, nonUnitProjection.size, util_duplicate(nonUnitProjection.data));
// rename and assign all others as merged
model.children.forEach(child => {
const projection = child.component.projection;
if (projection) {
if (projection.isFit) {
modelProjection.data.push(...child.component.projection.data);
}
child.renameProjection(projection.get('name'), name);
projection.merged = true;
}
});
return modelProjection;
}
return undefined;
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/bin.js
function bin_rangeFormula(model, fieldDef, channel, config) {
var _a, _b;
if (channeldef_binRequiresRange(fieldDef, channel)) {
// read format from axis or legend, if there is no format then use config.numberFormat
const guide = model_isUnitModel(model) ? (_b = (_a = model.axis(channel), (_a !== null && _a !== void 0 ? _a : model.legend(channel))), (_b !== null && _b !== void 0 ? _b : {})) : {};
const startField = channeldef_vgField(fieldDef, { expr: 'datum' });
const endField = channeldef_vgField(fieldDef, { expr: 'datum', binSuffix: 'end' });
return {
formulaAs: channeldef_vgField(fieldDef, { binSuffix: 'range', forAs: true }),
formula: common_binFormatExpression(startField, endField, guide.format, config)
};
}
return {};
}
function bin_binKey(bin, field) {
return `${bin_binToString(bin)}_${field}`;
}
function bin_getSignalsFromModel(model, key) {
return {
signal: model.getName(`${key}_bins`),
extentSignal: model.getName(`${key}_extent`)
};
}
function bin_getBinSignalName(model, field, bin) {
var _a;
const normalizedBin = (_a = channeldef_normalizeBin(bin, undefined), (_a !== null && _a !== void 0 ? _a : {}));
const key = bin_binKey(normalizedBin, field);
return model.getName(`${key}_bins`);
}
function bin_isBinTransform(t) {
return 'as' in t;
}
function bin_createBinComponent(t, bin, model) {
let as;
let span;
if (bin_isBinTransform(t)) {
as = isString(t.as) ? [t.as, `${t.as}_end`] : [t.as[0], t.as[1]];
}
else {
as = [channeldef_vgField(t, { forAs: true }), channeldef_vgField(t, { binSuffix: 'end', forAs: true })];
}
const normalizedBin = Object.assign({}, channeldef_normalizeBin(bin, undefined));
const key = bin_binKey(normalizedBin, t.field);
const { signal, extentSignal } = bin_getSignalsFromModel(model, key);
if (bin_isSelectionExtent(normalizedBin.extent)) {
const ext = normalizedBin.extent;
const selName = ext.selection;
span = parse_parseSelectionBinExtent(model.getSelectionComponent(util_varName(selName), selName), ext);
delete normalizedBin.extent; // Vega-Lite selection extent map to Vega's span property.
}
const binComponent = Object.assign(Object.assign(Object.assign({ bin: normalizedBin, field: t.field, as: [as] }, (signal ? { signal } : {})), (extentSignal ? { extentSignal } : {})), (span ? { span } : {}));
return { key, binComponent };
}
class bin_BinNode extends dataflow_DataFlowNode {
constructor(parent, bins) {
super(parent);
this.bins = bins;
}
clone() {
return new bin_BinNode(null, util_duplicate(this.bins));
}
static makeFromEncoding(parent, model) {
const bins = model.reduceFieldDef((binComponentIndex, fieldDef, channel) => {
if (channeldef_isTypedFieldDef(fieldDef) && bin_isBinning(fieldDef.bin)) {
const { key, binComponent } = bin_createBinComponent(fieldDef, fieldDef.bin, model);
binComponentIndex[key] = Object.assign(Object.assign(Object.assign({}, binComponent), binComponentIndex[key]), bin_rangeFormula(model, fieldDef, channel, model.config));
}
return binComponentIndex;
}, {});
if (util_keys(bins).length === 0) {
return null;
}
return new bin_BinNode(parent, bins);
}
/**
* Creates a bin node from BinTransform.
* The optional parameter should provide
*/
static makeFromTransform(parent, t, model) {
const { key, binComponent } = bin_createBinComponent(t, t.bin, model);
return new bin_BinNode(parent, {
[key]: binComponent
});
}
/**
* Merge bin nodes. This method either integrates the bin config from the other node
* or if this node already has a bin config, renames the corresponding signal in the model.
*/
merge(other, renameSignal) {
for (const key of util_keys(other.bins)) {
if (key in this.bins) {
renameSignal(other.bins[key].signal, this.bins[key].signal);
// Ensure that we don't have duplicate names for signal pairs
this.bins[key].as = util_unique([...this.bins[key].as, ...other.bins[key].as], util_hash);
}
else {
this.bins[key] = other.bins[key];
}
}
for (const child of other.children) {
other.removeChild(child);
child.parent = this;
}
other.remove();
}
producedFields() {
return new Set(util_vals(this.bins)
.map(c => c.as)
.flat(2));
}
dependentFields() {
return new Set(util_vals(this.bins).map(c => c.field));
}
hash() {
return `Bin ${util_hash(this.bins)}`;
}
assemble() {
return util_vals(this.bins).flatMap(bin => {
const transform = [];
const [binAs, ...remainingAs] = bin.as;
const _a = bin.bin, { extent } = _a, params = tslib_es6_rest(_a, ["extent"]);
const binTrans = Object.assign(Object.assign(Object.assign({ type: 'bin', field: util_replacePathInField(bin.field), as: binAs, signal: bin.signal }, (!bin_isSelectionExtent(extent) ? { extent } : { extent: null })), (bin.span ? { span: { signal: `span(${bin.span})` } } : {})), params);
if (!extent && bin.extentSignal) {
transform.push({
type: 'extent',
field: util_replacePathInField(bin.field),
signal: bin.extentSignal
});
binTrans.extent = { signal: bin.extentSignal };
}
transform.push(binTrans);
for (const as of remainingAs) {
for (let i = 0; i < 2; i++) {
transform.push({
type: 'formula',
expr: channeldef_vgField({ field: binAs[i] }, { expr: 'datum' }),
as: as[i]
});
}
}
if (bin.formula) {
transform.push({
type: 'formula',
expr: bin.formula,
as: bin.formulaAs
});
}
return transform;
});
}
}
//# sourceMappingURL=bin.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/source.js
class source_SourceNode extends dataflow_DataFlowNode {
constructor(data) {
super(null); // source cannot have parent
data = (data !== null && data !== void 0 ? data : { name: 'source' });
let format;
if (!isGenerator(data)) {
format = data.format ? Object.assign({}, util_omit(data.format, ['parse'])) : {};
}
if (isInlineData(data)) {
this._data = { values: data.values };
}
else if (isUrlData(data)) {
this._data = { url: data.url };
if (!format.type) {
// Extract extension from URL using snippet from
// http://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript
let defaultExtension = /(?:\.([^.]+))?$/.exec(data.url)[1];
if (!util_contains(['json', 'csv', 'tsv', 'dsv', 'topojson'], defaultExtension)) {
defaultExtension = 'json';
}
// defaultExtension has type string but we ensure that it is DataFormatType above
format.type = defaultExtension;
}
}
else if (isSphereGenerator(data)) {
// hardwire GeoJSON sphere data into output specification
this._data = { values: [{ type: 'Sphere' }] };
}
else if (isNamedData(data) || isGenerator(data)) {
this._data = {};
}
// set flag to check if generator
this._generator = isGenerator(data);
// any dataset can be named
if (data.name) {
this._name = data.name;
}
if (format && util_keys(format).length > 0) {
this._data.format = format;
}
}
dependentFields() {
return new Set();
}
producedFields() {
return undefined; // we don't know what this source produces
}
get data() {
return this._data;
}
hasName() {
return !!this._name;
}
get isGenerator() {
return this._generator;
}
get dataName() {
return this._name;
}
set dataName(name) {
this._name = name;
}
set parent(parent) {
throw new Error('Source nodes have to be roots.');
}
remove() {
throw new Error('Source nodes are roots and cannot be removed.');
}
hash() {
throw new Error('Cannot hash sources');
}
assemble() {
return Object.assign(Object.assign({ name: this._name }, this._data), { transform: [] });
}
}
//# sourceMappingURL=source.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/debug.js
/**
* Print debug information for dataflow tree.
*/
function debug_debug(node) {
console.log(`${node.constructor.name}${node.debugName ? `(${node.debugName})` : ''} -> ${node.children.map(c => {
return `${c.constructor.name}${c.debugName ? ` (${c.debugName})` : ''}`;
})}`);
console.log(node);
node.children.forEach(debug_debug);
}
/**
* Print the dataflow tree as graphviz.
*
* Render the output in http://viz-js.com/.
*/
function debug_draw(roots) {
// check the graph before printing it since the logic below assumes a consistent graph
debug_checkLinks(roots);
const nodes = {};
const edges = [];
function getId(node) {
let id = node['__uniqueid'];
if (id === undefined) {
id = util_uniqueId();
node['__uniqueid'] = id;
}
return id;
}
function getLabel(node) {
var _a, _b, _c;
const out = [node.constructor.name.slice(0, -4)];
if (node.debugName) {
out.push(`<i>${node.debugName}</i>`);
}
else if (node instanceof source_SourceNode) {
if (node.data.name || node.data.url) {
out.push(`<i>${_a = node.data.name, (_a !== null && _a !== void 0 ? _a : node.data.url)}</i>`);
}
}
const dep = node.dependentFields();
if ((_b = dep) === null || _b === void 0 ? void 0 : _b.size) {
out.push(`<font color="grey" point-size="10">IN:</font> ${[...node.dependentFields()].join(', ')}`);
}
const prod = node.producedFields();
if ((_c = prod) === null || _c === void 0 ? void 0 : _c.size) {
out.push(`<font color="grey" point-size="10">OUT:</font> ${[...node.producedFields()].join(', ')}`);
}
if (node instanceof dataflow_OutputNode) {
out.push(`<font color="grey" point-size="10">required:</font> ${node.isRequired()}`);
}
return out.join('<br/>');
}
function collector(node) {
var _a, _b;
const id = getId(node);
nodes[id] = {
id: id,
label: getLabel(node),
hash: node instanceof source_SourceNode
? (_b = (_a = node.data.url, (_a !== null && _a !== void 0 ? _a : node.data.name)), (_b !== null && _b !== void 0 ? _b : node.debugName)) : String(node.hash()).replace(/"/g, '')
};
for (const child of node.children) {
edges.push([id, getId(child)]);
collector(child);
}
}
roots.forEach(n => collector(n));
const dot = `digraph DataFlow {
rankdir = TB;
node [shape=record]
${util_entries(nodes)
.map(({ key, value }) => ` "${key}" [
label = <${value.label}>;
tooltip = "[${value.id}]&#010;${value.hash}"
]`)
.join('\n')}
${edges.map(([source, target]) => `"${source}" -> "${target}"`).join(' ')}
}`;
console.log(dot);
return dot;
}
/**
* Iterates over a dataflow graph and checks whether all links are consistent.
*/
function debug_checkLinks(nodes) {
for (const node of nodes) {
for (const child of node.children) {
if (child.parent !== node) {
console.error('Dataflow graph is inconsistent.', node, child);
return false;
}
}
if (!debug_checkLinks(node.children)) {
return false;
}
}
return true;
}
//# sourceMappingURL=debug.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/graticule.js
class graticule_GraticuleNode extends dataflow_DataFlowNode {
constructor(parent, params) {
super(parent);
this.params = params;
}
clone() {
return new graticule_GraticuleNode(null, this.params);
}
dependentFields() {
return new Set();
}
producedFields() {
return undefined; // there should never be a node before graticule
}
hash() {
return `Graticule ${util_hash(this.params)}`;
}
assemble() {
return Object.assign({ type: 'graticule' }, (this.params === true ? {} : this.params));
}
}
//# sourceMappingURL=graticule.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/sequence.js
class sequence_SequenceNode extends dataflow_DataFlowNode {
constructor(parent, params) {
super(parent);
this.params = params;
}
clone() {
return new sequence_SequenceNode(null, this.params);
}
dependentFields() {
return new Set();
}
producedFields() {
var _a;
return new Set([(_a = this.params.as, (_a !== null && _a !== void 0 ? _a : 'data'))]);
}
hash() {
return `Hash ${util_hash(this.params)}`;
}
assemble() {
return Object.assign({ type: 'sequence' }, this.params);
}
}
//# sourceMappingURL=sequence.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/optimizer.js
/**
* Whether this dataflow node is the source of the dataflow that produces data i.e. a source or a generator.
*/
function optimizer_isDataSourceNode(node) {
return node instanceof source_SourceNode || node instanceof graticule_GraticuleNode || node instanceof sequence_SequenceNode;
}
/**
* Abstract base class for BottomUpOptimizer and TopDownOptimizer.
* Contains only mutation handling logic. Subclasses need to implement iteration logic.
*/
class optimizer_OptimizerBase {
constructor() {
this._mutated = false;
}
// Once true, _mutated is never set to false
setMutated() {
this._mutated = true;
}
get mutatedFlag() {
return this._mutated;
}
}
/**
* Starts from a node and runs the optimization function(the "run" method) upwards to the root,
* depending on the continueFlag and mutatedFlag values returned by the optimization function.
*/
class optimizer_BottomUpOptimizer extends optimizer_OptimizerBase {
constructor() {
super();
this._continue = false;
}
setContinue() {
this._continue = true;
}
get continueFlag() {
return this._continue;
}
get flags() {
return { continueFlag: this.continueFlag, mutatedFlag: this.mutatedFlag };
}
set flags({ continueFlag, mutatedFlag }) {
if (continueFlag) {
this.setContinue();
}
if (mutatedFlag) {
this.setMutated();
}
}
/**
* Reset the state of the optimizer after it has completed a run from the bottom of the tree to the top.
*/
reset() {
// do nothing
}
optimizeNextFromLeaves(node) {
if (optimizer_isDataSourceNode(node)) {
return false;
}
const next = node.parent;
const { continueFlag } = this.run(node);
if (continueFlag) {
this.optimizeNextFromLeaves(next);
}
return this.mutatedFlag;
}
}
/**
* The optimizer function( the "run" method), is invoked on the given node and then continues recursively.
*/
class optimizer_TopDownOptimizer extends optimizer_OptimizerBase {
}
//# sourceMappingURL=optimizer.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/aggregate.js
function aggregate_addDimension(dims, channel, fieldDef, model) {
const channelDef2 = model_isUnitModel(model) ? model.encoding[channel_getSecondaryRangeChannel(channel)] : undefined;
if (channeldef_isTypedFieldDef(fieldDef) &&
model_isUnitModel(model) &&
channeldef_hasBand(channel, fieldDef, channelDef2, model.markDef, model.config)) {
dims.add(channeldef_vgField(fieldDef, {}));
dims.add(channeldef_vgField(fieldDef, { suffix: 'end' }));
if (channeldef_binRequiresRange(fieldDef, channel)) {
dims.add(channeldef_vgField(fieldDef, { binSuffix: 'range' }));
}
}
else if (channel_isGeoPositionChannel(channel)) {
const posChannel = channel_getPositionChannelFromLatLong(channel);
dims.add(model.getName(posChannel));
}
else {
dims.add(channeldef_vgField(fieldDef));
}
return dims;
}
function aggregate_mergeMeasures(parentMeasures, childMeasures) {
var _a;
for (const field of util_keys(childMeasures)) {
// when we merge a measure, we either have to add an aggregation operator or even a new field
const ops = childMeasures[field];
for (const op of util_keys(ops)) {
if (field in parentMeasures) {
// add operator to existing measure field
parentMeasures[field][op] = new Set([...(_a = parentMeasures[field][op], (_a !== null && _a !== void 0 ? _a : [])), ...ops[op]]);
}
else {
parentMeasures[field] = { [op]: ops[op] };
}
}
}
}
class aggregate_AggregateNode extends dataflow_DataFlowNode {
/**
* @param dimensions string set for dimensions
* @param measures dictionary mapping field name => dict of aggregation functions and names to use
*/
constructor(parent, dimensions, measures) {
super(parent);
this.dimensions = dimensions;
this.measures = measures;
}
clone() {
return new aggregate_AggregateNode(null, new Set(this.dimensions), util_duplicate(this.measures));
}
get groupBy() {
return this.dimensions;
}
static makeFromEncoding(parent, model) {
let isAggregate = false;
model.forEachFieldDef(fd => {
if (fd.aggregate) {
isAggregate = true;
}
});
const meas = {};
const dims = new Set();
if (!isAggregate) {
// no need to create this node if the model has no aggregation
return null;
}
model.forEachFieldDef((fieldDef, channel) => {
var _a, _b, _c, _d;
const { aggregate, field } = fieldDef;
if (aggregate) {
if (aggregate === 'count') {
meas['*'] = (_a = meas['*'], (_a !== null && _a !== void 0 ? _a : {}));
meas['*']['count'] = new Set([channeldef_vgField(fieldDef, { forAs: true })]);
}
else {
if (aggregate_isArgminDef(aggregate) || aggregate_isArgmaxDef(aggregate)) {
const op = aggregate_isArgminDef(aggregate) ? 'argmin' : 'argmax';
const argField = aggregate[op];
meas[argField] = (_b = meas[argField], (_b !== null && _b !== void 0 ? _b : {}));
meas[argField][op] = new Set([channeldef_vgField({ op, field: argField }, { forAs: true })]);
}
else {
meas[field] = (_c = meas[field], (_c !== null && _c !== void 0 ? _c : {}));
meas[field][aggregate] = new Set([channeldef_vgField(fieldDef, { forAs: true })]);
}
// For scale channel with domain === 'unaggregated', add min/max so we can use their union as unaggregated domain
if (channel_isScaleChannel(channel) && model.scaleDomain(channel) === 'unaggregated') {
meas[field] = (_d = meas[field], (_d !== null && _d !== void 0 ? _d : {}));
meas[field]['min'] = new Set([channeldef_vgField({ field, aggregate: 'min' }, { forAs: true })]);
meas[field]['max'] = new Set([channeldef_vgField({ field, aggregate: 'max' }, { forAs: true })]);
}
}
}
else {
aggregate_addDimension(dims, channel, fieldDef, model);
}
});
if (dims.size + util_keys(meas).length === 0) {
return null;
}
return new aggregate_AggregateNode(parent, dims, meas);
}
static makeFromTransform(parent, t) {
var _a, _b, _c;
const dims = new Set();
const meas = {};
for (const s of t.aggregate) {
const { op, field, as } = s;
if (op) {
if (op === 'count') {
meas['*'] = (_a = meas['*'], (_a !== null && _a !== void 0 ? _a : {}));
meas['*']['count'] = new Set([as ? as : channeldef_vgField(s, { forAs: true })]);
}
else {
meas[field] = (_b = meas[field], (_b !== null && _b !== void 0 ? _b : {}));
meas[field][op] = new Set([as ? as : channeldef_vgField(s, { forAs: true })]);
}
}
}
for (const s of (_c = t.groupby, (_c !== null && _c !== void 0 ? _c : []))) {
dims.add(s);
}
if (dims.size + util_keys(meas).length === 0) {
return null;
}
return new aggregate_AggregateNode(parent, dims, meas);
}
merge(other) {
if (util_setEqual(this.dimensions, other.dimensions)) {
aggregate_mergeMeasures(this.measures, other.measures);
return true;
}
else {
src_log_debug('different dimensions, cannot merge');
return false;
}
}
addDimensions(fields) {
fields.forEach(this.dimensions.add, this.dimensions);
}
dependentFields() {
return new Set([...this.dimensions, ...util_keys(this.measures)]);
}
producedFields() {
const out = new Set();
for (const field of util_keys(this.measures)) {
for (const op of util_keys(this.measures[field])) {
const m = this.measures[field][op];
if (m.size === 0) {
out.add(`${op}_${field}`);
}
else {
m.forEach(out.add, out);
}
}
}
return out;
}
hash() {
return `Aggregate ${util_hash({ dimensions: this.dimensions, measures: this.measures })}`;
}
assemble() {
const ops = [];
const fields = [];
const as = [];
for (const field of util_keys(this.measures)) {
for (const op of util_keys(this.measures[field])) {
for (const alias of this.measures[field][op]) {
as.push(alias);
ops.push(op);
fields.push(field === '*' ? null : util_replacePathInField(field));
}
}
}
const result = {
type: 'aggregate',
groupby: [...this.dimensions],
ops,
fields,
as
};
return result;
}
}
//# sourceMappingURL=aggregate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/facet.js
/**
* A node that helps us track what fields we are faceting by.
*/
class facet_FacetNode extends dataflow_DataFlowNode {
/**
* @param model The facet model.
* @param name The name that this facet source will have.
* @param data The source data for this facet data.
*/
constructor(parent, model, name, data) {
super(parent);
this.model = model;
this.name = name;
this.data = data;
for (const channel of channel_FACET_CHANNELS) {
const fieldDef = model.facet[channel];
if (fieldDef) {
const { bin, sort } = fieldDef;
this[channel] = Object.assign({ name: model.getName(`${channel}_domain`), fields: [channeldef_vgField(fieldDef), ...(bin_isBinning(bin) ? [channeldef_vgField(fieldDef, { binSuffix: 'end' })] : [])] }, (sort_isSortField(sort)
? { sortField: sort }
: isArray(sort)
? { sortIndexField: calculate_sortArrayIndexField(fieldDef, channel) }
: {}));
}
}
this.childModel = model.child;
}
hash() {
let out = `Facet`;
for (const channel of channel_FACET_CHANNELS) {
if (this[channel]) {
out += ` ${channel.charAt(0)}:${util_hash(this[channel])}`;
}
}
return out;
}
get fields() {
var _a;
const f = [];
for (const channel of channel_FACET_CHANNELS) {
if ((_a = this[channel]) === null || _a === void 0 ? void 0 : _a.fields) {
f.push(...this[channel].fields);
}
}
return f;
}
dependentFields() {
const depFields = new Set(this.fields);
for (const channel of channel_FACET_CHANNELS) {
if (this[channel]) {
if (this[channel].sortField) {
depFields.add(this[channel].sortField.field);
}
if (this[channel].sortIndexField) {
depFields.add(this[channel].sortIndexField);
}
}
}
return depFields;
}
producedFields() {
return new Set(); // facet does not produce any new fields
}
/**
* The name to reference this source is its name.
*/
getSource() {
return this.name;
}
getChildIndependentFieldsWithStep() {
const childIndependentFieldsWithStep = {};
for (const channel of ['x', 'y']) {
const childScaleComponent = this.childModel.component.scales[channel];
if (childScaleComponent && !childScaleComponent.merged) {
// independent scale
const type = childScaleComponent.get('type');
const range = childScaleComponent.get('range');
if (scale_hasDiscreteDomain(type) && vega_schema_isVgRangeStep(range)) {
const domain = domain_assembleDomain(this.childModel, channel);
const field = domain_getFieldFromDomain(domain);
if (field) {
childIndependentFieldsWithStep[channel] = field;
}
else {
src_log_warn(`Unknown field for ${channel}. Cannot calculate view size.`);
}
}
}
}
return childIndependentFieldsWithStep;
}
assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep) {
const childChannel = { row: 'y', column: 'x' }[channel];
const fields = [];
const ops = [];
const as = [];
if (childIndependentFieldsWithStep && childIndependentFieldsWithStep[childChannel]) {
if (crossedDataName) {
// If there is a crossed data, calculate max
fields.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
ops.push('max');
}
else {
// If there is no crossed data, just calculate distinct
fields.push(childIndependentFieldsWithStep[childChannel]);
ops.push('distinct');
}
// Although it is technically a max, just name it distinct so it's easier to refer to it
as.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
}
const { sortField, sortIndexField } = this[channel];
if (sortField) {
const { op = sort_DEFAULT_SORT_OP, field } = sortField;
fields.push(field);
ops.push(op);
as.push(channeldef_vgField(sortField, { forAs: true }));
}
else if (sortIndexField) {
fields.push(sortIndexField);
ops.push('max');
as.push(sortIndexField);
}
return {
name: this[channel].name,
// Use data from the crossed one if it exist
source: (crossedDataName !== null && crossedDataName !== void 0 ? crossedDataName : this.data),
transform: [
Object.assign({ type: 'aggregate', groupby: this[channel].fields }, (fields.length
? {
fields,
ops,
as
}
: {}))
]
};
}
assembleFacetHeaderData(childIndependentFieldsWithStep) {
var _a, _b;
const { columns } = this.model.layout;
const { layoutHeaders } = this.model.component;
const data = [];
const hasSharedAxis = {};
for (const headerChannel of HEADER_CHANNELS) {
for (const headerType of HEADER_TYPES) {
const headers = (_a = (layoutHeaders[headerChannel] && layoutHeaders[headerChannel][headerType]), (_a !== null && _a !== void 0 ? _a : []));
for (const header of headers) {
if (((_b = header.axes) === null || _b === void 0 ? void 0 : _b.length) > 0) {
hasSharedAxis[headerChannel] = true;
break;
}
}
}
if (hasSharedAxis[headerChannel]) {
const cardinality = `length(data("${this.facet.name}"))`;
const stop = headerChannel === 'row'
? columns
? { signal: `ceil(${cardinality} / ${columns})` }
: 1
: columns
? { signal: `min(${cardinality}, ${columns})` }
: { signal: cardinality };
data.push({
name: `${this.facet.name}_${headerChannel}`,
transform: [
{
type: 'sequence',
start: 0,
stop
}
]
});
}
}
const { row, column } = hasSharedAxis;
if (row || column) {
data.unshift(this.assembleRowColumnHeaderData('facet', null, childIndependentFieldsWithStep));
}
return data;
}
assemble() {
var _a, _b;
const data = [];
let crossedDataName = null;
const childIndependentFieldsWithStep = this.getChildIndependentFieldsWithStep();
const { column, row, facet } = this;
if (column && row && (childIndependentFieldsWithStep.x || childIndependentFieldsWithStep.y)) {
// Need to create a cross dataset to correctly calculate cardinality
crossedDataName = `cross_${this.column.name}_${this.row.name}`;
const fields = [].concat((_a = childIndependentFieldsWithStep.x, (_a !== null && _a !== void 0 ? _a : [])), (_b = childIndependentFieldsWithStep.y, (_b !== null && _b !== void 0 ? _b : [])));
const ops = fields.map(() => 'distinct');
data.push({
name: crossedDataName,
source: this.data,
transform: [
{
type: 'aggregate',
groupby: this.fields,
fields,
ops
}
]
});
}
for (const channel of [channel_COLUMN, channel_ROW]) {
if (this[channel]) {
data.push(this.assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep));
}
}
if (facet) {
const facetData = this.assembleFacetHeaderData(childIndependentFieldsWithStep);
if (facetData) {
data.push(...facetData);
}
}
return data;
}
}
//# sourceMappingURL=facet.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/formatparse.js
/**
* Remove quotes from a string.
*/
function formatparse_unquote(pattern) {
if ((pattern[0] === "'" && pattern[pattern.length - 1] === "'") ||
(pattern[0] === '"' && pattern[pattern.length - 1] === '"')) {
return pattern.slice(1, -1);
}
return pattern;
}
/**
* @param field The field.
* @param parse What to parse the field as.
*/
function formatparse_parseExpression(field, parse) {
const f = util_accessPathWithDatum(field);
if (parse === 'number') {
return `toNumber(${f})`;
}
else if (parse === 'boolean') {
return `toBoolean(${f})`;
}
else if (parse === 'string') {
return `toString(${f})`;
}
else if (parse === 'date') {
return `toDate(${f})`;
}
else if (parse === 'flatten') {
return f;
}
else if (parse.indexOf('date:') === 0) {
const specifier = formatparse_unquote(parse.slice(5, parse.length));
return `timeParse(${f},'${specifier}')`;
}
else if (parse.indexOf('utc:') === 0) {
const specifier = formatparse_unquote(parse.slice(4, parse.length));
return `utcParse(${f},'${specifier}')`;
}
else {
src_log_warn(log_message.unrecognizedParse(parse));
return null;
}
}
function formatparse_getImplicitFromFilterTransform(transform) {
const implicit = {};
forEachLeaf(transform.filter, filter => {
var _a;
if (predicate_isFieldPredicate(filter)) {
// Automatically add a parse node for filters with filter objects
let val = null;
// For EqualFilter, just use the equal property.
// For RangeFilter and OneOfFilter, all array members should have
// the same type, so we only use the first one.
if (predicate_isFieldEqualPredicate(filter)) {
val = filter.equal;
}
else if (predicate_isFieldRangePredicate(filter)) {
val = filter.range[0];
}
else if (predicate_isFieldOneOfPredicate(filter)) {
val = (_a = filter.oneOf, (_a !== null && _a !== void 0 ? _a : filter['in']))[0];
} // else -- for filter expression, we can't infer anything
if (val) {
if (datetime_isDateTime(val)) {
implicit[filter.field] = 'date';
}
else if (src_isNumber(val)) {
implicit[filter.field] = 'number';
}
else if (isString(val)) {
implicit[filter.field] = 'string';
}
}
if (filter.timeUnit) {
implicit[filter.field] = 'date';
}
}
});
return implicit;
}
/**
* Creates a parse node for implicit parsing from a model and updates ancestorParse.
*/
function formatparse_getImplicitFromEncoding(model) {
const implicit = {};
function add(fieldDef) {
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
implicit[fieldDef.field] = 'date';
}
else if (fieldDef.type === 'quantitative' &&
aggregate_isMinMaxOp(fieldDef.aggregate) // we need to parse numbers to support correct min and max
) {
implicit[fieldDef.field] = 'number';
}
else if (util_accessPathDepth(fieldDef.field) > 1) {
// For non-date/non-number (strings and booleans), derive a flattened field for a referenced nested field.
// (Parsing numbers / dates already flattens numeric and temporal fields.)
if (!(fieldDef.field in implicit)) {
implicit[fieldDef.field] = 'flatten';
}
}
else if (channeldef_isScaleFieldDef(fieldDef) && sort_isSortField(fieldDef.sort) && util_accessPathDepth(fieldDef.sort.field) > 1) {
// Flatten fields that we sort by but that are not otherwise flattened.
if (!(fieldDef.sort.field in implicit)) {
implicit[fieldDef.sort.field] = 'flatten';
}
}
}
if (model_isUnitModel(model) || model_isFacetModel(model)) {
// Parse encoded fields
model.forEachFieldDef((fieldDef, channel) => {
if (channeldef_isTypedFieldDef(fieldDef)) {
add(fieldDef);
}
else {
const mainChannel = channel_getMainRangeChannel(channel);
const mainFieldDef = model.fieldDef(mainChannel);
add(Object.assign(Object.assign({}, fieldDef), { type: mainFieldDef.type }));
}
});
}
// Parse quantitative dimension fields of path marks as numbers so that we sort them correctly.
if (model_isUnitModel(model)) {
const { mark, markDef, encoding } = model;
if (mark_isPathMark(mark) &&
// No need to sort by dimension if we have a connected scatterplot (order channel is present)
!model.encoding.order) {
const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';
const dimensionChannelDef = encoding[dimensionChannel];
if (channeldef_isFieldDef(dimensionChannelDef) &&
dimensionChannelDef.type === 'quantitative' &&
!(dimensionChannelDef.field in implicit)) {
implicit[dimensionChannelDef.field] = 'number';
}
}
}
return implicit;
}
/**
* Creates a parse node for implicit parsing from a model and updates ancestorParse.
*/
function formatparse_getImplicitFromSelection(model) {
const implicit = {};
if (model_isUnitModel(model) && model.component.selection) {
for (const name of util_keys(model.component.selection)) {
const selCmpt = model.component.selection[name];
for (const proj of selCmpt.project.items) {
if (!proj.channel && util_accessPathDepth(proj.field) > 1) {
implicit[proj.field] = 'flatten';
}
}
}
}
return implicit;
}
class formatparse_ParseNode extends dataflow_DataFlowNode {
constructor(parent, parse) {
super(parent);
this._parse = parse;
}
clone() {
return new formatparse_ParseNode(null, util_duplicate(this._parse));
}
hash() {
return `Parse ${util_hash(this._parse)}`;
}
/**
* Creates a parse node from a data.format.parse and updates ancestorParse.
*/
static makeExplicit(parent, model, ancestorParse) {
// Custom parse
let explicit = {};
const data = model.data;
if (!isGenerator(data) && data && data.format && data.format.parse) {
explicit = data.format.parse;
}
return this.makeWithAncestors(parent, explicit, {}, ancestorParse);
}
/**
* Creates a parse node from "explicit" parse and "implicit" parse and updates ancestorParse.
*/
static makeWithAncestors(parent, explicit, implicit, ancestorParse) {
// We should not parse what has already been parsed in a parent (explicitly or implicitly) or what has been derived (maked as "derived"). We also don't need to flatten a field that has already been parsed.
for (const field of util_keys(implicit)) {
const parsedAs = ancestorParse.getWithExplicit(field);
if (parsedAs.value !== undefined) {
// We always ignore derived fields even if they are implicitly defined because we expect users to create the right types.
if (parsedAs.explicit ||
parsedAs.value === implicit[field] ||
parsedAs.value === 'derived' ||
implicit[field] === 'flatten') {
delete implicit[field];
}
else {
src_log_warn(log_message.differentParse(field, implicit[field], parsedAs.value));
}
}
}
for (const field of util_keys(explicit)) {
const parsedAs = ancestorParse.get(field);
if (parsedAs !== undefined) {
// Don't parse a field again if it has been parsed with the same type already.
if (parsedAs === explicit[field]) {
delete explicit[field];
}
else {
src_log_warn(log_message.differentParse(field, explicit[field], parsedAs));
}
}
}
const parse = new split_Split(explicit, implicit);
// add the format parse from this model so that children don't parse the same field again
ancestorParse.copyAll(parse);
// copy only non-null parses
const p = {};
for (const key of util_keys(parse.combine())) {
const val = parse.get(key);
if (val !== null) {
p[key] = val;
}
}
if (util_keys(p).length === 0 || ancestorParse.parseNothing) {
return null;
}
return new formatparse_ParseNode(parent, p);
}
get parse() {
return this._parse;
}
merge(other) {
this._parse = Object.assign(Object.assign({}, this._parse), other.parse);
other.remove();
}
/**
* Assemble an object for Vega's format.parse property.
*/
assembleFormatParse() {
const formatParse = {};
for (const field of util_keys(this._parse)) {
const p = this._parse[field];
if (util_accessPathDepth(field) === 1) {
formatParse[field] = p;
}
}
return formatParse;
}
// format parse depends and produces all fields in its parse
producedFields() {
return new Set(util_keys(this._parse));
}
dependentFields() {
return new Set(util_keys(this._parse));
}
assembleTransforms(onlyNested = false) {
return util_keys(this._parse)
.filter(field => (onlyNested ? util_accessPathDepth(field) > 1 : true))
.map(field => {
const expr = formatparse_parseExpression(field, this._parse[field]);
if (!expr) {
return null;
}
const formula = {
type: 'formula',
expr,
as: util_removePathFromField(field) // Vega output is always flattened
};
return formula;
})
.filter(t => t !== null);
}
}
//# sourceMappingURL=formatparse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/joinaggregate.js
/**
* A class for the join aggregate transform nodes.
*/
class joinaggregate_JoinAggregateTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
}
clone() {
return new joinaggregate_JoinAggregateTransformNode(null, util_duplicate(this.transform));
}
addDimensions(fields) {
this.transform.groupby = util_unique(this.transform.groupby.concat(fields), d => d);
}
dependentFields() {
const out = new Set();
if (this.transform.groupby) {
this.transform.groupby.forEach(f => out.add(f));
}
this.transform.joinaggregate
.map(w => w.field)
.filter(f => f !== undefined)
.forEach(f => out.add(f));
return out;
}
producedFields() {
return new Set(this.transform.joinaggregate.map(this.getDefaultName));
}
getDefaultName(joinAggregateFieldDef) {
var _a;
return _a = joinAggregateFieldDef.as, (_a !== null && _a !== void 0 ? _a : channeldef_vgField(joinAggregateFieldDef));
}
hash() {
return `JoinAggregateTransform ${util_hash(this.transform)}`;
}
assemble() {
const fields = [];
const ops = [];
const as = [];
for (const joinaggregate of this.transform.joinaggregate) {
ops.push(joinaggregate.op);
as.push(this.getDefaultName(joinaggregate));
fields.push(joinaggregate.field === undefined ? null : joinaggregate.field);
}
const groupby = this.transform.groupby;
return Object.assign({ type: 'joinaggregate', as,
ops,
fields }, (groupby !== undefined ? { groupby } : {}));
}
}
//# sourceMappingURL=joinaggregate.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/stack.js
function stack_getStackByFields(model) {
return model.stack.stackBy.reduce((fields, by) => {
const fieldDef = by.fieldDef;
const _field = channeldef_vgField(fieldDef);
if (_field) {
fields.push(_field);
}
return fields;
}, []);
}
function stack_isValidAsArray(as) {
return isArray(as) && as.every(s => isString(s)) && as.length > 1;
}
class stack_StackNode extends dataflow_DataFlowNode {
constructor(parent, stack) {
super(parent);
this._stack = stack;
}
clone() {
return new stack_StackNode(null, util_duplicate(this._stack));
}
static makeFromTransform(parent, stackTransform) {
const { stack, groupby, as, offset = 'zero' } = stackTransform;
const sortFields = [];
const sortOrder = [];
if (stackTransform.sort !== undefined) {
for (const sortField of stackTransform.sort) {
sortFields.push(sortField.field);
sortOrder.push(util_getFirstDefined(sortField.order, 'ascending'));
}
}
const sort = {
field: sortFields,
order: sortOrder
};
let normalizedAs;
if (stack_isValidAsArray(as)) {
normalizedAs = as;
}
else if (isString(as)) {
normalizedAs = [as, as + '_end'];
}
else {
normalizedAs = [stackTransform.stack + '_start', stackTransform.stack + '_end'];
}
return new stack_StackNode(parent, {
stackField: stack,
groupby,
offset,
sort,
facetby: [],
as: normalizedAs
});
}
static makeFromEncoding(parent, model) {
const stackProperties = model.stack;
const { encoding } = model;
if (!stackProperties) {
return null;
}
let dimensionFieldDef;
if (stackProperties.groupbyChannel) {
const cDef = encoding[stackProperties.groupbyChannel];
dimensionFieldDef = channeldef_getTypedFieldDef(cDef); // Fair to cast as groupByChannel is always either x or y
}
const stackby = stack_getStackByFields(model);
const orderDef = model.encoding.order;
let sort;
if (isArray(orderDef) || channeldef_isFieldDef(orderDef)) {
sort = common_sortParams(orderDef);
}
else {
// default = descending by stackFields
// FIXME is the default here correct for binned fields?
sort = stackby.reduce((s, field) => {
s.field.push(field);
s.order.push('descending');
return s;
}, { field: [], order: [] });
}
return new stack_StackNode(parent, {
dimensionFieldDef,
stackField: model.vgField(stackProperties.fieldChannel),
facetby: [],
stackby,
sort,
offset: stackProperties.offset,
impute: stackProperties.impute,
as: [
model.vgField(stackProperties.fieldChannel, { suffix: 'start', forAs: true }),
model.vgField(stackProperties.fieldChannel, { suffix: 'end', forAs: true })
]
});
}
get stack() {
return this._stack;
}
addDimensions(fields) {
this._stack.facetby.push(...fields);
}
dependentFields() {
const out = new Set();
out.add(this._stack.stackField);
this.getGroupbyFields().forEach(f => out.add(f));
this._stack.facetby.forEach(f => out.add(f));
this._stack.sort.field.forEach(f => out.add(f));
return out;
}
producedFields() {
return new Set(this._stack.as);
}
hash() {
return `Stack ${util_hash(this._stack)}`;
}
getGroupbyFields() {
const { dimensionFieldDef, impute, groupby } = this._stack;
if (dimensionFieldDef) {
if (dimensionFieldDef.bin) {
if (impute) {
// For binned group by field with impute, we calculate bin_mid
// as we cannot impute two fields simultaneously
return [channeldef_vgField(dimensionFieldDef, { binSuffix: 'mid' })];
}
return [
// For binned group by field without impute, we need both bin (start) and bin_end
channeldef_vgField(dimensionFieldDef, {}),
channeldef_vgField(dimensionFieldDef, { binSuffix: 'end' })
];
}
return [channeldef_vgField(dimensionFieldDef)];
}
return (groupby !== null && groupby !== void 0 ? groupby : []);
}
assemble() {
const transform = [];
const { facetby, dimensionFieldDef, stackField: field, stackby, sort, offset, impute, as } = this._stack;
// Impute
if (impute && dimensionFieldDef) {
const { band = 0.5, bin } = dimensionFieldDef;
if (bin) {
// As we can only impute one field at a time, we need to calculate
// mid point for a binned field
transform.push({
type: 'formula',
expr: `${band}*` +
channeldef_vgField(dimensionFieldDef, { expr: 'datum' }) +
`+${1 - band}*` +
channeldef_vgField(dimensionFieldDef, { expr: 'datum', binSuffix: 'end' }),
as: channeldef_vgField(dimensionFieldDef, { binSuffix: 'mid', forAs: true })
});
}
transform.push({
type: 'impute',
field,
groupby: [...stackby, ...facetby],
key: channeldef_vgField(dimensionFieldDef, { binSuffix: 'mid' }),
method: 'value',
value: 0
});
}
// Stack
transform.push({
type: 'stack',
groupby: [...this.getGroupbyFields(), ...facetby],
field,
sort,
as,
offset
});
return transform;
}
}
//# sourceMappingURL=stack.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/window.js
/**
* A class for the window transform nodes
*/
class window_WindowTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
}
clone() {
return new window_WindowTransformNode(null, util_duplicate(this.transform));
}
addDimensions(fields) {
this.transform.groupby = util_unique(this.transform.groupby.concat(fields), d => d);
}
dependentFields() {
var _a, _b;
const out = new Set();
(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : [])).forEach(f => out.add(f));
(_b = this.transform.sort, (_b !== null && _b !== void 0 ? _b : [])).forEach(m => out.add(m.field));
this.transform.window
.map(w => w.field)
.filter(f => f !== undefined)
.forEach(f => out.add(f));
return out;
}
producedFields() {
return new Set(this.transform.window.map(this.getDefaultName));
}
getDefaultName(windowFieldDef) {
var _a;
return _a = windowFieldDef.as, (_a !== null && _a !== void 0 ? _a : channeldef_vgField(windowFieldDef));
}
hash() {
return `WindowTransform ${util_hash(this.transform)}`;
}
assemble() {
var _a;
const fields = [];
const ops = [];
const as = [];
const params = [];
for (const window of this.transform.window) {
ops.push(window.op);
as.push(this.getDefaultName(window));
params.push(window.param === undefined ? null : window.param);
fields.push(window.field === undefined ? null : window.field);
}
const frame = this.transform.frame;
const groupby = this.transform.groupby;
if (frame && frame[0] === null && frame[1] === null && ops.every(o => aggregate_isAggregateOp(o))) {
// when the window does not rely on any particular window ops or frame, switch to a simpler and more efficient joinaggregate
return Object.assign({ type: 'joinaggregate', as, ops: ops, fields }, (groupby !== undefined ? { groupby } : {}));
}
const sortFields = [];
const sortOrder = [];
if (this.transform.sort !== undefined) {
for (const sortField of this.transform.sort) {
sortFields.push(sortField.field);
sortOrder.push((_a = sortField.order, (_a !== null && _a !== void 0 ? _a : 'ascending')));
}
}
const sort = {
field: sortFields,
order: sortOrder
};
const ignorePeers = this.transform.ignorePeers;
return Object.assign(Object.assign(Object.assign({ type: 'window', params,
as,
ops,
fields,
sort }, (ignorePeers !== undefined ? { ignorePeers } : {})), (groupby !== undefined ? { groupby } : {})), (frame !== undefined ? { frame } : {}));
}
}
//# sourceMappingURL=window.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/identifier.js
class identifier_IdentifierNode extends dataflow_DataFlowNode {
clone() {
return new identifier_IdentifierNode(null);
}
constructor(parent) {
super(parent);
}
dependentFields() {
return new Set();
}
producedFields() {
return new Set([selection_SELECTION_ID]);
}
hash() {
return 'Identifier';
}
assemble() {
return { type: 'identifier', as: selection_SELECTION_ID };
}
}
//# sourceMappingURL=identifier.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/optimizers.js
/**
* Move parse nodes up to forks.
*/
class optimizers_MoveParseUp extends optimizer_BottomUpOptimizer {
run(node) {
const parent = node.parent;
// Move parse up by merging or swapping.
if (node instanceof formatparse_ParseNode) {
if (optimizer_isDataSourceNode(parent)) {
return this.flags;
}
if (parent.numChildren() > 1) {
// Don't move parse further up but continue with parent.
this.setContinue();
return this.flags;
}
if (parent instanceof formatparse_ParseNode) {
this.setMutated();
parent.merge(node);
}
else {
// Don't swap with nodes that produce something that the parse node depends on (e.g. lookup).
if (util_fieldIntersection(parent.producedFields(), node.dependentFields())) {
this.setContinue();
return this.flags;
}
this.setMutated();
node.swapWithParent();
}
}
this.setContinue();
return this.flags;
}
}
/**
* Merge identical nodes at forks by comparing hashes.
*
* Does not need to iterate from leaves so we implement this with recursion as it's a bit simpler.
*/
class optimizers_MergeIdenticalNodes extends optimizer_TopDownOptimizer {
mergeNodes(parent, nodes) {
const mergedNode = nodes.shift();
for (const node of nodes) {
parent.removeChild(node);
node.parent = mergedNode;
node.remove();
}
}
run(node) {
const hashes = node.children.map(x => x.hash());
const buckets = {};
for (let i = 0; i < hashes.length; i++) {
if (buckets[hashes[i]] === undefined) {
buckets[hashes[i]] = [node.children[i]];
}
else {
buckets[hashes[i]].push(node.children[i]);
}
}
for (const k of util_keys(buckets)) {
if (buckets[k].length > 1) {
this.setMutated();
this.mergeNodes(node, buckets[k]);
}
}
for (const child of node.children) {
this.run(child);
}
return this.mutatedFlag;
}
}
/**
* Repeatedly remove leaf nodes that are not output or facet nodes.
* The reason is that we don't need subtrees that don't have any output nodes.
* Facet nodes are needed for the row or column domains.
*/
class optimizers_RemoveUnusedSubtrees extends optimizer_BottomUpOptimizer {
run(node) {
if (node instanceof dataflow_OutputNode || node.numChildren() > 0 || node instanceof facet_FacetNode) {
// no need to continue with parent because it is output node or will have children (there was a fork)
return this.flags;
}
else {
this.setMutated();
node.remove();
}
return this.flags;
}
}
/**
* Removes duplicate time unit nodes (as determined by the name of the
* output field) that may be generated due to selections projected over
* time units.
*
* TODO: Try to make this a top down optimizer that keeps only the first
* insance of a time unit node.
* TODO: Try to make a generic version of this that only keeps one node per hash.
*/
class optimizers_RemoveDuplicateTimeUnits extends optimizer_BottomUpOptimizer {
constructor() {
super(...arguments);
this.fields = new Set();
this.prev = null;
}
run(node) {
this.setContinue();
if (node instanceof timeunit_TimeUnitNode) {
const pfields = node.producedFields();
if (util_hasIntersection(pfields, this.fields)) {
this.setMutated();
this.prev.remove();
}
else {
this.fields = new Set([...this.fields, ...pfields]);
}
this.prev = node;
}
return this.flags;
}
reset() {
this.fields.clear();
}
}
/**
* Merge adjacent time unit nodes.
*/
class optimizers_MergeTimeUnits extends optimizer_BottomUpOptimizer {
run(node) {
this.setContinue();
const parent = node.parent;
const timeUnitChildren = parent.children.filter(x => x instanceof timeunit_TimeUnitNode);
const combination = timeUnitChildren.pop();
for (const timeUnit of timeUnitChildren) {
this.setMutated();
combination.merge(timeUnit);
}
return this.flags;
}
}
/**
* Clones the subtree and ignores output nodes except for the leaves, which are renamed.
*/
function optimizers_cloneSubtree(facet) {
function clone(node) {
if (!(node instanceof facet_FacetNode)) {
const copy = node.clone();
if (copy instanceof dataflow_OutputNode) {
const newName = optimize_FACET_SCALE_PREFIX + copy.getSource();
copy.setSource(newName);
facet.model.component.data.outputNodes[newName] = copy;
}
else if (copy instanceof aggregate_AggregateNode ||
copy instanceof stack_StackNode ||
copy instanceof window_WindowTransformNode ||
copy instanceof joinaggregate_JoinAggregateTransformNode) {
copy.addDimensions(facet.fields);
}
node.children.flatMap(clone).forEach((n) => (n.parent = copy));
return [copy];
}
return node.children.flatMap(clone);
}
return clone;
}
/**
* Move facet nodes down to the next fork or output node. Also pull the main output with the facet node.
* After moving down the facet node, make a copy of the subtree and make it a child of the main output.
*/
function optimizers_moveFacetDown(node) {
if (node instanceof facet_FacetNode) {
if (node.numChildren() === 1 && !(node.children[0] instanceof dataflow_OutputNode)) {
// move down until we hit a fork or output node
const child = node.children[0];
if (child instanceof aggregate_AggregateNode ||
child instanceof stack_StackNode ||
child instanceof window_WindowTransformNode ||
child instanceof joinaggregate_JoinAggregateTransformNode) {
child.addDimensions(node.fields);
}
child.swapWithParent();
optimizers_moveFacetDown(node);
}
else {
// move main to facet
const facetMain = node.model.component.data.main;
optimizers_moveMainDownToFacet(facetMain);
// replicate the subtree and place it before the facet's main node
const cloner = optimizers_cloneSubtree(node);
const copy = node.children.map(cloner).flat();
for (const c of copy) {
c.parent = facetMain;
}
}
}
else {
node.children.map(optimizers_moveFacetDown);
}
}
function optimizers_moveMainDownToFacet(node) {
if (node instanceof dataflow_OutputNode && node.type === MAIN) {
if (node.numChildren() === 1) {
const child = node.children[0];
if (!(child instanceof facet_FacetNode)) {
child.swapWithParent();
optimizers_moveMainDownToFacet(node);
}
}
}
}
/**
* Remove output nodes that are not required. Starting from a root.
*/
class optimizers_RemoveUnnecessaryOutputNodes extends optimizer_TopDownOptimizer {
constructor() {
super();
}
run(node) {
if (node instanceof dataflow_OutputNode && !node.isRequired()) {
this.setMutated();
node.remove();
}
for (const child of node.children) {
this.run(child);
}
return this.mutatedFlag;
}
}
class optimizers_RemoveUnnecessaryIdentifierNodes extends optimizer_TopDownOptimizer {
constructor(model) {
super();
this.requiresSelectionId = model && selection_requiresSelectionId(model);
}
run(node) {
if (node instanceof identifier_IdentifierNode) {
// Only preserve IdentifierNodes if we have default discrete selections
// in our model tree, and if the nodes come after tuple producing nodes.
if (!(this.requiresSelectionId &&
(optimizer_isDataSourceNode(node.parent) || node.parent instanceof aggregate_AggregateNode || node.parent instanceof formatparse_ParseNode))) {
this.setMutated();
node.remove();
}
}
for (const child of node.children) {
this.run(child);
}
return this.mutatedFlag;
}
}
/**
* Inserts an intermediate ParseNode containing all non-conflicting parse fields and removes the empty ParseNodes.
*
* We assume that dependent paths that do not have a parse node can be just merged.
*/
class optimizers_MergeParse extends optimizer_BottomUpOptimizer {
run(node) {
const parent = node.parent;
const originalChildren = [...parent.children];
const parseChildren = parent.children.filter((child) => child instanceof formatparse_ParseNode);
if (parent.numChildren() > 1 && parseChildren.length >= 1) {
const commonParse = {};
const conflictingParse = new Set();
for (const parseNode of parseChildren) {
const parse = parseNode.parse;
for (const k of util_keys(parse)) {
if (!(k in commonParse)) {
commonParse[k] = parse[k];
}
else if (commonParse[k] !== parse[k]) {
conflictingParse.add(k);
}
}
}
for (const field of conflictingParse) {
delete commonParse[field];
}
if (util_keys(commonParse).length !== 0) {
this.setMutated();
const mergedParseNode = new formatparse_ParseNode(parent, commonParse);
for (const childNode of originalChildren) {
if (childNode instanceof formatparse_ParseNode) {
for (const key of util_keys(commonParse)) {
delete childNode.parse[key];
}
}
parent.removeChild(childNode);
childNode.parent = mergedParseNode;
// remove empty parse nodes
if (childNode instanceof formatparse_ParseNode && util_keys(childNode.parse).length === 0) {
childNode.remove();
}
}
}
}
this.setContinue();
return this.flags;
}
}
class optimizers_MergeAggregates extends optimizer_BottomUpOptimizer {
run(node) {
const parent = node.parent;
const aggChildren = parent.children.filter((child) => child instanceof aggregate_AggregateNode);
// Object which we'll use to map the fields which an aggregate is grouped by to
// the set of aggregates with that grouping. This is useful as only aggregates
// with the same group by can be merged
const groupedAggregates = {};
// Build groupedAggregates
for (const agg of aggChildren) {
const groupBys = util_hash(agg.groupBy);
if (!(groupBys in groupedAggregates)) {
groupedAggregates[groupBys] = [];
}
groupedAggregates[groupBys].push(agg);
}
// Merge aggregateNodes with same key in groupedAggregates
for (const group of util_keys(groupedAggregates)) {
const mergeableAggs = groupedAggregates[group];
if (mergeableAggs.length > 1) {
const mergedAggs = mergeableAggs.pop();
for (const agg of mergeableAggs) {
if (mergedAggs.merge(agg)) {
parent.removeChild(agg);
agg.parent = mergedAggs;
agg.remove();
this.setMutated();
}
}
}
}
this.setContinue();
return this.flags;
}
}
/**
* Merge bin nodes and move them up through forks. Stop at filters, parse, identifier as we want them to stay before the bin node.
*/
class optimizers_MergeBins extends optimizer_BottomUpOptimizer {
constructor(model) {
super();
this.model = model;
}
run(node) {
const parent = node.parent;
const moveBinsUp = !(optimizer_isDataSourceNode(parent) ||
parent instanceof filter_FilterNode ||
parent instanceof formatparse_ParseNode ||
parent instanceof identifier_IdentifierNode);
const promotableBins = [];
const remainingBins = [];
for (const child of parent.children) {
if (child instanceof bin_BinNode) {
if (moveBinsUp && !util_fieldIntersection(parent.producedFields(), child.dependentFields())) {
promotableBins.push(child);
}
else {
remainingBins.push(child);
}
}
}
if (promotableBins.length > 0) {
const promotedBin = promotableBins.pop();
for (const bin of promotableBins) {
promotedBin.merge(bin, this.model.renameSignal.bind(this.model));
}
this.setMutated();
if (parent instanceof bin_BinNode) {
parent.merge(promotedBin, this.model.renameSignal.bind(this.model));
}
else {
promotedBin.swapWithParent();
}
}
if (remainingBins.length > 1) {
const remainingBin = remainingBins.pop();
for (const bin of remainingBins) {
remainingBin.merge(bin, this.model.renameSignal.bind(this.model));
}
this.setMutated();
}
this.setContinue();
return this.flags;
}
}
/**
* This optimizer takes output nodes that are at a fork and moves them before the fork.
*
* The algorithm iterates over the children and tries to find the last output node in a cahin of output nodes.
* It then moves all output nodes before that main output node. All other children (and the children of the output nodes)
* are inserted after the main output node.
*/
class optimizers_MergeOutputs extends optimizer_BottomUpOptimizer {
run(node) {
const parent = node.parent;
const children = [...parent.children];
const hasOutputChild = util_some(children, child => child instanceof dataflow_OutputNode);
if (!hasOutputChild || parent.numChildren() <= 1) {
this.setContinue();
return this.flags;
}
const otherChildren = [];
// The output node we will connect all other nodes to
// output nodes will be added before, other nodes after
let mainOutput;
for (const child of children) {
if (child instanceof dataflow_OutputNode) {
let lastOutput = child;
while (lastOutput.numChildren() === 1) {
const theChild = lastOutput.children[0];
if (theChild instanceof dataflow_OutputNode) {
lastOutput = theChild;
}
else {
break;
}
}
otherChildren.push(...lastOutput.children);
if (mainOutput) {
// Move the output nodes before the mainOutput. We do this by setting
// the parent of the first not to the parent of the main output and
// the main output's parent to the last output.
// note: the child is the first output
parent.removeChild(child);
child.parent = mainOutput.parent;
mainOutput.parent.removeChild(mainOutput);
mainOutput.parent = lastOutput;
this.setMutated();
}
else {
mainOutput = lastOutput;
}
}
else {
otherChildren.push(child);
}
}
if (otherChildren.length) {
this.setMutated();
for (const child of otherChildren) {
child.parent.removeChild(child);
child.parent = mainOutput;
}
}
this.setContinue();
return this.flags;
}
}
//# sourceMappingURL=optimizers.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/optimize.js
const optimize_FACET_SCALE_PREFIX = 'scale_';
const optimize_MAX_OPTIMIZATION_RUNS = 5;
/**
* Return all leaf nodes.
*/
function optimize_getLeaves(roots) {
const leaves = [];
function append(node) {
if (node.numChildren() === 0) {
leaves.push(node);
}
else {
node.children.forEach(append);
}
}
roots.forEach(append);
return leaves;
}
function optimize_isTrue(x) {
return x;
}
/**
* Run the specified optimizer on the provided nodes.
*
* @param optimizer The optimizer instance to run.
* @param nodes A set of nodes to optimize.
* @param flag Flag that will be or'ed with return valued from optimization calls to the nodes.
*/
function optimize_runOptimizer(optimizer, nodes) {
const flags = nodes.map(node => {
if (optimizer instanceof optimizer_BottomUpOptimizer) {
const runFlags = optimizer.optimizeNextFromLeaves(node);
optimizer.reset();
return runFlags;
}
else {
return optimizer.run(node);
}
});
return flags.some(optimize_isTrue);
}
function optimize_optimizationDataflowHelper(dataComponent, model) {
let roots = dataComponent.sources;
const mutatedFlags = new Set();
mutatedFlags.add(optimize_runOptimizer(new optimizers_RemoveUnnecessaryOutputNodes(), roots));
mutatedFlags.add(optimize_runOptimizer(new optimizers_RemoveUnnecessaryIdentifierNodes(model), roots));
// remove source nodes that don't have any children because they also don't have output nodes
roots = roots.filter(r => r.numChildren() > 0);
mutatedFlags.add(optimize_runOptimizer(new optimizers_RemoveUnusedSubtrees(), optimize_getLeaves(roots)));
roots = roots.filter(r => r.numChildren() > 0);
mutatedFlags.add(optimize_runOptimizer(new optimizers_MoveParseUp(), optimize_getLeaves(roots)));
mutatedFlags.add(optimize_runOptimizer(new optimizers_MergeBins(model), optimize_getLeaves(roots)));
mutatedFlags.add(optimize_runOptimizer(new optimizers_RemoveDuplicateTimeUnits(), optimize_getLeaves(roots)));
mutatedFlags.add(optimize_runOptimizer(new optimizers_MergeParse(), optimize_getLeaves(roots)));
mutatedFlags.add(optimize_runOptimizer(new optimizers_MergeAggregates(), optimize_getLeaves(roots)));
mutatedFlags.add(optimize_runOptimizer(new optimizers_MergeTimeUnits(), optimize_getLeaves(roots)));
mutatedFlags.add(optimize_runOptimizer(new optimizers_MergeIdenticalNodes(), roots));
mutatedFlags.add(optimize_runOptimizer(new optimizers_MergeOutputs(), optimize_getLeaves(roots)));
dataComponent.sources = roots;
return mutatedFlags.has(true);
}
/**
* Optimizes the dataflow of the passed in data component.
*/
function optimize_optimizeDataflow(data, model) {
// check before optimizations
debug_checkLinks(data.sources);
let firstPassCounter = 0;
let secondPassCounter = 0;
for (let i = 0; i < optimize_MAX_OPTIMIZATION_RUNS; i++) {
if (!optimize_optimizationDataflowHelper(data, model)) {
break;
}
firstPassCounter++;
}
// move facets down and make a copy of the subtree so that we can have scales at the top level
data.sources.map(optimizers_moveFacetDown);
for (let i = 0; i < optimize_MAX_OPTIMIZATION_RUNS; i++) {
if (!optimize_optimizationDataflowHelper(data, model)) {
break;
}
secondPassCounter++;
}
// check after optimizations
debug_checkLinks(data.sources);
if (Math.max(firstPassCounter, secondPassCounter) === optimize_MAX_OPTIMIZATION_RUNS) {
src_log_warn(`Maximum optimization runs(${optimize_MAX_OPTIMIZATION_RUNS}) reached.`);
}
}
//# sourceMappingURL=optimize.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/signal.js
/**
* A class that behaves like a SignalRef but lazily generates the signal.
* The provided generator function should use `Model.getSignalName` to use the correct signal name.
*/
class SignalRefWrapper {
constructor(exprGenerator) {
Object.defineProperty(this, 'signal', {
enumerable: true,
get: exprGenerator
});
}
static fromName(rename, signalName) {
return new SignalRefWrapper(() => rename(signalName));
}
}
//# sourceMappingURL=signal.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/domain.js
function domain_parseScaleDomain(model) {
if (model_isUnitModel(model)) {
domain_parseUnitScaleDomain(model);
}
else {
domain_parseNonUnitScaleDomain(model);
}
}
function domain_parseUnitScaleDomain(model) {
const localScaleComponents = model.component.scales;
util_keys(localScaleComponents).forEach((channel) => {
const domains = domain_parseDomainForChannel(model, channel);
const localScaleCmpt = localScaleComponents[channel];
localScaleCmpt.setWithExplicit('domains', domains);
domain_parseSelectionDomain(model, channel);
if (model.component.data.isFaceted) {
// get resolve from closest facet parent as this decides whether we need to refer to cloned subtree or not
let facetParent = model;
while (!model_isFacetModel(facetParent) && facetParent.parent) {
facetParent = facetParent.parent;
}
const resolve = facetParent.component.resolve.scale[channel];
if (resolve === 'shared') {
for (const domain of domains.value) {
// Replace the scale domain with data output from a cloned subtree after the facet.
if (vega_schema_isDataRefDomain(domain)) {
// use data from cloned subtree (which is the same as data but with a prefix added once)
domain.data = optimize_FACET_SCALE_PREFIX + domain.data.replace(optimize_FACET_SCALE_PREFIX, '');
}
}
}
}
});
}
function domain_parseNonUnitScaleDomain(model) {
for (const child of model.children) {
domain_parseScaleDomain(child);
}
const localScaleComponents = model.component.scales;
util_keys(localScaleComponents).forEach((channel) => {
let domains;
let selectionExtent = null;
for (const child of model.children) {
const childComponent = child.component.scales[channel];
if (childComponent) {
if (domains === undefined) {
domains = childComponent.getWithExplicit('domains');
}
else {
domains = split_mergeValuesWithExplicit(domains, childComponent.getWithExplicit('domains'), 'domains', 'scale', domain_domainsTieBreaker);
}
const se = childComponent.get('selectionExtent');
if (selectionExtent && se && selectionExtent.selection !== se.selection) {
src_log_warn('The same selection must be used to override scale domains in a layered view.');
}
selectionExtent = se;
}
}
localScaleComponents[channel].setWithExplicit('domains', domains);
if (selectionExtent) {
localScaleComponents[channel].set('selectionExtent', selectionExtent, true);
}
});
}
/**
* Remove unaggregated domain if it is not applicable
* Add unaggregated domain if domain is not specified and config.scale.useUnaggregatedDomain is true.
*/
function domain_normalizeUnaggregatedDomain(domain, fieldDef, scaleType, scaleConfig) {
if (domain === 'unaggregated') {
const { valid, reason } = domain_canUseUnaggregatedDomain(fieldDef, scaleType);
if (!valid) {
src_log_warn(reason);
return undefined;
}
}
else if (domain === undefined && scaleConfig.useUnaggregatedDomain) {
// Apply config if domain is not specified.
const { valid } = domain_canUseUnaggregatedDomain(fieldDef, scaleType);
if (valid) {
return 'unaggregated';
}
}
return domain;
}
function domain_parseDomainForChannel(model, channel) {
const scaleType = model.getScaleComponent(channel).get('type');
const domain = domain_normalizeUnaggregatedDomain(model.scaleDomain(channel), model.fieldDef(channel), scaleType, model.config.scale);
if (domain !== model.scaleDomain(channel)) {
model.specifiedScales[channel] = Object.assign(Object.assign({}, model.specifiedScales[channel]), { domain });
}
// If channel is either X or Y then union them with X2 & Y2 if they exist
if (channel === 'x' && model.channelHasField('x2')) {
if (model.channelHasField('x')) {
return split_mergeValuesWithExplicit(domain_parseSingleChannelDomain(scaleType, domain, model, 'x'), domain_parseSingleChannelDomain(scaleType, domain, model, 'x2'), 'domain', 'scale', domain_domainsTieBreaker);
}
else {
return domain_parseSingleChannelDomain(scaleType, domain, model, 'x2');
}
}
else if (channel === 'y' && model.channelHasField('y2')) {
if (model.channelHasField('y')) {
return split_mergeValuesWithExplicit(domain_parseSingleChannelDomain(scaleType, domain, model, 'y'), domain_parseSingleChannelDomain(scaleType, domain, model, 'y2'), 'domain', 'scale', domain_domainsTieBreaker);
}
else {
return domain_parseSingleChannelDomain(scaleType, domain, model, 'y2');
}
}
return domain_parseSingleChannelDomain(scaleType, domain, model, channel);
}
function domain_mapDomainToDataSignal(domain, type, timeUnit) {
return domain.map(v => {
const data = channeldef_valueExpr(v, { timeUnit, type });
return { signal: `{data: ${data}}` };
});
}
function domain_parseSingleChannelDomain(scaleType, domain, model, channel) {
const fieldDef = model.fieldDef(channel);
if (domain && domain !== 'unaggregated' && !scale_isSelectionDomain(domain)) {
// explicit value
const { type, timeUnit } = fieldDef;
if (type === 'temporal' || timeUnit) {
return split_makeExplicit(domain_mapDomainToDataSignal(domain, type, timeUnit));
}
return split_makeExplicit([domain]);
}
const stack = model.stack;
if (stack && channel === stack.fieldChannel) {
if (stack.offset === 'normalize') {
return split_makeImplicit([[0, 1]]);
}
const data = model.requestDataName(MAIN);
return split_makeImplicit([
{
data,
field: model.vgField(channel, { suffix: 'start' })
},
{
data,
field: model.vgField(channel, { suffix: 'end' })
}
]);
}
const sort = channel_isScaleChannel(channel)
? domain_domainSort(model, channel, scaleType)
: undefined;
if (domain === 'unaggregated') {
const data = model.requestDataName(MAIN);
const { field } = fieldDef;
return split_makeImplicit([
{
data,
field: channeldef_vgField({ field, aggregate: 'min' })
},
{
data,
field: channeldef_vgField({ field, aggregate: 'max' })
}
]);
}
else if (bin_isBinning(fieldDef.bin)) {
if (scale_hasDiscreteDomain(scaleType)) {
if (scaleType === 'bin-ordinal') {
// we can omit the domain as it is inferred from the `bins` property
return split_makeImplicit([]);
}
// ordinal bin scale takes domain from bin_range, ordered by bin start
// This is useful for both axis-based scale (x/y) and legend-based scale (other channels).
return split_makeImplicit([
{
// If sort by aggregation of a specified sort field, we need to use RAW table,
// so we can aggregate values for the scale independently from the main aggregation.
data: util_isBoolean(sort) ? model.requestDataName(MAIN) : model.requestDataName(RAW),
// Use range if we added it and the scale does not support computing a range as a signal.
field: model.vgField(channel, channeldef_binRequiresRange(fieldDef, channel) ? { binSuffix: 'range' } : {}),
// we have to use a sort object if sort = true to make the sort correct by bin start
sort: sort === true || !isObject(sort)
? {
field: model.vgField(channel, {}),
op: 'min' // min or max doesn't matter since we sort by the start of the bin range
}
: sort
}
]);
}
else {
// continuous scales
const { bin } = fieldDef;
if (bin_isBinning(bin)) {
const binSignal = bin_getBinSignalName(model, fieldDef.field, bin);
return split_makeImplicit([
new SignalRefWrapper(() => {
const signal = model.getSignalName(binSignal);
return `[${signal}.start, ${signal}.stop]`;
})
]);
}
else {
return split_makeImplicit([
{
data: model.requestDataName(MAIN),
field: model.vgField(channel, {})
}
]);
}
}
}
else if (fieldDef.timeUnit &&
util_contains(['time', 'utc'], scaleType) &&
channeldef_hasBand(channel, fieldDef, model_isUnitModel(model) ? model.encoding[channel_getSecondaryRangeChannel(channel)] : undefined, model.markDef, model.config)) {
const data = model.requestDataName(MAIN);
return split_makeImplicit([
{
data,
field: model.vgField(channel)
},
{
data,
field: model.vgField(channel, { suffix: 'end' })
}
]);
}
else if (sort) {
return split_makeImplicit([
{
// If sort by aggregation of a specified sort field, we need to use RAW table,
// so we can aggregate values for the scale independently from the main aggregation.
data: util_isBoolean(sort) ? model.requestDataName(MAIN) : model.requestDataName(RAW),
field: model.vgField(channel),
sort: sort
}
]);
}
else {
return split_makeImplicit([
{
data: model.requestDataName(MAIN),
field: model.vgField(channel)
}
]);
}
}
function domain_normalizeSortField(sort, isStacked) {
const { op, field, order } = sort;
return Object.assign(Object.assign({
// Apply default op
op: (op !== null && op !== void 0 ? op : (isStacked ? 'sum' : sort_DEFAULT_SORT_OP)) }, (field ? { field: util_replacePathInField(field) } : {})), (order ? { order } : {}));
}
function domain_parseSelectionDomain(model, channel) {
const scale = model.component.scales[channel];
const spec = model.specifiedScales[channel].domain;
const bin = model.fieldDef(channel).bin;
const domain = scale_isSelectionDomain(spec) && spec;
const extent = bin_isBinParams(bin) && bin_isSelectionExtent(bin.extent) && bin.extent;
if (domain || extent) {
// As scale parsing occurs before selection parsing, we cannot set
// domainRaw directly. So instead, we store the selectionExtent on
// the scale component, and then add domainRaw during scale assembly.
scale.set('selectionExtent', (domain !== null && domain !== void 0 ? domain : extent), true);
}
}
function domain_domainSort(model, channel, scaleType) {
if (!scale_hasDiscreteDomain(scaleType)) {
return undefined;
}
// save to cast as the only exception is the geojson type for shape, which would not generate a scale
const fieldDef = model.fieldDef(channel);
const sort = fieldDef.sort;
// if the sort is specified with array, use the derived sort index field
if (sort_isSortArray(sort)) {
return {
op: 'min',
field: calculate_sortArrayIndexField(fieldDef, channel),
order: 'ascending'
};
}
const isStacked = model.stack !== null;
// Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale)
if (sort_isSortField(sort)) {
return domain_normalizeSortField(sort, isStacked);
}
else if (sort_isSortByEncoding(sort)) {
const { encoding, order } = sort;
const fieldDefToSortBy = model.fieldDef(encoding);
const { aggregate, field } = fieldDefToSortBy;
if (aggregate_isArgminDef(aggregate) || aggregate_isArgmaxDef(aggregate)) {
return domain_normalizeSortField({
field: channeldef_vgField(fieldDefToSortBy),
order
}, isStacked);
}
else if (aggregate_isAggregateOp(aggregate) || !aggregate) {
return domain_normalizeSortField({
op: aggregate,
field,
order
}, isStacked);
}
}
else if (sort === 'descending') {
return {
op: 'min',
field: model.vgField(channel),
order: 'descending'
};
}
else if (util_contains(['ascending', undefined /* default =ascending*/], sort)) {
return true;
}
// sort == null
return undefined;
}
/**
* Determine if a scale can use unaggregated domain.
* @return {Boolean} Returns true if all of the following conditions apply:
* 1. `scale.domain` is `unaggregated`
* 2. Aggregation function is not `count` or `sum`
* 3. The scale is quantitative or time scale.
*/
function domain_canUseUnaggregatedDomain(fieldDef, scaleType) {
const { aggregate, type } = fieldDef;
if (!aggregate) {
return {
valid: false,
reason: log_message.unaggregateDomainHasNoEffectForRawField(fieldDef)
};
}
if (isString(aggregate) && !aggregate_SHARED_DOMAIN_OP_INDEX[aggregate]) {
return {
valid: false,
reason: log_message.unaggregateDomainWithNonSharedDomainOp(aggregate)
};
}
if (type === 'quantitative') {
if (scaleType === 'log') {
return {
valid: false,
reason: log_message.unaggregatedDomainWithLogScale(fieldDef)
};
}
}
return { valid: true };
}
/**
* Tie breaker for mergeValuesWithExplicit for domains. We concat the specified values.
*/
function domain_domainsTieBreaker(v1, v2, property, propertyOf) {
if (v1.explicit && v2.explicit) {
src_log_warn(log_message.mergeConflictingDomainProperty(property, propertyOf, v1.value, v2.value));
}
// If equal score, concat the domains so that we union them later.
return { explicit: v1.explicit, value: [...v1.value, ...v2.value] };
}
/**
* Converts an array of domains to a single Vega scale domain.
*/
function domain_mergeDomains(domains) {
const uniqueDomains = util_unique(domains.map(domain => {
// ignore sort property when computing the unique domains
if (vega_schema_isDataRefDomain(domain)) {
const { sort: _s } = domain, domainWithoutSort = tslib_es6_rest(domain, ["sort"]);
return domainWithoutSort;
}
return domain;
}), util_hash);
const sorts = util_unique(domains
.map(d => {
if (vega_schema_isDataRefDomain(d)) {
const s = d.sort;
if (s !== undefined && !util_isBoolean(s)) {
if ('op' in s && s.op === 'count') {
// let's make sure that if op is count, we don't use a field
delete s.field;
}
if (s.order === 'ascending') {
// drop order: ascending as it is the default
delete s.order;
}
}
return s;
}
return undefined;
})
.filter(s => s !== undefined), util_hash);
if (uniqueDomains.length === 0) {
return undefined;
}
else if (uniqueDomains.length === 1) {
const domain = domains[0];
if (vega_schema_isDataRefDomain(domain) && sorts.length > 0) {
let sort = sorts[0];
if (sorts.length > 1) {
src_log_warn(log_message.MORE_THAN_ONE_SORT);
sort = true;
}
return Object.assign(Object.assign({}, domain), { sort });
}
return domain;
}
// only keep sort properties that work with unioned domains
const unionDomainSorts = util_unique(sorts.map(s => {
if (util_isBoolean(s) || !('op' in s) || s.op in aggregate_MULTIDOMAIN_SORT_OP_INDEX) {
return s;
}
src_log_warn(log_message.domainSortDropped(s));
return true;
}), util_hash);
let sort;
if (unionDomainSorts.length === 1) {
sort = unionDomainSorts[0];
}
else if (unionDomainSorts.length > 1) {
src_log_warn(log_message.MORE_THAN_ONE_SORT);
sort = true;
}
const allData = util_unique(domains.map(d => {
if (vega_schema_isDataRefDomain(d)) {
return d.data;
}
return null;
}), x => x);
if (allData.length === 1 && allData[0] !== null) {
// create a union domain of different fields with a single data source
const domain = Object.assign({ data: allData[0], fields: uniqueDomains.map(d => d.field) }, (sort ? { sort } : {}));
return domain;
}
return Object.assign({ fields: uniqueDomains }, (sort ? { sort } : {}));
}
/**
* Return a field if a scale single field.
* Return `undefined` otherwise.
*
*/
function domain_getFieldFromDomain(domain) {
if (vega_schema_isDataRefDomain(domain) && isString(domain.field)) {
return domain.field;
}
else if (vega_schema_isDataRefUnionedDomain(domain)) {
let field;
for (const nonUnionDomain of domain.fields) {
if (vega_schema_isDataRefDomain(nonUnionDomain) && isString(nonUnionDomain.field)) {
if (!field) {
field = nonUnionDomain.field;
}
else if (field !== nonUnionDomain.field) {
src_log_warn('Detected faceted independent scales that union domain of multiple fields from different data sources. We will use the first field. The result view size may be incorrect.');
return field;
}
}
}
src_log_warn('Detected faceted independent scales that union domain of identical fields from different source detected. We will assume that this is the same field from a different fork of the same data source. However, if this is not case, the result view size maybe incorrect.');
return field;
}
else if (vega_schema_isFieldRefUnionDomain(domain)) {
src_log_warn('Detected faceted independent scales that union domain of multiple fields from the same data source. We will use the first field. The result view size may be incorrect.');
const field = domain.fields[0];
return isString(field) ? field : undefined;
}
return undefined;
}
function domain_assembleDomain(model, channel) {
const scaleComponent = model.component.scales[channel];
const domains = scaleComponent.get('domains').map((domain) => {
// Correct references to data as the original domain's data was determined
// in parseScale, which happens before parseData. Thus the original data
// reference can be incorrect.
if (vega_schema_isDataRefDomain(domain)) {
domain.data = model.lookupDataSource(domain.data);
}
return domain;
});
// domains is an array that has to be merged into a single vega domain
return domain_mergeDomains(domains);
}
//# sourceMappingURL=domain.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/assemble.js
function assemble_assembleScales(model) {
if (model_isLayerModel(model) || model_isConcatModel(model) || model_isRepeatModel(model)) {
// For concat / layer / repeat, include scales of children too
return model.children.reduce((scales, child) => {
return scales.concat(assemble_assembleScales(child));
}, assemble_assembleScalesForModel(model));
}
else {
// For facet, child scales would not be included in the parent's scope.
// For unit, there is no child.
return assemble_assembleScalesForModel(model);
}
}
function assemble_assembleScalesForModel(model) {
return util_keys(model.component.scales).reduce((scales, channel) => {
const scaleComponent = model.component.scales[channel];
if (scaleComponent.merged) {
// Skipped merged scales
return scales;
}
const scale = scaleComponent.combine();
const { name, type, selectionExtent, domains: _d, range: _r } = scale, otherScaleProps = tslib_es6_rest(scale, ["name", "type", "selectionExtent", "domains", "range"]);
const range = assemble_assembleScaleRange(scale.range, name, channel);
let domainRaw;
if (selectionExtent) {
domainRaw = assemble_assembleSelectionScaleDomain(model, selectionExtent);
}
const domain = domain_assembleDomain(model, channel);
scales.push(Object.assign(Object.assign(Object.assign(Object.assign({ name,
type }, (domain ? { domain } : {})), (domainRaw ? { domainRaw } : {})), { range: range }), otherScaleProps));
return scales;
}, []);
}
function assemble_assembleScaleRange(scaleRange, scaleName, channel) {
// add signals to x/y range
if (channel === 'x' || channel === 'y') {
if (vega_schema_isVgRangeStep(scaleRange)) {
// For width/height step, use a signal created in layout assemble instead of a constant step.
return {
step: { signal: scaleName + '_step' }
};
}
}
return scaleRange;
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/component.js
class component_ScaleComponent extends split_Split {
constructor(name, typeWithExplicit) {
super({}, // no initial explicit property
{ name } // name as initial implicit property
);
this.merged = false;
this.setWithExplicit('type', typeWithExplicit);
}
/**
* Whether the scale definitely includes zero in the domain
*/
domainDefinitelyIncludesZero() {
if (this.get('zero') !== false) {
return true;
}
return util_some(this.get('domains'), d => isArray(d) && d.length === 2 && d[0] <= 0 && d[1] >= 0);
}
}
//# sourceMappingURL=component.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/range.js
const range_RANGE_PROPERTIES = ['range', 'scheme'];
function range_getSizeType(channel) {
return channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;
}
function range_parseUnitScaleRange(model) {
const localScaleComponents = model.component.scales;
// use SCALE_CHANNELS instead of scales[channel] to ensure that x, y come first!
channel_SCALE_CHANNELS.forEach((channel) => {
const localScaleCmpt = localScaleComponents[channel];
if (!localScaleCmpt) {
return;
}
const rangeWithExplicit = range_parseRangeForChannel(channel, model);
localScaleCmpt.setWithExplicit('range', rangeWithExplicit);
});
}
function range_getBinStepSignal(model, channel) {
const fieldDef = model.fieldDef(channel);
if (fieldDef && fieldDef.bin && bin_isBinning(fieldDef.bin)) {
const binSignal = bin_getBinSignalName(model, fieldDef.field, fieldDef.bin);
// TODO: extract this to be range step signal
const sizeType = range_getSizeType(channel);
const sizeSignal = model.getName(sizeType);
return new SignalRefWrapper(() => {
const updatedName = model.getSignalName(binSignal);
const binCount = `(${updatedName}.stop - ${updatedName}.start) / ${updatedName}.step`;
return `${model.getSignalName(sizeSignal)} / (${binCount})`;
});
}
return undefined;
}
/**
* Return mixins that includes one of the Vega range types (explicit range, range.step, range.scheme).
*/
function range_parseRangeForChannel(channel, model) {
const specifiedScale = model.specifiedScales[channel];
const { size } = model;
const mergedScaleCmpt = model.getScaleComponent(channel);
const scaleType = mergedScaleCmpt.get('type');
// Check if any of the range properties is specified.
// If so, check if it is compatible and make sure that we only output one of the properties
for (const property of range_RANGE_PROPERTIES) {
if (specifiedScale[property] !== undefined) {
const supportedByScaleType = scale_scaleTypeSupportProperty(scaleType, property);
const channelIncompatability = scale_channelScalePropertyIncompatability(channel, property);
if (!supportedByScaleType) {
src_log_warn(log_message.scalePropertyNotWorkWithScaleType(scaleType, property, channel));
}
else if (channelIncompatability) {
// channel
src_log_warn(channelIncompatability);
}
else {
switch (property) {
case 'range':
return split_makeExplicit(specifiedScale[property]);
case 'scheme':
return split_makeExplicit(range_parseScheme(specifiedScale[property]));
}
}
}
}
if (channel === channel_X || channel === channel_Y) {
const sizeChannel = channel === channel_X ? 'width' : 'height';
const sizeValue = size[sizeChannel];
if (base_isStep(sizeValue)) {
if (scale_hasDiscreteDomain(scaleType)) {
return split_makeExplicit({ step: sizeValue.step });
}
else {
src_log_warn(log_message.stepDropped(sizeChannel));
}
}
}
return split_makeImplicit(range_defaultRange(channel, model));
}
function range_parseScheme(scheme) {
if (scale_isExtendedScheme(scheme)) {
return Object.assign({ scheme: scheme.name }, util_omit(scheme, ['name']));
}
return { scheme: scheme };
}
function range_defaultRange(channel, model) {
const { size, config, mark } = model;
const getSignalName = model.getSignalName.bind(model);
const { type } = model.fieldDef(channel);
const mergedScaleCmpt = model.getScaleComponent(channel);
const scaleType = mergedScaleCmpt.get('type');
const { domain } = model.specifiedScales[channel];
switch (channel) {
case channel_X:
case channel_Y: {
// If there is no explicit width/height for discrete x/y scales
if (util_contains(['point', 'band'], scaleType)) {
if (channel === channel_X && !size.width) {
const w = config_getViewConfigDiscreteSize(config.view, 'width');
if (base_isStep(w)) {
return w;
}
}
else if (channel === channel_Y && !size.height) {
const h = config_getViewConfigDiscreteSize(config.view, 'height');
if (base_isStep(h)) {
return h;
}
}
}
// If step is null, use zero to width or height.
// Note that these range signals are temporary
// as they can be merged and renamed.
// (We do not have the right size signal here since parseLayoutSize() happens after parseScale().)
// We will later replace these temporary names with
// the final name in assembleScaleRange()
const sizeType = range_getSizeType(channel);
const sizeSignal = model.getName(sizeType);
if (channel === channel_Y && scale_hasContinuousDomain(scaleType)) {
// For y continuous scale, we have to start from the height as the bottom part has the max value.
return [SignalRefWrapper.fromName(getSignalName, sizeSignal), 0];
}
else {
return [0, SignalRefWrapper.fromName(getSignalName, sizeSignal)];
}
}
case channel_SIZE: {
// TODO: support custom rangeMin, rangeMax
const zero = model.component.scales[channel].get('zero');
const rangeMin = range_sizeRangeMin(mark, zero, config);
const rangeMax = range_sizeRangeMax(mark, size, model, config);
if (scale_isContinuousToDiscrete(scaleType)) {
return range_interpolateRange(rangeMin, rangeMax, range_defaultContinuousToDiscreteCount(scaleType, config, domain, channel));
}
else {
return [rangeMin, rangeMax];
}
}
case channel_STROKEWIDTH:
// TODO: support custom rangeMin, rangeMax
return [config.scale.minStrokeWidth, config.scale.maxStrokeWidth];
case channel_SHAPE:
return 'symbol';
case channel_COLOR:
case channel_FILL:
case channel_STROKE:
if (scaleType === 'ordinal') {
// Only nominal data uses ordinal scale by default
return type === 'nominal' ? 'category' : 'ordinal';
}
else {
return mark === 'rect' || mark === 'geoshape' ? 'heatmap' : 'ramp';
}
case channel_OPACITY:
case channel_FILLOPACITY:
case channel_STROKEOPACITY:
// TODO: support custom rangeMin, rangeMax
return [config.scale.minOpacity, config.scale.maxOpacity];
}
/* istanbul ignore next: should never reach here */
throw new Error(`Scale range undefined for channel ${channel}`);
}
function range_defaultContinuousToDiscreteCount(scaleType, config, domain, channel) {
switch (scaleType) {
case 'quantile':
return config.scale.quantileCount;
case 'quantize':
return config.scale.quantizeCount;
case 'threshold':
if (domain !== undefined && isArray(domain)) {
return domain.length + 1;
}
else {
src_log_warn(log_message.domainRequiredForThresholdScale(channel));
// default threshold boundaries for threshold scale since domain has cardinality of 2
return 3;
}
}
}
/**
* Returns the linear interpolation of the range according to the cardinality
*
* @param rangeMin start of the range
* @param rangeMax end of the range
* @param cardinality number of values in the output range
*/
function range_interpolateRange(rangeMin, rangeMax, cardinality) {
// always return a signal since it's better to compute the sequence in Vega later
const f = () => {
const rMax = vega_schema_isSignalRef(rangeMax) ? rangeMax.signal : rangeMax;
const step = `(${rMax} - ${rangeMin}) / (${cardinality} - 1)`;
return `sequence(${rangeMin}, ${rangeMax} + ${step}, ${step})`;
};
if (vega_schema_isSignalRef(rangeMax)) {
return new SignalRefWrapper(f);
}
else {
return { signal: f() };
}
}
function range_sizeRangeMin(mark, zero, config) {
if (zero) {
return 0;
}
switch (mark) {
case 'bar':
case 'tick':
return config.scale.minBandSize;
case 'line':
case 'trail':
case 'rule':
return config.scale.minStrokeWidth;
case 'text':
return config.scale.minFontSize;
case 'point':
case 'square':
case 'circle':
return config.scale.minSize;
}
/* istanbul ignore next: should never reach here */
// sizeRangeMin not implemented for the mark
throw new Error(log_message.incompatibleChannel('size', mark));
}
const range_MAX_SIZE_RANGE_STEP_RATIO = 0.95;
function range_sizeRangeMax(mark, size, model, config) {
const xyStepSignals = {
x: range_getBinStepSignal(model, 'x'),
y: range_getBinStepSignal(model, 'y')
};
switch (mark) {
case 'bar':
case 'tick': {
if (config.scale.maxBandSize !== undefined) {
return config.scale.maxBandSize;
}
const min = range_minXYStep(size, xyStepSignals, config.view);
if (src_isNumber(min)) {
return min - 1;
}
else {
return new SignalRefWrapper(() => `${min.signal} - 1`);
}
}
case 'line':
case 'trail':
case 'rule':
return config.scale.maxStrokeWidth;
case 'text':
return config.scale.maxFontSize;
case 'point':
case 'square':
case 'circle': {
if (config.scale.maxSize) {
return config.scale.maxSize;
}
const pointStep = range_minXYStep(size, xyStepSignals, config.view);
if (src_isNumber(pointStep)) {
return Math.pow(range_MAX_SIZE_RANGE_STEP_RATIO * pointStep, 2);
}
else {
return new SignalRefWrapper(() => `pow(${range_MAX_SIZE_RANGE_STEP_RATIO} * ${pointStep.signal}, 2)`);
}
}
}
/* istanbul ignore next: should never reach here */
// sizeRangeMax not implemented for the mark
throw new Error(log_message.incompatibleChannel('size', mark));
}
/**
* @returns {number} Range step of x or y or minimum between the two if both are ordinal scale.
*/
function range_minXYStep(size, xyStepSignals, viewConfig) {
const widthStep = base_isStep(size.width) ? size.width.step : config_getViewConfigDiscreteStep(viewConfig, 'width');
const heightStep = base_isStep(size.height) ? size.height.step : config_getViewConfigDiscreteStep(viewConfig, 'height');
if (xyStepSignals.x || xyStepSignals.y) {
return new SignalRefWrapper(() => {
const exprs = [
xyStepSignals.x ? xyStepSignals.x.signal : widthStep,
xyStepSignals.y ? xyStepSignals.y.signal : heightStep
];
return `min(${exprs.join(', ')})`;
});
}
return Math.min(widthStep, heightStep);
}
//# sourceMappingURL=range.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/properties.js
function properties_parseScaleProperty(model, property) {
if (model_isUnitModel(model)) {
properties_parseUnitScaleProperty(model, property);
}
else {
properties_parseNonUnitScaleProperty(model, property);
}
}
function properties_parseUnitScaleProperty(model, property) {
const localScaleComponents = model.component.scales;
util_keys(localScaleComponents).forEach((channel) => {
const specifiedScale = model.specifiedScales[channel];
const localScaleCmpt = localScaleComponents[channel];
const mergedScaleCmpt = model.getScaleComponent(channel);
const fieldDef = model.fieldDef(channel);
const config = model.config;
const specifiedValue = specifiedScale[property];
const sType = mergedScaleCmpt.get('type');
const supportedByScaleType = scale_scaleTypeSupportProperty(sType, property);
const channelIncompatability = scale_channelScalePropertyIncompatability(channel, property);
if (specifiedValue !== undefined) {
// If there is a specified value, check if it is compatible with scale type and channel
if (!supportedByScaleType) {
src_log_warn(log_message.scalePropertyNotWorkWithScaleType(sType, property, channel));
}
else if (channelIncompatability) {
// channel
src_log_warn(channelIncompatability);
}
}
if (supportedByScaleType && channelIncompatability === undefined) {
if (specifiedValue !== undefined) {
// copyKeyFromObject ensures type safety
localScaleCmpt.copyKeyFromObject(property, specifiedScale);
}
else {
const value = properties_getDefaultValue(property, model, channel, fieldDef, mergedScaleCmpt.get('type'), mergedScaleCmpt.get('padding'), mergedScaleCmpt.get('paddingInner'), specifiedScale.domain, model.markDef, config);
if (value !== undefined) {
localScaleCmpt.set(property, value, false);
}
}
}
});
}
// Note: This method is used in Voyager.
function properties_getDefaultValue(property, model, channel, fieldDef, scaleType, scalePadding, scalePaddingInner, specifiedDomain, markDef, config) {
const scaleConfig = config.scale;
const { type, sort } = fieldDef;
// If we have default rule-base, determine default value first
switch (property) {
case 'bins':
return properties_bins(model, fieldDef);
case 'interpolate':
return properties_interpolate(channel, type);
case 'nice':
return properties_nice(scaleType, channel, fieldDef);
case 'padding':
return properties_padding(channel, scaleType, scaleConfig, fieldDef, markDef, config.bar);
case 'paddingInner':
return properties_paddingInner(scalePadding, channel, markDef.type, scaleConfig);
case 'paddingOuter':
return properties_paddingOuter(scalePadding, channel, scaleType, markDef.type, scalePaddingInner, scaleConfig);
case 'reverse':
return properties_reverse(scaleType, sort);
case 'zero':
return properties_zero(channel, fieldDef, specifiedDomain, markDef, scaleType);
}
// Otherwise, use scale config
return scaleConfig[property];
}
// This method is here rather than in range.ts to avoid circular dependency.
function properties_parseScaleRange(model) {
if (model_isUnitModel(model)) {
range_parseUnitScaleRange(model);
}
else {
properties_parseNonUnitScaleProperty(model, 'range');
}
}
function properties_parseNonUnitScaleProperty(model, property) {
const localScaleComponents = model.component.scales;
for (const child of model.children) {
if (property === 'range') {
properties_parseScaleRange(child);
}
else {
properties_parseScaleProperty(child, property);
}
}
util_keys(localScaleComponents).forEach((channel) => {
let valueWithExplicit;
for (const child of model.children) {
const childComponent = child.component.scales[channel];
if (childComponent) {
const childValueWithExplicit = childComponent.getWithExplicit(property);
valueWithExplicit = split_mergeValuesWithExplicit(valueWithExplicit, childValueWithExplicit, property, 'scale', split_tieBreakByComparing((v1, v2) => {
switch (property) {
case 'range':
// For step, prefer larger step
if (v1.step && v2.step) {
return v1.step - v2.step;
}
return 0;
// TODO: precedence rule for other properties
}
return 0;
}));
}
}
localScaleComponents[channel].setWithExplicit(property, valueWithExplicit);
});
}
function properties_bins(model, fieldDef) {
const bin = fieldDef.bin;
if (bin_isBinning(bin)) {
const binSignal = bin_getBinSignalName(model, fieldDef.field, bin);
return new SignalRefWrapper(() => {
return model.getSignalName(binSignal);
});
}
else if (bin_isBinned(bin) && bin_isBinParams(bin) && bin.step !== undefined) {
// start and stop will be determined from the scale domain
return {
step: bin.step
};
}
return undefined;
}
function properties_interpolate(channel, type) {
if (util_contains([channel_COLOR, channel_FILL, channel_STROKE], channel) && type !== 'nominal') {
return 'hcl';
}
return undefined;
}
function properties_nice(scaleType, channel, fieldDef) {
if (fieldDef.bin || util_contains([scale_ScaleType.TIME, scale_ScaleType.UTC], scaleType)) {
return undefined;
}
return util_contains([channel_X, channel_Y], channel) ? true : undefined;
}
function properties_padding(channel, scaleType, scaleConfig, fieldDef, markDef, barConfig) {
if (util_contains([channel_X, channel_Y], channel)) {
if (scale_isContinuousToContinuous(scaleType)) {
if (scaleConfig.continuousPadding !== undefined) {
return scaleConfig.continuousPadding;
}
const { type, orient } = markDef;
if (type === 'bar' && !fieldDef.bin && !fieldDef.timeUnit) {
if ((orient === 'vertical' && channel === 'x') || (orient === 'horizontal' && channel === 'y')) {
return barConfig.continuousBandSize;
}
}
}
if (scaleType === scale_ScaleType.POINT) {
return scaleConfig.pointPadding;
}
}
return undefined;
}
function properties_paddingInner(paddingValue, channel, mark, scaleConfig) {
if (paddingValue !== undefined) {
// If user has already manually specified "padding", no need to add default paddingInner.
return undefined;
}
if (util_contains([channel_X, channel_Y], channel)) {
// Padding is only set for X and Y by default.
// Basically it doesn't make sense to add padding for color and size.
// paddingOuter would only be called if it's a band scale, just return the default for bandScale.
const { bandPaddingInner, barBandPaddingInner, rectBandPaddingInner } = scaleConfig;
return util_getFirstDefined(bandPaddingInner, mark === 'bar' ? barBandPaddingInner : rectBandPaddingInner);
}
return undefined;
}
function properties_paddingOuter(paddingValue, channel, scaleType, mark, paddingInnerValue, scaleConfig) {
if (paddingValue !== undefined) {
// If user has already manually specified "padding", no need to add default paddingOuter.
return undefined;
}
if (util_contains([channel_X, channel_Y], channel)) {
// Padding is only set for X and Y by default.
// Basically it doesn't make sense to add padding for color and size.
if (scaleType === scale_ScaleType.BAND) {
const { bandPaddingOuter } = scaleConfig;
return util_getFirstDefined(bandPaddingOuter,
/* By default, paddingOuter is paddingInner / 2. The reason is that
size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter).
and we want the width/height to be integer by default.
Note that step (by default) and cardinality are integers.) */
paddingInnerValue / 2);
}
}
return undefined;
}
function properties_reverse(scaleType, sort) {
if (scale_hasContinuousDomain(scaleType) && sort === 'descending') {
// For continuous domain scales, Vega does not support domain sort.
// Thus, we reverse range instead if sort is descending
return true;
}
return undefined;
}
function properties_zero(channel, fieldDef, specifiedDomain, markDef, scaleType) {
// If users explicitly provide a domain range, we should not augment zero as that will be unexpected.
const hasCustomDomain = !!specifiedDomain && specifiedDomain !== 'unaggregated';
if (hasCustomDomain) {
if (scale_hasContinuousDomain(scaleType)) {
if (isArray(specifiedDomain)) {
const first = specifiedDomain[0];
const last = specifiedDomain[specifiedDomain.length - 1];
if (first <= 0 && last >= 0) {
// if the domain includes zero, make zero remains true
return true;
}
}
return false;
}
}
// If there is no custom domain, return true only for the following cases:
// 1) using quantitative field with size
// While this can be either ratio or interval fields, our assumption is that
// ratio are more common. However, if the scaleType is discretizing scale, we want to return
// false so that range doesn't start at zero
if (channel === 'size' && fieldDef.type === 'quantitative' && !scale_isContinuousToDiscrete(scaleType)) {
return true;
}
// 2) non-binned, quantitative x-scale or y-scale
// (For binning, we should not include zero by default because binning are calculated without zero.)
if (!fieldDef.bin && util_contains([channel_X, channel_Y], channel)) {
const { orient, type } = markDef;
if (util_contains(['bar', 'area', 'line', 'trail'], type)) {
if ((orient === 'horizontal' && channel === 'y') || (orient === 'vertical' && channel === 'x')) {
return false;
}
}
return true;
}
return false;
}
//# sourceMappingURL=properties.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/type.js
/**
* Determine if there is a specified scale type and if it is appropriate,
* or determine default type if type is unspecified or inappropriate.
*/
// NOTE: CompassQL uses this method.
function type_scaleType(specifiedScale, channel, fieldDef, mark) {
const defaultScaleType = type_defaultType(channel, fieldDef, mark);
const { type } = specifiedScale;
if (!channel_isScaleChannel(channel)) {
// There is no scale for these channels
return null;
}
if (type !== undefined) {
// Check if explicitly specified scale type is supported by the channel
if (!scale_channelSupportScaleType(channel, type)) {
src_log_warn(log_message.scaleTypeNotWorkWithChannel(channel, type, defaultScaleType));
return defaultScaleType;
}
// Check if explicitly specified scale type is supported by the data type
if (!scale_scaleTypeSupportDataType(type, fieldDef.type)) {
src_log_warn(log_message.scaleTypeNotWorkWithFieldDef(type, defaultScaleType));
return defaultScaleType;
}
return type;
}
return defaultScaleType;
}
/**
* Determine appropriate default scale type.
*/
// NOTE: Voyager uses this method.
function type_defaultType(channel, fieldDef, mark) {
switch (fieldDef.type) {
case 'nominal':
case 'ordinal':
if (channel_isColorChannel(channel) || channel_rangeType(channel) === 'discrete') {
if (channel === 'shape' && fieldDef.type === 'ordinal') {
src_log_warn(log_message.discreteChannelCannotEncode(channel, 'ordinal'));
}
return 'ordinal';
}
if (util_contains(['x', 'y'], channel)) {
if (util_contains(['rect', 'bar', 'image', 'rule'], mark)) {
// The rect/bar mark should fit into a band.
// For rule, using band scale to make rule align with axis ticks better https://github.com/vega/vega-lite/issues/3429
return 'band';
}
}
// Otherwise, use ordinal point scale so we can easily get center positions of the marks.
return 'point';
case 'temporal':
if (channel_isColorChannel(channel)) {
return 'time';
}
else if (channel_rangeType(channel) === 'discrete') {
src_log_warn(log_message.discreteChannelCannotEncode(channel, 'temporal'));
// TODO: consider using quantize (equivalent to binning) once we have it
return 'ordinal';
}
return 'time';
case 'quantitative':
if (channel_isColorChannel(channel)) {
if (bin_isBinning(fieldDef.bin)) {
return 'bin-ordinal';
}
return 'linear';
}
else if (channel_rangeType(channel) === 'discrete') {
src_log_warn(log_message.discreteChannelCannotEncode(channel, 'quantitative'));
// TODO: consider using quantize (equivalent to binning) once we have it
return 'ordinal';
}
return 'linear';
case 'geojson':
return undefined;
}
/* istanbul ignore next: should never reach this */
throw new Error(log_message.invalidFieldType(fieldDef.type));
}
//# sourceMappingURL=type.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/scale/parse.js
function parse_parseScales(model, { ignoreRange } = {}) {
parse_parseScaleCore(model);
domain_parseScaleDomain(model);
for (const prop of scale_NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES) {
properties_parseScaleProperty(model, prop);
}
if (!ignoreRange) {
// range depends on zero
properties_parseScaleRange(model);
}
}
function parse_parseScaleCore(model) {
if (model_isUnitModel(model)) {
model.component.scales = parse_parseUnitScaleCore(model);
}
else {
model.component.scales = parse_parseNonUnitScaleCore(model);
}
}
/**
* Parse scales for all channels of a model.
*/
function parse_parseUnitScaleCore(model) {
const { encoding, mark } = model;
return channel_SCALE_CHANNELS.reduce((scaleComponents, channel) => {
let fieldDef;
let specifiedScale;
const channelDef = encoding[channel];
// Don't generate scale for shape of geoshape
if (channeldef_isFieldDef(channelDef) && mark === mark_GEOSHAPE && channel === channel_SHAPE && channelDef.type === GEOJSON) {
return scaleComponents;
}
if (channeldef_isFieldDef(channelDef)) {
fieldDef = channelDef;
specifiedScale = channelDef.scale;
}
else if (channeldef_hasConditionalFieldDef(channelDef)) {
// Need to specify generic for hasConditionalFieldDef as the value type can vary across channels
fieldDef = channelDef.condition;
specifiedScale = channelDef.condition['scale']; // We use ['scale'] since we know that channel here has scale for sure
}
if (fieldDef && specifiedScale !== null && specifiedScale !== false) {
specifiedScale = (specifiedScale !== null && specifiedScale !== void 0 ? specifiedScale : {});
const sType = type_scaleType(specifiedScale, channel, fieldDef, mark);
scaleComponents[channel] = new component_ScaleComponent(model.scaleName(channel + '', true), {
value: sType,
explicit: specifiedScale.type === sType
});
}
return scaleComponents;
}, {});
}
const parse_scaleTypeTieBreaker = split_tieBreakByComparing((st1, st2) => scale_scaleTypePrecedence(st1) - scale_scaleTypePrecedence(st2));
function parse_parseNonUnitScaleCore(model) {
const scaleComponents = (model.component.scales = {});
const scaleTypeWithExplicitIndex = {};
const resolve = model.component.resolve;
// Parse each child scale and determine if a particular channel can be merged.
for (const child of model.children) {
parse_parseScaleCore(child);
// Instead of always merging right away -- check if it is compatible to merge first!
util_keys(child.component.scales).forEach((channel) => {
var _a;
// if resolve is undefined, set default first
resolve.scale[channel] = (_a = resolve.scale[channel], (_a !== null && _a !== void 0 ? _a : resolve_defaultScaleResolve(channel, model)));
if (resolve.scale[channel] === 'shared') {
const explicitScaleType = scaleTypeWithExplicitIndex[channel];
const childScaleType = child.component.scales[channel].getWithExplicit('type');
if (explicitScaleType) {
if (scale_scaleCompatible(explicitScaleType.value, childScaleType.value)) {
// merge scale component if type are compatible
scaleTypeWithExplicitIndex[channel] = split_mergeValuesWithExplicit(explicitScaleType, childScaleType, 'type', 'scale', parse_scaleTypeTieBreaker);
}
else {
// Otherwise, update conflicting channel to be independent
resolve.scale[channel] = 'independent';
// Remove from the index so they don't get merged
delete scaleTypeWithExplicitIndex[channel];
}
}
else {
scaleTypeWithExplicitIndex[channel] = childScaleType;
}
}
});
}
// Merge each channel listed in the index
for (const channel of util_keys(scaleTypeWithExplicitIndex)) {
// Create new merged scale component
const name = model.scaleName(channel, true);
const typeWithExplicit = scaleTypeWithExplicitIndex[channel];
scaleComponents[channel] = new component_ScaleComponent(name, typeWithExplicit);
// rename each child and mark them as merged
for (const child of model.children) {
const childScale = child.component.scales[channel];
if (childScale) {
child.renameScale(childScale.get('name'), name);
childScale.merged = true;
}
}
}
return scaleComponents;
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/model.js
class model_NameMap {
constructor() {
this.nameMap = {};
}
rename(oldName, newName) {
this.nameMap[oldName] = newName;
}
has(name) {
return this.nameMap[name] !== undefined;
}
get(name) {
// If the name appears in the _nameMap, we need to read its new name.
// We have to loop over the dict just in case the new name also gets renamed.
while (this.nameMap[name] && name !== this.nameMap[name]) {
name = this.nameMap[name];
}
return name;
}
}
/*
We use type guards instead of `instanceof` as `instanceof` makes
different parts of the compiler depend on the actual implementation of
the model classes, which in turn depend on different parts of the compiler.
Thus, `instanceof` leads to circular dependency problems.
On the other hand, type guards only make different parts of the compiler
depend on the type of the model classes, but not the actual implementation.
*/
function model_isUnitModel(model) {
var _a;
return ((_a = model) === null || _a === void 0 ? void 0 : _a.type) === 'unit';
}
function model_isFacetModel(model) {
var _a;
return ((_a = model) === null || _a === void 0 ? void 0 : _a.type) === 'facet';
}
function model_isRepeatModel(model) {
var _a;
return ((_a = model) === null || _a === void 0 ? void 0 : _a.type) === 'repeat';
}
function model_isConcatModel(model) {
var _a;
return ((_a = model) === null || _a === void 0 ? void 0 : _a.type) === 'concat';
}
function model_isLayerModel(model) {
var _a;
return ((_a = model) === null || _a === void 0 ? void 0 : _a.type) === 'layer';
}
class model_Model {
constructor(spec, type, parent, parentGivenName, config, repeater, resolve, view) {
var _a, _b;
this.type = type;
this.parent = parent;
this.config = config;
this.repeater = repeater;
this.view = view;
this.children = [];
/**
* Corrects the data references in marks after assemble.
*/
this.correctDataNames = (mark) => {
// TODO: make this correct
// for normal data references
if (mark.from && mark.from.data) {
mark.from.data = this.lookupDataSource(mark.from.data);
}
// for access to facet data
if (mark.from && mark.from.facet && mark.from.facet.data) {
mark.from.facet.data = this.lookupDataSource(mark.from.facet.data);
}
return mark;
};
this.parent = parent;
this.config = config;
this.repeater = repeater;
// If name is not provided, always use parent's givenName to avoid name conflicts.
this.name = (_a = spec.name, (_a !== null && _a !== void 0 ? _a : parentGivenName));
this.title = title_isText(spec.title) ? { text: spec.title } : spec.title;
// Shared name maps
this.scaleNameMap = parent ? parent.scaleNameMap : new model_NameMap();
this.projectionNameMap = parent ? parent.projectionNameMap : new model_NameMap();
this.signalNameMap = parent ? parent.signalNameMap : new model_NameMap();
this.data = spec.data;
this.description = spec.description;
this.transforms = transform_normalizeTransform((_b = spec.transform, (_b !== null && _b !== void 0 ? _b : [])));
this.layout = isUnitSpec(spec) || isLayerSpec(spec) ? {} : base_extractCompositionLayout(spec, type, config);
this.component = {
data: {
sources: parent ? parent.component.data.sources : [],
outputNodes: parent ? parent.component.data.outputNodes : {},
outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {},
// data is faceted if the spec is a facet spec or the parent has faceted data and data is undefined
isFaceted: isFacetSpec(spec) || (parent && parent.component.data.isFaceted && spec.data === undefined)
},
layoutSize: new split_Split(),
layoutHeaders: { row: {}, column: {}, facet: {} },
mark: null,
resolve: Object.assign({ scale: {}, axis: {}, legend: {} }, (resolve ? util_duplicate(resolve) : {})),
selection: null,
scales: null,
projection: null,
axes: {},
legends: {}
};
}
get width() {
return this.getSizeSignalRef('width');
}
get height() {
return this.getSizeSignalRef('height');
}
parse() {
this.parseScale();
this.parseLayoutSize(); // depends on scale
this.renameTopLevelLayoutSizeSignal();
this.parseSelections();
this.parseProjection();
this.parseData(); // (pathorder) depends on markDef; selection filters depend on parsed selections; depends on projection because some transforms require the finalized projection name.
this.parseAxesAndHeaders(); // depends on scale and layout size
this.parseLegends(); // depends on scale, markDef
this.parseMarkGroup(); // depends on data name, scale, layout size, axisGroup, and children's scale, axis, legend and mark.
}
parseScale() {
parse_parseScales(this);
}
parseProjection() {
parse_parseProjection(this);
}
/**
* Rename top-level spec's size to be just width / height, ignoring model name.
* This essentially merges the top-level spec's width/height signals with the width/height signals
* to help us reduce redundant signals declaration.
*/
renameTopLevelLayoutSizeSignal() {
if (this.getName('width') !== 'width') {
this.renameSignal(this.getName('width'), 'width');
}
if (this.getName('height') !== 'height') {
this.renameSignal(this.getName('height'), 'height');
}
}
parseLegends() {
parse_parseLegend(this);
}
assembleGroupStyle() {
var _a, _b;
if (this.type === 'unit' || this.type === 'layer') {
return _b = (_a = this.view) === null || _a === void 0 ? void 0 : _a.style, (_b !== null && _b !== void 0 ? _b : 'cell');
}
return undefined;
}
assembleEncodeFromView(view) {
// Exclude "style"
const { style: _ } = view, baseView = tslib_es6_rest(view, ["style"]);
const e = {};
for (const property in baseView) {
if (src_hasOwnProperty(baseView, property)) {
const value = baseView[property];
if (value !== undefined) {
e[property] = { value };
}
}
}
return e;
}
assembleGroupEncodeEntry(isTopLevel) {
let encodeEntry = undefined;
if (this.view) {
encodeEntry = this.assembleEncodeFromView(this.view);
}
if (!isTopLevel) {
// For top-level spec, we can set the global width and height signal to adjust the group size.
// For other child specs, we have to manually set width and height in the encode entry.
if (this.type === 'unit' || this.type === 'layer') {
return Object.assign({ width: this.getSizeSignalRef('width'), height: this.getSizeSignalRef('height') }, ((encodeEntry !== null && encodeEntry !== void 0 ? encodeEntry : {})));
}
}
return encodeEntry;
}
assembleLayout() {
if (!this.layout) {
return undefined;
}
const _a = this.layout, { spacing } = _a, layout = tslib_es6_rest(_a, ["spacing"]);
const { component, config } = this;
const titleBand = assemble_assembleLayoutTitleBand(component.layoutHeaders, config);
return Object.assign(Object.assign(Object.assign({ padding: spacing }, this.assembleDefaultLayout()), layout), (titleBand ? { titleBand } : {}));
}
assembleDefaultLayout() {
return {};
}
assembleHeaderMarks() {
const { layoutHeaders } = this.component;
let headerMarks = [];
for (const channel of channel_FACET_CHANNELS) {
if (layoutHeaders[channel].title) {
headerMarks.push(assemble_assembleTitleGroup(this, channel));
}
}
for (const channel of HEADER_CHANNELS) {
headerMarks = headerMarks.concat(assemble_assembleHeaderGroups(this, channel));
}
return headerMarks;
}
assembleAxes() {
return assemble_assembleAxes(this.component.axes, this.config);
}
assembleLegends() {
return assemble_assembleLegends(this);
}
assembleProjections() {
return assemble_assembleProjections(this);
}
assembleTitle() {
var _a, _b, _c;
const _d = (_a = this.title, (_a !== null && _a !== void 0 ? _a : {})), { encoding } = _d, titleNoEncoding = tslib_es6_rest(_d, ["encoding"]);
const title = Object.assign(Object.assign(Object.assign({}, title_extractTitleConfig(this.config.title).nonMark), titleNoEncoding), (encoding ? { encode: { update: encoding } } : {}));
if (title.text) {
if (util_contains(['unit', 'layer'], this.type)) {
// Unit/Layer
if (util_contains(['middle', undefined], title.anchor)) {
title.frame = (_b = title.frame, (_b !== null && _b !== void 0 ? _b : 'group'));
}
}
else {
// composition with Vega layout
// Set title = "start" by default for composition as "middle" does not look nice
// https://github.com/vega/vega/issues/960#issuecomment-471360328
title.anchor = (_c = title.anchor, (_c !== null && _c !== void 0 ? _c : 'start'));
}
return util_keys(title).length > 0 ? title : undefined;
}
return undefined;
}
/**
* Assemble the mark group for this model. We accept optional `signals` so that we can include concat top-level signals with the top-level model's local signals.
*/
assembleGroup(signals = []) {
const group = {};
signals = signals.concat(this.assembleSignals());
if (signals.length > 0) {
group.signals = signals;
}
const layout = this.assembleLayout();
if (layout) {
group.layout = layout;
}
group.marks = [].concat(this.assembleHeaderMarks(), this.assembleMarks());
// Only include scales if this spec is top-level or if parent is facet.
// (Otherwise, it will be merged with upper-level's scope.)
const scales = !this.parent || model_isFacetModel(this.parent) ? assemble_assembleScales(this) : [];
if (scales.length > 0) {
group.scales = scales;
}
const axes = this.assembleAxes();
if (axes.length > 0) {
group.axes = axes;
}
const legends = this.assembleLegends();
if (legends.length > 0) {
group.legends = legends;
}
return group;
}
hasDescendantWithFieldOnChannel(channel) {
for (const child of this.children) {
if (model_isUnitModel(child)) {
if (child.channelHasField(channel)) {
return true;
}
}
else {
if (child.hasDescendantWithFieldOnChannel(channel)) {
return true;
}
}
}
return false;
}
getName(text) {
return util_varName((this.name ? this.name + '_' : '') + text);
}
/**
* Request a data source name for the given data source type and mark that data source as required.
* This method should be called in parse, so that all used data source can be correctly instantiated in assembleData().
* You can lookup the correct dataset name in assemble with `lookupDataSource`.
*/
requestDataName(name) {
var _a;
const fullName = this.getName(name);
// Increase ref count. This is critical because otherwise we won't create a data source.
// We also increase the ref counts on OutputNode.getSource() calls.
const refCounts = this.component.data.outputNodeRefCounts;
refCounts[fullName] = (_a = refCounts[fullName], (_a !== null && _a !== void 0 ? _a : 0)) + 1;
return fullName;
}
getSizeSignalRef(sizeType) {
if (model_isFacetModel(this.parent)) {
const channel = channel_getPositionScaleChannel(sizeType);
const scaleComponent = this.component.scales[channel];
if (scaleComponent && !scaleComponent.merged) {
// independent scale
const type = scaleComponent.get('type');
const range = scaleComponent.get('range');
if (scale_hasDiscreteDomain(type) && vega_schema_isVgRangeStep(range)) {
const scaleName = scaleComponent.get('name');
const domain = domain_assembleDomain(this, channel);
const field = domain_getFieldFromDomain(domain);
if (field) {
const fieldRef = channeldef_vgField({ aggregate: 'distinct', field }, { expr: 'datum' });
return {
signal: assemble_sizeExpr(scaleName, scaleComponent, fieldRef)
};
}
else {
src_log_warn(`Unknown field for ${channel}. Cannot calculate view size.`);
return null;
}
}
}
}
return {
signal: this.signalNameMap.get(this.getName(sizeType))
};
}
/**
* Lookup the name of the datasource for an output node. You probably want to call this in assemble.
*/
lookupDataSource(name) {
const node = this.component.data.outputNodes[name];
if (!node) {
// Name not found in map so let's just return what we got.
// This can happen if we already have the correct name.
return name;
}
return node.getSource();
}
getSignalName(oldSignalName) {
return this.signalNameMap.get(oldSignalName);
}
renameSignal(oldName, newName) {
this.signalNameMap.rename(oldName, newName);
}
renameScale(oldName, newName) {
this.scaleNameMap.rename(oldName, newName);
}
renameProjection(oldName, newName) {
this.projectionNameMap.rename(oldName, newName);
}
/**
* @return scale name for a given channel after the scale has been parsed and named.
*/
scaleName(originalScaleName, parse) {
if (parse) {
// During the parse phase always return a value
// No need to refer to rename map because a scale can't be renamed
// before it has the original name.
return this.getName(originalScaleName);
}
// If there is a scale for the channel, it should either
// be in the scale component or exist in the name map
if (
// If there is a scale for the channel, there should be a local scale component for it
(channel_isChannel(originalScaleName) && channel_isScaleChannel(originalScaleName) && this.component.scales[originalScaleName]) ||
// in the scale name map (the scale get merged by its parent)
this.scaleNameMap.has(this.getName(originalScaleName))) {
return this.scaleNameMap.get(this.getName(originalScaleName));
}
return undefined;
}
/**
* @return projection name after the projection has been parsed and named.
*/
projectionName(parse) {
if (parse) {
// During the parse phase always return a value
// No need to refer to rename map because a projection can't be renamed
// before it has the original name.
return this.getName('projection');
}
if ((this.component.projection && !this.component.projection.merged) ||
this.projectionNameMap.has(this.getName('projection'))) {
return this.projectionNameMap.get(this.getName('projection'));
}
return undefined;
}
/**
* Traverse a model's hierarchy to get the scale component for a particular channel.
*/
getScaleComponent(channel) {
/* istanbul ignore next: This is warning for debugging test */
if (!this.component.scales) {
throw new Error('getScaleComponent cannot be called before parseScale(). Make sure you have called parseScale or use parseUnitModelWithScale().');
}
const localScaleComponent = this.component.scales[channel];
if (localScaleComponent && !localScaleComponent.merged) {
return localScaleComponent;
}
return this.parent ? this.parent.getScaleComponent(channel) : undefined;
}
/**
* Traverse a model's hierarchy to get a particular selection component.
*/
getSelectionComponent(variableName, origName) {
let sel = this.component.selection[variableName];
if (!sel && this.parent) {
sel = this.parent.getSelectionComponent(variableName, origName);
}
if (!sel) {
throw new Error(log_message.selectionNotFound(origName));
}
return sel;
}
}
/** Abstract class for UnitModel and FacetModel. Both of which can contain fieldDefs as a part of its own specification. */
class model_ModelWithField extends model_Model {
/** Get "field" reference for Vega */
vgField(channel, opt = {}) {
const fieldDef = this.fieldDef(channel);
if (!fieldDef) {
return undefined;
}
return channeldef_vgField(fieldDef, opt);
}
reduceFieldDef(f, init) {
return encoding_reduce(this.getMapping(), (acc, cd, c) => {
const fieldDef = channeldef_getFieldDef(cd);
if (fieldDef) {
return f(acc, fieldDef, c);
}
return acc;
}, init);
}
forEachFieldDef(f, t) {
encoding_forEach(this.getMapping(), (cd, c) => {
const fieldDef = channeldef_getFieldDef(cd);
if (fieldDef) {
f(fieldDef, c);
}
}, t);
}
}
//# sourceMappingURL=model.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/density.js
/**
* A class for density transform nodes
*/
class density_DensityTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
var _a, _b, _c;
super(parent);
this.transform = transform;
this.transform = util_duplicate(transform); // duplicate to prevent side effects
const specifiedAs = (_a = this.transform.as, (_a !== null && _a !== void 0 ? _a : [undefined, undefined]));
this.transform.as = [(_b = specifiedAs[0], (_b !== null && _b !== void 0 ? _b : 'value')), (_c = specifiedAs[1], (_c !== null && _c !== void 0 ? _c : 'density'))];
}
clone() {
return new density_DensityTransformNode(null, util_duplicate(this.transform));
}
dependentFields() {
var _a;
return new Set([this.transform.density, ...(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : []))]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
return `DensityTransform ${util_hash(this.transform)}`;
}
assemble() {
const _a = this.transform, { density } = _a, rest = tslib_es6_rest(_a, ["density"]);
const result = Object.assign({ type: 'kde', field: density }, rest);
return result;
}
}
//# sourceMappingURL=density.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/filterinvalid.js
class filterinvalid_FilterInvalidNode extends dataflow_DataFlowNode {
constructor(parent, filter) {
super(parent);
this.filter = filter;
}
clone() {
return new filterinvalid_FilterInvalidNode(null, Object.assign({}, this.filter));
}
static make(parent, model) {
const { config, mark, markDef } = model;
const invalid = common_getMarkPropOrConfig('invalid', markDef, config);
if (invalid !== 'filter') {
return null;
}
const filter = model.reduceFieldDef((aggregator, fieldDef, channel) => {
const scaleComponent = channel_isScaleChannel(channel) && model.getScaleComponent(channel);
if (scaleComponent) {
const scaleType = scaleComponent.get('type');
// While discrete domain scales can handle invalid values, continuous scales can't.
// Thus, for non-path marks, we have to filter null for scales with continuous domains.
// (For path marks, we will use "defined" property and skip these values instead.)
if (scale_hasContinuousDomain(scaleType) && !fieldDef.aggregate && !mark_isPathMark(mark)) {
aggregator[fieldDef.field] = fieldDef; // we know that the fieldDef is a typed field def
}
}
return aggregator;
}, {});
if (!util_keys(filter).length) {
return null;
}
return new filterinvalid_FilterInvalidNode(parent, filter);
}
dependentFields() {
return new Set(util_keys(this.filter));
}
producedFields() {
return new Set(); // filter does not produce any new fields
}
hash() {
return `FilterInvalid ${util_hash(this.filter)}`;
}
/**
* Create the VgTransforms for each of the filtered fields.
*/
assemble() {
const filters = util_keys(this.filter).reduce((vegaFilters, field) => {
const fieldDef = this.filter[field];
const ref = channeldef_vgField(fieldDef, { expr: 'datum' });
if (fieldDef !== null) {
if (fieldDef.type === 'temporal') {
vegaFilters.push(`(isDate(${ref}) || (isValid(${ref}) && isFinite(+${ref})))`);
}
else if (fieldDef.type === 'quantitative') {
vegaFilters.push(`isValid(${ref})`);
vegaFilters.push(`isFinite(+${ref})`);
}
else {
// should never get here
}
}
return vegaFilters;
}, []);
return filters.length > 0
? {
type: 'filter',
expr: filters.join(' && ')
}
: null;
}
}
//# sourceMappingURL=filterinvalid.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/flatten.js
/**
* A class for flatten transform nodes
*/
class flatten_FlattenTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
this.transform = util_duplicate(transform); // duplicate to prevent side effects
const { flatten, as = [] } = this.transform;
this.transform.as = flatten.map((f, i) => { var _a; return _a = as[i], (_a !== null && _a !== void 0 ? _a : f); });
}
clone() {
return new flatten_FlattenTransformNode(this.parent, util_duplicate(this.transform));
}
dependentFields() {
return new Set(this.transform.flatten);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
return `FlattenTransform ${util_hash(this.transform)}`;
}
assemble() {
const { flatten: fields, as } = this.transform;
const result = {
type: 'flatten',
fields,
as
};
return result;
}
}
//# sourceMappingURL=flatten.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/fold.js
/**
* A class for flatten transform nodes
*/
class fold_FoldTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
var _a, _b, _c;
super(parent);
this.transform = transform;
this.transform = util_duplicate(transform); // duplicate to prevent side effects
const specifiedAs = (_a = this.transform.as, (_a !== null && _a !== void 0 ? _a : [undefined, undefined]));
this.transform.as = [(_b = specifiedAs[0], (_b !== null && _b !== void 0 ? _b : 'key')), (_c = specifiedAs[1], (_c !== null && _c !== void 0 ? _c : 'value'))];
}
clone() {
return new fold_FoldTransformNode(null, util_duplicate(this.transform));
}
dependentFields() {
return new Set(this.transform.fold);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
return `FoldTransform ${util_hash(this.transform)}`;
}
assemble() {
const { fold, as } = this.transform;
const result = {
type: 'fold',
fields: fold,
as
};
return result;
}
}
//# sourceMappingURL=fold.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/geojson.js
class geojson_GeoJSONNode extends dataflow_DataFlowNode {
constructor(parent, fields, geojson, signal) {
super(parent);
this.fields = fields;
this.geojson = geojson;
this.signal = signal;
}
clone() {
return new geojson_GeoJSONNode(null, util_duplicate(this.fields), this.geojson, this.signal);
}
static parseAll(parent, model) {
if (model.component.projection && !model.component.projection.isFit) {
return parent;
}
let geoJsonCounter = 0;
for (const coordinates of [
[channel_LONGITUDE, channel_LATITUDE],
[channel_LONGITUDE2, channel_LATITUDE2]
]) {
const pair = coordinates.map(channel => model.channelHasField(channel)
? model.fieldDef(channel).field
: channeldef_isValueDef(model.encoding[channel])
? { expr: model.encoding[channel].value + '' }
: undefined);
if (pair[0] || pair[1]) {
parent = new geojson_GeoJSONNode(parent, pair, null, model.getName(`geojson_${geoJsonCounter++}`));
}
}
if (model.channelHasField(channel_SHAPE)) {
const fieldDef = model.fieldDef(channel_SHAPE);
if (fieldDef.type === GEOJSON) {
parent = new geojson_GeoJSONNode(parent, null, fieldDef.field, model.getName(`geojson_${geoJsonCounter++}`));
}
}
return parent;
}
dependentFields() {
var _a;
const fields = (_a = this.fields, (_a !== null && _a !== void 0 ? _a : [])).filter(isString);
return new Set([...(this.geojson ? [this.geojson] : []), ...fields]);
}
producedFields() {
return new Set();
}
hash() {
return `GeoJSON ${this.geojson} ${this.signal} ${util_hash(this.fields)}`;
}
assemble() {
return Object.assign(Object.assign(Object.assign({ type: 'geojson' }, (this.fields ? { fields: this.fields } : {})), (this.geojson ? { geojson: this.geojson } : {})), { signal: this.signal });
}
}
//# sourceMappingURL=geojson.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/geopoint.js
class geopoint_GeoPointNode extends dataflow_DataFlowNode {
constructor(parent, projection, fields, as) {
super(parent);
this.projection = projection;
this.fields = fields;
this.as = as;
}
clone() {
return new geopoint_GeoPointNode(null, this.projection, util_duplicate(this.fields), util_duplicate(this.as));
}
static parseAll(parent, model) {
if (!model.projectionName()) {
return parent;
}
for (const coordinates of [
[channel_LONGITUDE, channel_LATITUDE],
[channel_LONGITUDE2, channel_LATITUDE2]
]) {
const pair = coordinates.map(channel => model.channelHasField(channel)
? model.fieldDef(channel).field
: channeldef_isValueDef(model.encoding[channel])
? { expr: model.encoding[channel].value + '' }
: undefined);
const suffix = coordinates[0] === channel_LONGITUDE2 ? '2' : '';
if (pair[0] || pair[1]) {
parent = new geopoint_GeoPointNode(parent, model.projectionName(), pair, [
model.getName('x' + suffix),
model.getName('y' + suffix)
]);
}
}
return parent;
}
dependentFields() {
return new Set(this.fields.filter(isString));
}
producedFields() {
return new Set(this.as);
}
hash() {
return `Geopoint ${this.projection} ${util_hash(this.fields)} ${util_hash(this.as)}`;
}
assemble() {
return {
type: 'geopoint',
projection: this.projection,
fields: this.fields,
as: this.as
};
}
}
//# sourceMappingURL=geopoint.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/impute.js
class impute_ImputeNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
}
clone() {
return new impute_ImputeNode(null, util_duplicate(this.transform));
}
dependentFields() {
var _a;
return new Set([this.transform.impute, this.transform.key, ...(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : []))]);
}
producedFields() {
return new Set([this.transform.impute]);
}
processSequence(keyvals) {
const { start = 0, stop, step } = keyvals;
const result = [start, stop, ...(step ? [step] : [])].join(',');
return { signal: `sequence(${result})` };
}
static makeFromTransform(parent, imputeTransform) {
return new impute_ImputeNode(parent, imputeTransform);
}
static makeFromEncoding(parent, model) {
const encoding = model.encoding;
const xDef = encoding.x;
const yDef = encoding.y;
if (channeldef_isFieldDef(xDef) && channeldef_isFieldDef(yDef)) {
const imputedChannel = xDef.impute ? xDef : yDef.impute ? yDef : undefined;
if (imputedChannel === undefined) {
return undefined;
}
const keyChannel = xDef.impute ? yDef : yDef.impute ? xDef : undefined;
const { method, value, frame, keyvals } = imputedChannel.impute;
const groupbyFields = encoding_pathGroupingFields(model.mark, encoding);
return new impute_ImputeNode(parent, Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ impute: imputedChannel.field, key: keyChannel.field }, (method ? { method } : {})), (value !== undefined ? { value } : {})), (frame ? { frame } : {})), (keyvals !== undefined ? { keyvals } : {})), (groupbyFields.length ? { groupby: groupbyFields } : {})));
}
return null;
}
hash() {
return `Impute ${util_hash(this.transform)}`;
}
assemble() {
const { impute, key, keyvals, method, groupby, value, frame = [null, null] } = this.transform;
const initialImpute = Object.assign(Object.assign(Object.assign(Object.assign({ type: 'impute', field: impute, key }, (keyvals ? { keyvals: transform_isImputeSequence(keyvals) ? this.processSequence(keyvals) : keyvals } : {})), { method: 'value' }), (groupby ? { groupby } : {})), { value: null });
let setImputedField;
if (method && method !== 'value') {
const deriveNewField = Object.assign({ type: 'window', as: [`imputed_${impute}_value`], ops: [method], fields: [impute], frame, ignorePeers: false }, (groupby ? { groupby } : {}));
const replaceOriginal = {
type: 'formula',
expr: `datum.${impute} === null ? datum.imputed_${impute}_value : datum.${impute}`,
as: impute
};
setImputedField = [deriveNewField, replaceOriginal];
}
else {
const replaceWithValue = {
type: 'formula',
expr: `datum.${impute} === null ? ${value} : datum.${impute}`,
as: impute
};
setImputedField = [replaceWithValue];
}
return [initialImpute, ...setImputedField];
}
}
//# sourceMappingURL=impute.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/index.js
/**
* Class to track interesting properties (see https://15721.courses.cs.cmu.edu/spring2016/papers/graefe-ieee1995.pdf)
* about how fields have been parsed or whether they have been derived in a transform. We use this to not parse the
* same field again (or differently).
*/
class data_AncestorParse extends split_Split {
constructor(explicit = {}, implicit = {}, parseNothing = false) {
super(explicit, implicit);
this.explicit = explicit;
this.implicit = implicit;
this.parseNothing = parseNothing;
}
clone() {
const clone = super.clone();
clone.parseNothing = this.parseNothing;
return clone;
}
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/loess.js
/**
* A class for loess transform nodes
*/
class loess_LoessTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
var _a, _b, _c;
super(parent);
this.transform = transform;
this.transform = util_duplicate(transform); // duplicate to prevent side effects
const specifiedAs = (_a = this.transform.as, (_a !== null && _a !== void 0 ? _a : [undefined, undefined]));
this.transform.as = [(_b = specifiedAs[0], (_b !== null && _b !== void 0 ? _b : transform.on)), (_c = specifiedAs[1], (_c !== null && _c !== void 0 ? _c : transform.loess))];
}
clone() {
return new loess_LoessTransformNode(null, util_duplicate(this.transform));
}
dependentFields() {
var _a;
return new Set([this.transform.loess, this.transform.on, ...(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : []))]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
return `LoessTransform ${util_hash(this.transform)}`;
}
assemble() {
const _a = this.transform, { loess, on } = _a, rest = tslib_es6_rest(_a, ["loess", "on"]);
const result = Object.assign({ type: 'loess', x: on, y: loess }, rest);
return result;
}
}
//# sourceMappingURL=loess.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/lookup.js
class lookup_LookupNode extends dataflow_DataFlowNode {
constructor(parent, transform, secondary) {
super(parent);
this.transform = transform;
this.secondary = secondary;
}
clone() {
return new lookup_LookupNode(null, util_duplicate(this.transform), this.secondary);
}
static make(parent, model, transform, counter) {
var _a;
const sources = model.component.data.sources;
const { from } = transform;
let fromOutputNode = null;
if (transform_isLookupData(from)) {
let fromSource = parse_findSource(from.data, sources);
if (!fromSource) {
fromSource = new source_SourceNode(from.data);
sources.push(fromSource);
}
const fromOutputName = model.getName(`lookup_${counter}`);
fromOutputNode = new dataflow_OutputNode(fromSource, fromOutputName, 'lookup', model.component.data.outputNodeRefCounts);
model.component.data.outputNodes[fromOutputName] = fromOutputNode;
}
else if (transform_isLookupSelection(from)) {
const selName = from.selection;
transform.as = (_a = transform.as, (_a !== null && _a !== void 0 ? _a : selName));
fromOutputNode = model.getSelectionComponent(util_varName(selName), selName).materialized;
if (!fromOutputNode) {
throw new Error(log_message.noSameUnitLookup(selName));
}
}
return new lookup_LookupNode(parent, transform, fromOutputNode.getSource());
}
dependentFields() {
return new Set([this.transform.lookup]);
}
producedFields() {
return new Set(this.transform.as ? vega_util_src_array(this.transform.as) : this.transform.from.fields);
}
hash() {
return `Lookup ${util_hash({ transform: this.transform, secondary: this.secondary })}`;
}
assemble() {
let foreign;
if (this.transform.from.fields) {
// lookup a few fields and add create a flat output
foreign = Object.assign({ values: this.transform.from.fields }, (this.transform.as ? { as: vega_util_src_array(this.transform.as) } : {}));
}
else {
// lookup full record and nest it
let asName = this.transform.as;
if (!isString(asName)) {
src_log_warn(log_message.NO_FIELDS_NEEDS_AS);
asName = '_lookup';
}
foreign = {
as: [asName]
};
}
return Object.assign(Object.assign({ type: 'lookup', from: this.secondary, key: this.transform.from.key, fields: [this.transform.lookup] }, foreign), (this.transform.default ? { default: this.transform.default } : {}));
}
}
//# sourceMappingURL=lookup.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/quantile.js
/**
* A class for quantile transform nodes
*/
class quantile_QuantileTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
var _a, _b, _c;
super(parent);
this.transform = transform;
this.transform = util_duplicate(transform); // duplicate to prevent side effects
const specifiedAs = (_a = this.transform.as, (_a !== null && _a !== void 0 ? _a : [undefined, undefined]));
this.transform.as = [(_b = specifiedAs[0], (_b !== null && _b !== void 0 ? _b : 'prob')), (_c = specifiedAs[1], (_c !== null && _c !== void 0 ? _c : 'value'))];
}
clone() {
return new quantile_QuantileTransformNode(null, util_duplicate(this.transform));
}
dependentFields() {
var _a;
return new Set([this.transform.quantile, ...(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : []))]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
return `QuantileTransform ${util_hash(this.transform)}`;
}
assemble() {
const _a = this.transform, { quantile } = _a, rest = tslib_es6_rest(_a, ["quantile"]);
const result = Object.assign({ type: 'quantile', field: quantile }, rest);
return result;
}
}
//# sourceMappingURL=quantile.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/regression.js
/**
* A class for regression transform nodes
*/
class regression_RegressionTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
var _a, _b, _c;
super(parent);
this.transform = transform;
this.transform = util_duplicate(transform); // duplicate to prevent side effects
const specifiedAs = (_a = this.transform.as, (_a !== null && _a !== void 0 ? _a : [undefined, undefined]));
this.transform.as = [(_b = specifiedAs[0], (_b !== null && _b !== void 0 ? _b : transform.on)), (_c = specifiedAs[1], (_c !== null && _c !== void 0 ? _c : transform.regression))];
}
clone() {
return new regression_RegressionTransformNode(null, util_duplicate(this.transform));
}
dependentFields() {
var _a;
return new Set([this.transform.regression, this.transform.on, ...(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : []))]);
}
producedFields() {
return new Set(this.transform.as);
}
hash() {
return `RegressionTransform ${util_hash(this.transform)}`;
}
assemble() {
const _a = this.transform, { regression, on } = _a, rest = tslib_es6_rest(_a, ["regression", "on"]);
const result = Object.assign({ type: 'regression', x: on, y: regression }, rest);
return result;
}
}
//# sourceMappingURL=regression.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/pivot.js
/**
* A class for pivot transform nodes.
*/
class pivot_PivotTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
}
clone() {
return new pivot_PivotTransformNode(null, util_duplicate(this.transform));
}
addDimensions(fields) {
var _a;
this.transform.groupby = util_unique((_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : [])).concat(fields), d => d);
}
producedFields() {
return undefined; // return undefined so that potentially everything can depend on the pivot
}
dependentFields() {
var _a;
return new Set([this.transform.pivot, this.transform.value, ...(_a = this.transform.groupby, (_a !== null && _a !== void 0 ? _a : []))]);
}
hash() {
return `PivotTransform ${util_hash(this.transform)}`;
}
assemble() {
const { pivot, value, groupby, limit, op } = this.transform;
return Object.assign(Object.assign(Object.assign({ type: 'pivot', field: pivot, value }, (limit !== undefined ? { limit } : {})), (op !== undefined ? { op } : {})), (groupby !== undefined ? { groupby } : {}));
}
}
//# sourceMappingURL=pivot.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/sample.js
/**
* A class for the sample transform nodes
*/
class sample_SampleTransformNode extends dataflow_DataFlowNode {
constructor(parent, transform) {
super(parent);
this.transform = transform;
}
clone() {
return new sample_SampleTransformNode(null, util_duplicate(this.transform));
}
dependentFields() {
return new Set();
}
producedFields() {
return new Set();
}
hash() {
return `SampleTransform ${util_hash(this.transform)}`;
}
assemble() {
return {
type: 'sample',
size: this.transform.sample
};
}
}
//# sourceMappingURL=sample.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/assemble.js
function assemble_makeWalkTree(data) {
// to name datasources
let datasetIndex = 0;
/**
* Recursively walk down the tree.
*/
function walkTree(node, dataSource) {
var _a;
if (node instanceof source_SourceNode) {
// If the source is a named data source or a data source with values, we need
// to put it in a different data source. Otherwise, Vega may override the data.
if (!node.isGenerator && !isUrlData(node.data)) {
data.push(dataSource);
const newData = {
name: null,
source: dataSource.name,
transform: []
};
dataSource = newData;
}
}
if (node instanceof formatparse_ParseNode) {
if (node.parent instanceof source_SourceNode && !dataSource.source) {
// If node's parent is a root source and the data source does not refer to another data source, use normal format parse
dataSource.format = Object.assign(Object.assign({}, (_a = dataSource.format, (_a !== null && _a !== void 0 ? _a : {}))), { parse: node.assembleFormatParse() });
// add calculates for all nested fields
dataSource.transform.push(...node.assembleTransforms(true));
}
else {
// Otherwise use Vega expression to parse
dataSource.transform.push(...node.assembleTransforms());
}
}
if (node instanceof facet_FacetNode) {
if (!dataSource.name) {
dataSource.name = `data_${datasetIndex++}`;
}
if (!dataSource.source || dataSource.transform.length > 0) {
data.push(dataSource);
node.data = dataSource.name;
}
else {
node.data = dataSource.source;
}
node.assemble().forEach(d => data.push(d));
// break here because the rest of the tree has to be taken care of by the facet.
return;
}
if (node instanceof graticule_GraticuleNode ||
node instanceof sequence_SequenceNode ||
node instanceof filterinvalid_FilterInvalidNode ||
node instanceof filter_FilterNode ||
node instanceof calculate_CalculateNode ||
node instanceof geopoint_GeoPointNode ||
node instanceof geojson_GeoJSONNode ||
node instanceof aggregate_AggregateNode ||
node instanceof lookup_LookupNode ||
node instanceof window_WindowTransformNode ||
node instanceof joinaggregate_JoinAggregateTransformNode ||
node instanceof fold_FoldTransformNode ||
node instanceof flatten_FlattenTransformNode ||
node instanceof density_DensityTransformNode ||
node instanceof loess_LoessTransformNode ||
node instanceof quantile_QuantileTransformNode ||
node instanceof regression_RegressionTransformNode ||
node instanceof identifier_IdentifierNode ||
node instanceof sample_SampleTransformNode ||
node instanceof pivot_PivotTransformNode) {
dataSource.transform.push(node.assemble());
}
if (node instanceof bin_BinNode ||
node instanceof timeunit_TimeUnitNode ||
node instanceof impute_ImputeNode ||
node instanceof stack_StackNode) {
dataSource.transform.push(...node.assemble());
}
if (node instanceof dataflow_OutputNode) {
if (dataSource.source && dataSource.transform.length === 0) {
node.setSource(dataSource.source);
}
else if (node.parent instanceof dataflow_OutputNode) {
// Note that an output node may be required but we still do not assemble a
// separate data source for it.
node.setSource(dataSource.name);
}
else {
if (!dataSource.name) {
dataSource.name = `data_${datasetIndex++}`;
}
// Here we set the name of the datasource we generated. From now on
// other assemblers can use it.
node.setSource(dataSource.name);
// if this node has more than one child, we will add a datasource automatically
if (node.numChildren() === 1) {
data.push(dataSource);
const newData = {
name: null,
source: dataSource.name,
transform: []
};
dataSource = newData;
}
}
}
switch (node.numChildren()) {
case 0:
// done
if (node instanceof dataflow_OutputNode && (!dataSource.source || dataSource.transform.length > 0)) {
// do not push empty datasources that are simply references
data.push(dataSource);
}
break;
case 1:
walkTree(node.children[0], dataSource);
break;
default: {
if (!dataSource.name) {
dataSource.name = `data_${datasetIndex++}`;
}
let source = dataSource.name;
if (!dataSource.source || dataSource.transform.length > 0) {
data.push(dataSource);
}
else {
source = dataSource.source;
}
node.children.forEach(child => {
const newData = {
name: null,
source: source,
transform: []
};
walkTree(child, newData);
});
break;
}
}
}
return walkTree;
}
/**
* Assemble data sources that are derived from faceted data.
*/
function assemble_assembleFacetData(root) {
const data = [];
const walkTree = assemble_makeWalkTree(data);
root.children.forEach(child => walkTree(child, {
source: root.name,
name: null,
transform: []
}));
return data;
}
/**
* Create Vega Data array from a given compiled model and append all of them to the given array
*
* @param model
* @param data array
* @return modified data array
*/
function assemble_assembleRootData(dataComponent, datasets) {
var _a, _b;
const data = [];
// dataComponent.sources.forEach(debug);
// draw(dataComponent.sources);
const walkTree = assemble_makeWalkTree(data);
let sourceIndex = 0;
dataComponent.sources.forEach(root => {
// assign a name if the source does not have a name yet
if (!root.hasName()) {
root.dataName = `source_${sourceIndex++}`;
}
const newData = root.assemble();
walkTree(root, newData);
});
// remove empty transform arrays for cleaner output
data.forEach(d => {
if (d.transform.length === 0) {
delete d.transform;
}
});
// move sources without transforms (the ones that are potentially used in lookups) to the beginning
let whereTo = 0;
for (const [i, d] of data.entries()) {
if ((_a = d.transform, (_a !== null && _a !== void 0 ? _a : [])).length === 0 && !d.source) {
data.splice(whereTo++, 0, data.splice(i, 1)[0]);
}
}
// now fix the from references in lookup transforms
for (const d of data) {
for (const t of (_b = d.transform, (_b !== null && _b !== void 0 ? _b : []))) {
if (t.type === 'lookup') {
t.from = dataComponent.outputNodes[t.from].getSource();
}
}
}
// inline values for datasets that are in the datastore
for (const d of data) {
if (d.name in datasets) {
d.values = datasets[d.name];
}
}
return data;
}
//# sourceMappingURL=assemble.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/header/parse.js
function parse_getHeaderType(orient) {
if (orient === 'top' || orient === 'left') {
return 'header';
}
return 'footer';
}
function parse_parseFacetHeaders(model) {
for (const channel of channel_FACET_CHANNELS) {
parse_parseFacetHeader(model, channel);
}
parse_mergeChildAxis(model, 'x');
parse_mergeChildAxis(model, 'y');
}
function parse_parseFacetHeader(model, channel) {
var _a;
if (model.channelHasField(channel)) {
const fieldDef = model.facet[channel];
const titleConfig = common_getHeaderProperty('title', null, model.config, channel);
let title = channeldef_title(fieldDef, model.config, {
allowDisabling: true,
includeDefault: titleConfig === undefined || !!titleConfig
});
if (model.child.component.layoutHeaders[channel].title) {
// TODO: better handle multiline titles
title = isArray(title) ? title.join(', ') : title;
// merge title with child to produce "Title / Subtitle / Sub-subtitle"
title += ' / ' + model.child.component.layoutHeaders[channel].title;
model.child.component.layoutHeaders[channel].title = null;
}
const labelOrient = common_getHeaderProperty('labelOrient', fieldDef, model.config, channel);
const header = (_a = fieldDef.header, (_a !== null && _a !== void 0 ? _a : {}));
const labels = util_getFirstDefined(header.labels, true);
const headerType = util_contains(['bottom', 'right'], labelOrient) ? 'footer' : 'header';
model.component.layoutHeaders[channel] = {
title,
facetFieldDef: fieldDef,
[headerType]: channel === 'facet' ? [] : [parse_makeHeaderComponent(model, channel, labels)]
};
}
}
function parse_makeHeaderComponent(model, channel, labels) {
const sizeType = channel === 'row' ? 'height' : 'width';
return {
labels,
sizeSignal: model.child.component.layoutSize.get(sizeType) ? model.child.getSizeSignalRef(sizeType) : undefined,
axes: []
};
}
function parse_mergeChildAxis(model, channel) {
var _a;
const { child } = model;
if (child.component.axes[channel]) {
const { layoutHeaders, resolve } = model.component;
resolve.axis[channel] = resolve_parseGuideResolve(resolve, channel);
if (resolve.axis[channel] === 'shared') {
// For shared axis, move the axes to facet's header or footer
const headerChannel = channel === 'x' ? 'column' : 'row';
const layoutHeader = layoutHeaders[headerChannel];
for (const axisComponent of child.component.axes[channel]) {
const headerType = parse_getHeaderType(axisComponent.get('orient'));
layoutHeader[headerType] = (_a = layoutHeader[headerType], (_a !== null && _a !== void 0 ? _a : [parse_makeHeaderComponent(model, headerChannel, false)]));
// FIXME: assemble shouldn't be called here, but we do it this way so we only extract the main part of the axes
const mainAxis = assemble_assembleAxis(axisComponent, 'main', model.config, { header: true });
// LayoutHeader no longer keep track of property precedence, thus let's combine.
layoutHeader[headerType][0].axes.push(mainAxis);
axisComponent.mainExtracted = true;
}
}
else {
// Otherwise do nothing for independent axes
}
}
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/layoutsize/parse.js
function parse_parseLayerLayoutSize(model) {
parse_parseChildrenLayoutSize(model);
const layoutSizeCmpt = model.component.layoutSize;
layoutSizeCmpt.setWithExplicit('width', parse_parseNonUnitLayoutSizeForChannel(model, 'width'));
layoutSizeCmpt.setWithExplicit('height', parse_parseNonUnitLayoutSizeForChannel(model, 'height'));
}
const parse_parseRepeatLayoutSize = parse_parseLayerLayoutSize;
const parse_SIZE_TYPE_TO_MERGE = {
vconcat: 'width',
hconcat: 'height'
};
function parse_parseConcatLayoutSize(model) {
parse_parseChildrenLayoutSize(model);
const layoutSizeCmpt = model.component.layoutSize;
const sizeTypeToMerge = parse_SIZE_TYPE_TO_MERGE[model.concatType];
if (sizeTypeToMerge) {
layoutSizeCmpt.setWithExplicit(sizeTypeToMerge, parse_parseNonUnitLayoutSizeForChannel(model, sizeTypeToMerge));
}
}
function parse_parseChildrenLayoutSize(model) {
for (const child of model.children) {
child.parseLayoutSize();
}
}
function parse_parseNonUnitLayoutSizeForChannel(model, sizeType) {
const channel = sizeType === 'width' ? 'x' : 'y';
const resolve = model.component.resolve;
let mergedSize;
// Try to merge layout size
for (const child of model.children) {
const childSize = child.component.layoutSize.getWithExplicit(sizeType);
const scaleResolve = resolve.scale[channel];
if (scaleResolve === 'independent' && childSize.value === 'step') {
// Do not merge independent scales with range-step as their size depends
// on the scale domains, which can be different between scales.
mergedSize = undefined;
break;
}
if (mergedSize) {
if (scaleResolve === 'independent' && mergedSize.value !== childSize.value) {
// For independent scale, only merge if all the sizes are the same.
// If the values are different, abandon the merge!
mergedSize = undefined;
break;
}
mergedSize = split_mergeValuesWithExplicit(mergedSize, childSize, sizeType, '');
}
else {
mergedSize = childSize;
}
}
if (mergedSize) {
// If merged, rename size and set size of all children.
for (const child of model.children) {
model.renameSignal(child.getName(sizeType), model.getName(sizeType));
child.component.layoutSize.set(sizeType, 'merged', false);
}
return mergedSize;
}
else {
// Otherwise, there is no merged size.
return {
explicit: false,
value: undefined
};
}
}
function parse_parseUnitLayoutSize(model) {
const { size, component } = model;
for (const channel of channel_POSITION_SCALE_CHANNELS) {
const sizeType = channel_getSizeType(channel);
if (size[sizeType]) {
const specifiedSize = size[sizeType];
component.layoutSize.set(sizeType, base_isStep(specifiedSize) ? 'step' : specifiedSize, true);
}
else {
const defaultSize = parse_defaultUnitSize(model, sizeType);
component.layoutSize.set(sizeType, defaultSize, false);
}
}
}
function parse_defaultUnitSize(model, sizeType) {
const channel = sizeType === 'width' ? 'x' : 'y';
const config = model.config;
const scaleComponent = model.getScaleComponent(channel);
if (scaleComponent) {
const scaleType = scaleComponent.get('type');
const range = scaleComponent.get('range');
if (scale_hasDiscreteDomain(scaleType)) {
const size = config_getViewConfigDiscreteSize(config.view, sizeType);
if (vega_schema_isVgRangeStep(range) || base_isStep(size)) {
// For discrete domain with range.step, use dynamic width/height
return 'step';
}
else {
return size;
}
}
else {
return config_getViewConfigContinuousSize(config.view, sizeType);
}
}
else if (model.hasProjection) {
return config_getViewConfigContinuousSize(config.view, sizeType);
}
else {
const size = config_getViewConfigDiscreteSize(config.view, sizeType);
return base_isStep(size) ? size.step : size;
}
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/repeater.js
function repeater_replaceRepeaterInFacet(facet, repeater) {
if (isFacetMapping(facet)) {
return repeater_replaceRepeater(facet, repeater);
}
return repeater_replaceRepeaterInFieldDef(facet, repeater);
}
function repeater_replaceRepeaterInEncoding(encoding, repeater) {
return repeater_replaceRepeater(encoding, repeater);
}
/**
* Replaces repeated value and returns if the repeated value is valid.
*/
function repeater_replaceRepeat(o, repeater) {
if (channeldef_isRepeatRef(o.field)) {
if (o.field.repeat in repeater) {
// any needed to calm down ts compiler
return Object.assign(Object.assign({}, o), { field: repeater[o.field.repeat] });
}
else {
src_log_warn(log_message.noSuchRepeatedValue(o.field.repeat));
return undefined;
}
}
return o;
}
/**
* Replace repeater values in a field def with the concrete field name.
*/
function repeater_replaceRepeaterInFieldDef(fieldDef, repeater) {
fieldDef = repeater_replaceRepeat(fieldDef, repeater);
if (fieldDef === undefined) {
// the field def should be ignored
return undefined;
}
else if (fieldDef === null) {
return null;
}
if (channeldef_isSortableFieldDef(fieldDef) && sort_isSortField(fieldDef.sort)) {
const sort = repeater_replaceRepeat(fieldDef.sort, repeater);
fieldDef = Object.assign(Object.assign({}, fieldDef), (sort ? { sort } : {}));
}
return fieldDef;
}
function repeater_replaceRepeaterInChannelDef(channelDef, repeater) {
if (channeldef_isFieldDef(channelDef)) {
const fd = repeater_replaceRepeaterInFieldDef(channelDef, repeater);
if (fd) {
return fd;
}
else if (channeldef_isConditionalDef(channelDef)) {
return { condition: channelDef.condition };
}
}
else {
if (channeldef_hasConditionalFieldDef(channelDef)) {
const fd = repeater_replaceRepeaterInFieldDef(channelDef.condition, repeater);
if (fd) {
return Object.assign(Object.assign({}, channelDef), { condition: fd });
}
else {
const { condition } = channelDef, channelDefWithoutCondition = tslib_es6_rest(channelDef, ["condition"]);
return channelDefWithoutCondition;
}
}
return channelDef;
}
return undefined;
}
function repeater_replaceRepeater(mapping, repeater) {
const out = {};
for (const channel in mapping) {
if (src_hasOwnProperty(mapping, channel)) {
const channelDef = mapping[channel];
if (isArray(channelDef)) {
// array cannot have condition
out[channel] = channelDef.map(cd => repeater_replaceRepeaterInChannelDef(cd, repeater)).filter(cd => cd);
}
else {
const cd = repeater_replaceRepeaterInChannelDef(channelDef, repeater);
if (cd !== undefined) {
out[channel] = cd;
}
}
}
}
return out;
}
//# sourceMappingURL=repeater.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/facet.js
function facet_facetSortFieldName(fieldDef, sort, opt) {
return channeldef_vgField(sort, Object.assign({ suffix: `by_${channeldef_vgField(fieldDef)}` }, ((opt !== null && opt !== void 0 ? opt : {}))));
}
class facet_FacetModel extends model_ModelWithField {
constructor(spec, parent, parentGivenName, repeater, config) {
super(spec, 'facet', parent, parentGivenName, config, repeater, spec.resolve);
this.child = buildmodel_buildModel(spec.spec, this, this.getName('child'), undefined, repeater, config);
this.children = [this.child];
const facet = repeater_replaceRepeaterInFacet(spec.facet, repeater);
this.facet = this.initFacet(facet);
}
initFacet(facet) {
// clone to prevent side effect to the original spec
if (!isFacetMapping(facet)) {
return { facet: channeldef_normalize(facet, 'facet') };
}
return encoding_reduce(facet, (normalizedFacet, fieldDef, channel) => {
if (!util_contains([channel_ROW, channel_COLUMN], channel)) {
// Drop unsupported channel
src_log_warn(log_message.incompatibleChannel(channel, 'facet'));
return normalizedFacet;
}
if (fieldDef.field === undefined) {
src_log_warn(log_message.emptyFieldDef(fieldDef, channel));
return normalizedFacet;
}
// Convert type to full, lowercase type, or augment the fieldDef with a default type if missing.
normalizedFacet[channel] = channeldef_normalize(fieldDef, channel);
return normalizedFacet;
}, {});
}
channelHasField(channel) {
return !!this.facet[channel];
}
fieldDef(channel) {
return this.facet[channel];
}
parseData() {
this.component.data = parse_parseData(this);
this.child.parseData();
}
parseLayoutSize() {
parse_parseChildrenLayoutSize(this);
}
parseSelections() {
// As a facet has a single child, the selection components are the same.
// The child maintains its selections to assemble signals, which remain
// within its unit.
this.child.parseSelections();
this.component.selection = this.child.component.selection;
}
parseMarkGroup() {
this.child.parseMarkGroup();
}
parseAxesAndHeaders() {
this.child.parseAxesAndHeaders();
parse_parseFacetHeaders(this);
}
assembleSelectionTopLevelSignals(signals) {
return this.child.assembleSelectionTopLevelSignals(signals);
}
assembleSignals() {
this.child.assembleSignals();
return [];
}
assembleSelectionData(data) {
return this.child.assembleSelectionData(data);
}
getHeaderLayoutMixins() {
var _a, _b, _c, _d;
const layoutMixins = {};
for (const channel of channel_FACET_CHANNELS) {
for (const headerType of HEADER_TYPES) {
const layoutHeaderComponent = this.component.layoutHeaders[channel];
const headerComponent = layoutHeaderComponent[headerType];
const { facetFieldDef } = layoutHeaderComponent;
if (facetFieldDef) {
const titleOrient = common_getHeaderProperty('titleOrient', facetFieldDef, this.config, channel);
if (util_contains(['right', 'bottom'], titleOrient)) {
const headerChannel = common_getHeaderChannel(channel, titleOrient);
layoutMixins.titleAnchor = (_a = layoutMixins.titleAnchor, (_a !== null && _a !== void 0 ? _a : {}));
layoutMixins.titleAnchor[headerChannel] = 'end';
}
}
if ((_b = headerComponent) === null || _b === void 0 ? void 0 : _b[0]) {
// set header/footerBand
const sizeType = channel === 'row' ? 'height' : 'width';
const bandType = headerType === 'header' ? 'headerBand' : 'footerBand';
if (channel !== 'facet' && !this.child.component.layoutSize.get(sizeType)) {
// If facet child does not have size signal, then apply headerBand
layoutMixins[bandType] = (_c = layoutMixins[bandType], (_c !== null && _c !== void 0 ? _c : {}));
layoutMixins[bandType][channel] = 0.5;
}
if (layoutHeaderComponent.title) {
layoutMixins.offset = (_d = layoutMixins.offset, (_d !== null && _d !== void 0 ? _d : {}));
layoutMixins.offset[channel === 'row' ? 'rowTitle' : 'columnTitle'] = 10;
}
}
}
}
return layoutMixins;
}
assembleDefaultLayout() {
const { column, row } = this.facet;
const columns = column ? this.columnDistinctSignal() : row ? 1 : undefined;
let align = 'all';
// Do not align the cells if the scale corresponding to the direction is indepent.
// We always align when we facet into both row and column.
if (!row && this.component.resolve.scale.x === 'independent') {
align = 'none';
}
else if (!column && this.component.resolve.scale.y === 'independent') {
align = 'none';
}
return Object.assign(Object.assign(Object.assign({}, this.getHeaderLayoutMixins()), (columns ? { columns } : {})), { bounds: 'full', align });
}
assembleLayoutSignals() {
// FIXME(https://github.com/vega/vega-lite/issues/1193): this can be incorrect if we have independent scales.
return this.child.assembleLayoutSignals();
}
columnDistinctSignal() {
if (this.parent && this.parent instanceof facet_FacetModel) {
// For nested facet, we will add columns to group mark instead
// See discussion in https://github.com/vega/vega/issues/952
// and https://github.com/vega/vega-view/releases/tag/v1.2.6
return undefined;
}
else {
// In facetNode.assemble(), the name is always this.getName('column') + '_layout'.
const facetLayoutDataName = this.getName('column_domain');
return { signal: `length(data('${facetLayoutDataName}'))` };
}
}
assembleGroup(signals) {
if (this.parent && this.parent instanceof facet_FacetModel) {
// Provide number of columns for layout.
// See discussion in https://github.com/vega/vega/issues/952
// and https://github.com/vega/vega-view/releases/tag/v1.2.6
return Object.assign(Object.assign({}, (this.channelHasField('column')
? {
encode: {
update: {
// TODO(https://github.com/vega/vega-lite/issues/2759):
// Correct the signal for facet of concat of facet_column
columns: { field: channeldef_vgField(this.facet.column, { prefix: 'distinct' }) }
}
}
}
: {})), super.assembleGroup(signals));
}
return super.assembleGroup(signals);
}
/**
* Aggregate cardinality for calculating size
*/
getCardinalityAggregateForChild() {
const fields = [];
const ops = [];
const as = [];
if (this.child instanceof facet_FacetModel) {
if (this.child.channelHasField('column')) {
const field = channeldef_vgField(this.child.facet.column);
fields.push(field);
ops.push('distinct');
as.push(`distinct_${field}`);
}
}
else {
for (const channel of ['x', 'y']) {
const childScaleComponent = this.child.component.scales[channel];
if (childScaleComponent && !childScaleComponent.merged) {
const type = childScaleComponent.get('type');
const range = childScaleComponent.get('range');
if (scale_hasDiscreteDomain(type) && vega_schema_isVgRangeStep(range)) {
const domain = domain_assembleDomain(this.child, channel);
const field = domain_getFieldFromDomain(domain);
if (field) {
fields.push(field);
ops.push('distinct');
as.push(`distinct_${field}`);
}
else {
src_log_warn(`Unknown field for ${channel}. Cannot calculate view size.`);
}
}
}
}
}
return { fields, ops, as };
}
assembleFacet() {
const { name, data } = this.component.data.facetRoot;
const { row, column } = this.facet;
const { fields, ops, as } = this.getCardinalityAggregateForChild();
const groupby = [];
for (const channel of channel_FACET_CHANNELS) {
const fieldDef = this.facet[channel];
if (fieldDef) {
groupby.push(channeldef_vgField(fieldDef));
const { bin, sort } = fieldDef;
if (bin_isBinning(bin)) {
groupby.push(channeldef_vgField(fieldDef, { binSuffix: 'end' }));
}
if (sort_isSortField(sort)) {
const { field, op = sort_DEFAULT_SORT_OP } = sort;
const outputName = facet_facetSortFieldName(fieldDef, sort);
if (row && column) {
// For crossed facet, use pre-calculate field as it requires a different groupby
// For each calculated field, apply max and assign them to the same name as
// all values of the same group should be the same anyway.
fields.push(outputName);
ops.push('max');
as.push(outputName);
}
else {
fields.push(field);
ops.push(op);
as.push(outputName);
}
}
else if (isArray(sort)) {
const outputName = calculate_sortArrayIndexField(fieldDef, channel);
fields.push(outputName);
ops.push('max');
as.push(outputName);
}
}
}
const cross = !!row && !!column;
return Object.assign({ name,
data,
groupby }, (cross || fields.length > 0
? {
aggregate: Object.assign(Object.assign({}, (cross ? { cross } : {})), (fields.length ? { fields, ops, as } : {}))
}
: {}));
}
facetSortFields(channel) {
const { facet } = this;
const fieldDef = facet[channel];
if (fieldDef) {
if (sort_isSortField(fieldDef.sort)) {
return [facet_facetSortFieldName(fieldDef, fieldDef.sort, { expr: 'datum' })];
}
else if (isArray(fieldDef.sort)) {
return [calculate_sortArrayIndexField(fieldDef, channel, { expr: 'datum' })];
}
return [channeldef_vgField(fieldDef, { expr: 'datum' })];
}
return [];
}
facetSortOrder(channel) {
const { facet } = this;
const fieldDef = facet[channel];
if (fieldDef) {
const { sort } = fieldDef;
const order = (sort_isSortField(sort) ? sort.order : !isArray(sort) && sort) || 'ascending';
return [order];
}
return [];
}
assembleLabelTitle() {
const { facet, config } = this;
if (facet.facet) {
// Facet always uses title to display labels
return assemble_assembleLabelTitle(facet.facet, 'facet', config);
}
const ORTHOGONAL_ORIENT = {
row: ['top', 'bottom'],
column: ['left', 'right']
};
for (const channel of HEADER_CHANNELS) {
if (facet[channel]) {
const labelOrient = common_getHeaderProperty('labelOrient', facet[channel], config, channel);
if (util_contains(ORTHOGONAL_ORIENT[channel], labelOrient)) {
// Row/Column with orthogonal labelOrient must use title to display labels
return assemble_assembleLabelTitle(facet[channel], channel, config);
}
}
}
return undefined;
}
assembleMarks() {
const { child } = this;
// If we facet by two dimensions, we need to add a cross operator to the aggregation
// so that we create all groups
const facetRoot = this.component.data.facetRoot;
const data = assemble_assembleFacetData(facetRoot);
const encodeEntry = child.assembleGroupEncodeEntry(false);
const title = this.assembleLabelTitle() || child.assembleTitle();
const style = child.assembleGroupStyle();
const markGroup = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: this.getName('cell'), type: 'group' }, (title ? { title } : {})), (style ? { style } : {})), { from: {
facet: this.assembleFacet()
},
// TODO: move this to after data
sort: {
field: channel_FACET_CHANNELS.map(c => this.facetSortFields(c)).flat(),
order: channel_FACET_CHANNELS.map(c => this.facetSortOrder(c)).flat()
} }), (data.length > 0 ? { data: data } : {})), (encodeEntry ? { encode: { update: encodeEntry } } : {})), child.assembleGroup(assemble_assembleFacetSignals(this, [])));
return [markGroup];
}
getMapping() {
return this.facet;
}
}
//# sourceMappingURL=facet.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/joinaggregatefacet.js
function joinaggregatefacet_makeJoinAggregateFromFacet(parent, facet) {
const { row, column } = facet;
if (row && column) {
let newParent = null;
// only need to make one for crossed facet
for (const fieldDef of [row, column]) {
if (sort_isSortField(fieldDef.sort)) {
const { field, op = sort_DEFAULT_SORT_OP } = fieldDef.sort;
parent = newParent = new joinaggregate_JoinAggregateTransformNode(parent, {
joinaggregate: [
{
op,
field,
as: facet_facetSortFieldName(fieldDef, fieldDef.sort, { forAs: true })
}
],
groupby: [channeldef_vgField(fieldDef)]
});
}
}
return newParent;
}
return null;
}
//# sourceMappingURL=joinaggregatefacet.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/data/parse.js
function parse_findSource(data, sources) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
for (const other of sources) {
const otherData = other.data;
// if both datasets have a name defined, we cannot merge
if (data.name && other.hasName() && data.name !== other.dataName) {
continue;
}
// feature and mesh are mutually exclusive
if (((_a = data['format']) === null || _a === void 0 ? void 0 : _a.mesh) && ((_b = otherData.format) === null || _b === void 0 ? void 0 : _b.feature)) {
continue;
}
// we have to extract the same feature or mesh
if ((((_c = data['format']) === null || _c === void 0 ? void 0 : _c.feature) || ((_d = otherData.format) === null || _d === void 0 ? void 0 : _d.feature)) &&
((_e = data['format']) === null || _e === void 0 ? void 0 : _e.feature) !== ((_f = otherData.format) === null || _f === void 0 ? void 0 : _f.feature)) {
continue;
}
if ((((_g = data['format']) === null || _g === void 0 ? void 0 : _g.mesh) || ((_h = otherData.format) === null || _h === void 0 ? void 0 : _h.mesh)) && ((_j = data['format']) === null || _j === void 0 ? void 0 : _j.mesh) !== ((_k = otherData.format) === null || _k === void 0 ? void 0 : _k.mesh)) {
continue;
}
if (isInlineData(data) && isInlineData(otherData)) {
if (util_deepEqual(data.values, otherData.values)) {
return other;
}
}
else if (isUrlData(data) && isUrlData(otherData)) {
if (data.url === otherData.url) {
return other;
}
}
else if (isNamedData(data)) {
if (data.name === other.dataName) {
return other;
}
}
}
return null;
}
function parse_parseRoot(model, sources) {
if (model.data || !model.parent) {
// if the model defines a data source or is the root, create a source node
if (model.data === null) {
// data: null means we should ignore the parent's data so we just create a new data source
const source = new source_SourceNode([]);
sources.push(source);
return source;
}
const existingSource = parse_findSource(model.data, sources);
if (existingSource) {
if (!isGenerator(model.data)) {
existingSource.data.format = util_mergeDeep({}, model.data.format, existingSource.data.format);
}
// if the new source has a name but the existing one does not, we can set it
if (!existingSource.hasName() && model.data.name) {
existingSource.dataName = model.data.name;
}
return existingSource;
}
else {
const source = new source_SourceNode(model.data);
sources.push(source);
return source;
}
}
else {
// If we don't have a source defined (overriding parent's data), use the parent's facet root or main.
return model.parent.component.data.facetRoot
? model.parent.component.data.facetRoot
: model.parent.component.data.main;
}
}
/**
* Parses a transform array into a chain of connected dataflow nodes.
*/
function parse_parseTransformArray(head, model, ancestorParse) {
var _a, _b;
let lookupCounter = 0;
for (const t of model.transforms) {
let derivedType = undefined;
let transformNode;
if (transform_isCalculate(t)) {
transformNode = head = new calculate_CalculateNode(head, t);
derivedType = 'derived';
}
else if (transform_isFilter(t)) {
const implicit = formatparse_getImplicitFromFilterTransform(t);
transformNode = head = (_a = formatparse_ParseNode.makeWithAncestors(head, {}, implicit, ancestorParse), (_a !== null && _a !== void 0 ? _a : head));
head = new filter_FilterNode(head, model, t.filter);
}
else if (transform_isBin(t)) {
transformNode = head = bin_BinNode.makeFromTransform(head, t, model);
derivedType = 'number';
}
else if (transform_isTimeUnit(t)) {
derivedType = 'date';
const parsedAs = ancestorParse.getWithExplicit(t.field);
// Create parse node because the input to time unit is always date.
if (parsedAs.value === undefined) {
head = new formatparse_ParseNode(head, { [t.field]: derivedType });
ancestorParse.set(t.field, derivedType, false);
}
transformNode = head = timeunit_TimeUnitNode.makeFromTransform(head, t);
}
else if (transform_isAggregate(t)) {
transformNode = head = aggregate_AggregateNode.makeFromTransform(head, t);
derivedType = 'number';
if (selection_requiresSelectionId(model)) {
head = new identifier_IdentifierNode(head);
}
}
else if (transform_isLookup(t)) {
transformNode = head = lookup_LookupNode.make(head, model, t, lookupCounter++);
derivedType = 'derived';
}
else if (transform_isWindow(t)) {
transformNode = head = new window_WindowTransformNode(head, t);
derivedType = 'number';
}
else if (transform_isJoinAggregate(t)) {
transformNode = head = new joinaggregate_JoinAggregateTransformNode(head, t);
derivedType = 'number';
}
else if (transform_isStack(t)) {
transformNode = head = stack_StackNode.makeFromTransform(head, t);
derivedType = 'derived';
}
else if (transform_isFold(t)) {
transformNode = head = new fold_FoldTransformNode(head, t);
derivedType = 'derived';
}
else if (transform_isFlatten(t)) {
transformNode = head = new flatten_FlattenTransformNode(head, t);
derivedType = 'derived';
}
else if (transform_isPivot(t)) {
transformNode = head = new pivot_PivotTransformNode(head, t);
derivedType = 'derived';
}
else if (transform_isSample(t)) {
head = new sample_SampleTransformNode(head, t);
}
else if (transform_isImpute(t)) {
transformNode = head = impute_ImputeNode.makeFromTransform(head, t);
derivedType = 'derived';
}
else if (transform_isDensity(t)) {
transformNode = head = new density_DensityTransformNode(head, t);
derivedType = 'derived';
}
else if (transform_isQuantile(t)) {
transformNode = head = new quantile_QuantileTransformNode(head, t);
derivedType = 'derived';
}
else if (transform_isRegression(t)) {
transformNode = head = new regression_RegressionTransformNode(head, t);
derivedType = 'derived';
}
else if (transform_isLoess(t)) {
transformNode = head = new loess_LoessTransformNode(head, t);
derivedType = 'derived';
}
else {
src_log_warn(log_message.invalidTransformIgnored(t));
continue;
}
if (transformNode && derivedType !== undefined) {
for (const field of (_b = transformNode.producedFields(), (_b !== null && _b !== void 0 ? _b : []))) {
ancestorParse.set(field, derivedType, false);
}
}
}
return head;
}
/*
Description of the dataflow (http://asciiflow.com/):
+--------+
| Source |
+---+----+
|
v
FormatParse
(explicit)
|
v
Transforms
(Filter, Calculate, Binning, TimeUnit, Aggregate, Window, ...)
|
v
FormatParse
(implicit)
|
v
Binning (in `encoding`)
|
v
Timeunit (in `encoding`)
|
v
Formula From Sort Array
|
v
+--+--+
| Raw |
+-----+
|
v
Aggregate (in `encoding`)
|
v
Stack (in `encoding`)
|
v
Invalid Filter
|
v
+----------+
| Main |
+----------+
|
v
+-------+
| Facet |----> "column", "column-layout", and "row"
+-------+
|
v
...Child data...
*/
function parse_parseData(model) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
let head = parse_parseRoot(model, model.component.data.sources);
const { outputNodes, outputNodeRefCounts } = model.component.data;
const ancestorParse = model.parent ? model.parent.component.data.ancestorParse.clone() : new data_AncestorParse();
const data = model.data;
if (isGenerator(data)) {
// insert generator transform
if (isSequenceGenerator(data)) {
head = new sequence_SequenceNode(head, data.sequence);
}
else if (isGraticuleGenerator(data)) {
head = new graticule_GraticuleNode(head, data.graticule);
}
// no parsing necessary for generator
ancestorParse.parseNothing = true;
}
else if (((_b = (_a = data) === null || _a === void 0 ? void 0 : _a.format) === null || _b === void 0 ? void 0 : _b.parse) === null) {
// format.parse: null means disable parsing
ancestorParse.parseNothing = true;
}
head = (_c = formatparse_ParseNode.makeExplicit(head, model, ancestorParse), (_c !== null && _c !== void 0 ? _c : head));
// Default discrete selections require an identifer transform to
// uniquely identify data points. Add this transform at the head of
// the pipeline such that the identifier field is available for all
// subsequent datasets. During optimization, we will remove this
// transform if it proves to be unnecessary. Additional identifier
// transforms will be necessary when new tuples are constructed
// (e.g., post-aggregation).
head = new identifier_IdentifierNode(head);
// HACK: This is equivalent for merging bin extent for union scale.
// FIXME(https://github.com/vega/vega-lite/issues/2270): Correctly merge extent / bin node for shared bin scale
const parentIsLayer = model.parent && model_isLayerModel(model.parent);
if (model_isUnitModel(model) || model_isFacetModel(model)) {
if (parentIsLayer) {
head = (_d = bin_BinNode.makeFromEncoding(head, model), (_d !== null && _d !== void 0 ? _d : head));
}
}
if (model.transforms.length > 0) {
head = parse_parseTransformArray(head, model, ancestorParse);
}
// create parse nodes for fields that need to be parsed (or flattened) implicitly
const implicitSelection = formatparse_getImplicitFromSelection(model);
const implicitEncoding = formatparse_getImplicitFromEncoding(model);
head = (_e = formatparse_ParseNode.makeWithAncestors(head, {}, Object.assign(Object.assign({}, implicitSelection), implicitEncoding), ancestorParse), (_e !== null && _e !== void 0 ? _e : head));
if (model_isUnitModel(model)) {
head = geojson_GeoJSONNode.parseAll(head, model);
head = geopoint_GeoPointNode.parseAll(head, model);
}
if (model_isUnitModel(model) || model_isFacetModel(model)) {
if (!parentIsLayer) {
head = (_f = bin_BinNode.makeFromEncoding(head, model), (_f !== null && _f !== void 0 ? _f : head));
}
head = (_g = timeunit_TimeUnitNode.makeFromEncoding(head, model), (_g !== null && _g !== void 0 ? _g : head));
head = calculate_CalculateNode.parseAllForSortIndex(head, model);
}
// add an output node pre aggregation
const rawName = model.getName(RAW);
const raw = new dataflow_OutputNode(head, rawName, RAW, outputNodeRefCounts);
outputNodes[rawName] = raw;
head = raw;
if (model_isUnitModel(model)) {
const agg = aggregate_AggregateNode.makeFromEncoding(head, model);
if (agg) {
head = agg;
if (selection_requiresSelectionId(model)) {
head = new identifier_IdentifierNode(head);
}
}
head = (_h = impute_ImputeNode.makeFromEncoding(head, model), (_h !== null && _h !== void 0 ? _h : head));
head = (_j = stack_StackNode.makeFromEncoding(head, model), (_j !== null && _j !== void 0 ? _j : head));
}
if (model_isUnitModel(model)) {
head = (_k = filterinvalid_FilterInvalidNode.make(head, model), (_k !== null && _k !== void 0 ? _k : head));
}
// output node for marks
const mainName = model.getName(MAIN);
const main = new dataflow_OutputNode(head, mainName, MAIN, outputNodeRefCounts);
outputNodes[mainName] = main;
head = main;
if (model_isUnitModel(model)) {
parse_materializeSelections(model, main);
}
// add facet marker
let facetRoot = null;
if (model_isFacetModel(model)) {
const facetName = model.getName('facet');
// Derive new sort index field for facet's sort array
head = calculate_CalculateNode.parseAllForSortIndex(head, model);
// Derive new aggregate for facet's sort field
// augment data source with new fields for crossed facet
head = (_l = joinaggregatefacet_makeJoinAggregateFromFacet(head, model.facet), (_l !== null && _l !== void 0 ? _l : head));
facetRoot = new facet_FacetNode(head, model, facetName, main.getSource());
outputNodes[facetName] = facetRoot;
head = facetRoot;
}
return Object.assign(Object.assign({}, model.component.data), { outputNodes,
outputNodeRefCounts,
raw,
main,
facetRoot,
ancestorParse });
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/baseconcat.js
class baseconcat_BaseConcatModel extends model_Model {
constructor(spec, specType, parent, parentGivenName, config, repeater, resolve) {
super(spec, specType, parent, parentGivenName, config, repeater, resolve);
}
parseData() {
this.component.data = parse_parseData(this);
this.children.forEach(child => {
child.parseData();
});
}
parseSelections() {
// Merge selections up the hierarchy so that they may be referenced
// across unit specs. Persist their definitions within each child
// to assemble signals which remain within output Vega unit groups.
this.component.selection = {};
for (const child of this.children) {
child.parseSelections();
util_keys(child.component.selection).forEach(key => {
this.component.selection[key] = child.component.selection[key];
});
}
}
parseMarkGroup() {
for (const child of this.children) {
child.parseMarkGroup();
}
}
parseAxesAndHeaders() {
for (const child of this.children) {
child.parseAxesAndHeaders();
}
// TODO(#2415): support shared axes
}
assembleSelectionTopLevelSignals(signals) {
return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);
}
assembleSignals() {
this.children.forEach(child => child.assembleSignals());
return [];
}
assembleLayoutSignals() {
return this.children.reduce((signals, child) => {
return [...signals, ...child.assembleLayoutSignals()];
}, assemble_assembleLayoutSignals(this));
}
assembleSelectionData(data) {
return this.children.reduce((db, child) => child.assembleSelectionData(db), data);
}
assembleMarks() {
// only children have marks
return this.children.map(child => {
const title = child.assembleTitle();
const style = child.assembleGroupStyle();
const encodeEntry = child.assembleGroupEncodeEntry(false);
return Object.assign(Object.assign(Object.assign(Object.assign({ type: 'group', name: child.getName('group') }, (title ? { title } : {})), (style ? { style } : {})), (encodeEntry ? { encode: { update: encodeEntry } } : {})), child.assembleGroup());
});
}
}
//# sourceMappingURL=baseconcat.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/concat.js
class concat_ConcatModel extends baseconcat_BaseConcatModel {
constructor(spec, parent, parentGivenName, repeater, config) {
var _a, _b, _c, _d;
super(spec, 'concat', parent, parentGivenName, config, repeater, spec.resolve);
if (((_b = (_a = spec.resolve) === null || _a === void 0 ? void 0 : _a.axis) === null || _b === void 0 ? void 0 : _b.x) === 'shared' || ((_d = (_c = spec.resolve) === null || _c === void 0 ? void 0 : _c.axis) === null || _d === void 0 ? void 0 : _d.y) === 'shared') {
src_log_warn(log_message.CONCAT_CANNOT_SHARE_AXIS);
}
this.concatType = isVConcatSpec(spec) ? 'vconcat' : isHConcatSpec(spec) ? 'hconcat' : 'concat';
this.children = this.getChildren(spec).map((child, i) => {
return buildmodel_buildModel(child, this, this.getName('concat_' + i), undefined, repeater, config);
});
}
getChildren(spec) {
if (isVConcatSpec(spec)) {
return spec.vconcat;
}
else if (isHConcatSpec(spec)) {
return spec.hconcat;
}
return spec.concat;
}
parseLayoutSize() {
parse_parseConcatLayoutSize(this);
}
parseAxisGroup() {
return null;
}
assembleDefaultLayout() {
return Object.assign(Object.assign({}, (this.concatType === 'vconcat' ? { columns: 1 } : {})), { bounds: 'full',
// Use align each so it can work with multiple plots with different size
align: 'each' });
}
}
//# sourceMappingURL=concat.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/axis/component.js
function component_isFalseOrNull(v) {
return v === false || v === null;
}
const component_AXIS_COMPONENT_PROPERTIES_INDEX = Object.assign(Object.assign({ gridScale: 1, scale: 1 }, axis_COMMON_AXIS_PROPERTIES_INDEX), { labelExpr: 1, encode: 1 });
const component_AXIS_COMPONENT_PROPERTIES = util_keys(component_AXIS_COMPONENT_PROPERTIES_INDEX);
class component_AxisComponent extends split_Split {
constructor(explicit = {}, implicit = {}, mainExtracted = false) {
super();
this.explicit = explicit;
this.implicit = implicit;
this.mainExtracted = mainExtracted;
}
clone() {
return new component_AxisComponent(util_duplicate(this.explicit), util_duplicate(this.implicit), this.mainExtracted);
}
hasAxisPart(part) {
// FIXME(https://github.com/vega/vega-lite/issues/2552) this method can be wrong if users use a Vega theme.
if (part === 'axis') {
// always has the axis container part
return true;
}
if (part === 'grid' || part === 'title') {
return !!this.get(part);
}
// Other parts are enabled by default, so they should not be false or null.
return !component_isFalseOrNull(this.get(part));
}
}
//# sourceMappingURL=component.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/axis/encode.js
function axis_encode_labels(model, channel, specifiedLabelsSpec) {
var _a;
const fieldDef = (_a = model.fieldDef(channel), (_a !== null && _a !== void 0 ? _a : (channel === 'x' ? model.fieldDef('x2') : channel === 'y' ? model.fieldDef('y2') : undefined)));
const axis = model.axis(channel);
let labelsSpec = {};
// We use a label encoding instead of setting the `format` property because Vega does not let us determine how the format should be interpreted.
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
const isUTCScale = model.getScaleComponent(channel).get('type') === scale_ScaleType.UTC;
const expr = common_timeFormatExpression('datum.value', fieldDef.timeUnit, axis.format, null, isUTCScale);
if (expr) {
labelsSpec.text = { signal: expr };
}
}
labelsSpec = Object.assign(Object.assign({}, labelsSpec), specifiedLabelsSpec);
return util_keys(labelsSpec).length === 0 ? undefined : labelsSpec;
}
//# sourceMappingURL=encode.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/axis/parse.js
function parse_parseUnitAxes(model) {
return channel_POSITION_SCALE_CHANNELS.reduce((axis, channel) => {
if (model.component.scales[channel] && model.axis(channel)) {
axis[channel] = [parse_parseAxis(channel, model)];
}
return axis;
}, {});
}
const parse_OPPOSITE_ORIENT = {
bottom: 'top',
top: 'bottom',
left: 'right',
right: 'left'
};
function parse_parseLayerAxes(model) {
var _a;
const { axes, resolve } = model.component;
const axisCount = { top: 0, bottom: 0, right: 0, left: 0 };
for (const child of model.children) {
child.parseAxesAndHeaders();
for (const channel of util_keys(child.component.axes)) {
resolve.axis[channel] = resolve_parseGuideResolve(model.component.resolve, channel);
if (resolve.axis[channel] === 'shared') {
// If the resolve says shared (and has not been overridden)
// We will try to merge and see if there is a conflict
axes[channel] = parse_mergeAxisComponents(axes[channel], child.component.axes[channel]);
if (!axes[channel]) {
// If merge returns nothing, there is a conflict so we cannot make the axis shared.
// Thus, mark axis as independent and remove the axis component.
resolve.axis[channel] = 'independent';
delete axes[channel];
}
}
}
}
// Move axes to layer's axis component and merge shared axes
for (const channel of [channel_X, channel_Y]) {
for (const child of model.children) {
if (!child.component.axes[channel]) {
// skip if the child does not have a particular axis
continue;
}
if (resolve.axis[channel] === 'independent') {
// If axes are independent, concat the axisComponent array.
axes[channel] = (_a = axes[channel], (_a !== null && _a !== void 0 ? _a : [])).concat(child.component.axes[channel]);
// Automatically adjust orient
for (const axisComponent of child.component.axes[channel]) {
const { value: orient, explicit } = axisComponent.getWithExplicit('orient');
if (axisCount[orient] > 0 && !explicit) {
// Change axis orient if the number do not match
const oppositeOrient = parse_OPPOSITE_ORIENT[orient];
if (axisCount[orient] > axisCount[oppositeOrient]) {
axisComponent.set('orient', oppositeOrient, false);
}
}
axisCount[orient]++;
// TODO(https://github.com/vega/vega-lite/issues/2634): automatically add extra offset?
}
}
// After merging, make sure to remove axes from child
delete child.component.axes[channel];
}
// Suppress grid lines for dual axis charts (https://github.com/vega/vega-lite/issues/4676)
if (resolve.axis[channel] === 'independent' && axes[channel] && axes[channel].length > 1) {
for (const axisCmpt of axes[channel]) {
if (!!axisCmpt.get('grid') && !axisCmpt.explicit.grid) {
axisCmpt.implicit.grid = false;
}
}
}
}
}
function parse_mergeAxisComponents(mergedAxisCmpts, childAxisCmpts) {
if (mergedAxisCmpts) {
// FIXME: this is a bit wrong once we support multiple axes
if (mergedAxisCmpts.length !== childAxisCmpts.length) {
return undefined; // Cannot merge axis component with different number of axes.
}
const length = mergedAxisCmpts.length;
for (let i = 0; i < length; i++) {
const merged = mergedAxisCmpts[i];
const child = childAxisCmpts[i];
if (!!merged !== !!child) {
return undefined;
}
else if (merged && child) {
const mergedOrient = merged.getWithExplicit('orient');
const childOrient = child.getWithExplicit('orient');
if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {
// TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.)
// Cannot merge due to inconsistent orient
return undefined;
}
else {
mergedAxisCmpts[i] = parse_mergeAxisComponent(merged, child);
}
}
}
}
else {
// For first one, return a copy of the child
return childAxisCmpts.map(axisComponent => axisComponent.clone());
}
return mergedAxisCmpts;
}
function parse_mergeAxisComponent(merged, child) {
for (const prop of component_AXIS_COMPONENT_PROPERTIES) {
const mergedValueWithExplicit = split_mergeValuesWithExplicit(merged.getWithExplicit(prop), child.getWithExplicit(prop), prop, 'axis',
// Tie breaker function
(v1, v2) => {
switch (prop) {
case 'title':
return common_mergeTitleComponent(v1, v2);
case 'gridScale':
return {
explicit: v1.explicit,
value: util_getFirstDefined(v1.value, v2.value)
};
}
return split_defaultTieBreaker(v1, v2, prop, 'axis');
});
merged.setWithExplicit(prop, mergedValueWithExplicit);
}
return merged;
}
function parse_getFieldDefTitle(model, channel) {
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef = model.fieldDef(channel);
const fieldDef2 = model.fieldDef(channel2);
const title1 = fieldDef ? fieldDef.title : undefined;
const title2 = fieldDef2 ? fieldDef2.title : undefined;
if (title1 && title2) {
return common_mergeTitle(title1, title2);
}
else if (title1) {
return title1;
}
else if (title2) {
return title2;
}
else if (title1 !== undefined) {
// falsy value to disable config
return title1;
}
else if (title2 !== undefined) {
// falsy value to disable config
return title2;
}
return undefined;
}
function axis_parse_isExplicit(value, property, axis, model, channel) {
switch (property) {
case 'titleAngle':
case 'labelAngle':
return value === util_normalizeAngle(axis[property]);
case 'values':
return !!axis.values;
// specified axis.values is already respected, but may get transformed.
case 'encode':
// both VL axis.encoding and axis.labelAngle affect VG axis.encode
return !!axis.encoding || !!axis.labelAngle;
case 'title':
// title can be explicit if fieldDef.title is set
if (value === parse_getFieldDefTitle(model, channel)) {
return true;
}
}
// Otherwise, things are explicit if the returned value matches the specified property
return value === axis[property];
}
function parse_parseAxis(channel, model) {
var _a;
const axis = model.axis(channel);
const axisComponent = new component_AxisComponent();
// 1.2. Add properties
component_AXIS_COMPONENT_PROPERTIES.forEach(property => {
const value = axis_parse_getProperty(property, axis, channel, model);
if (value !== undefined) {
const explicit = axis_parse_isExplicit(value, property, axis, model, channel);
const configValue = getAxisConfig(property, model.config, channel, axisComponent.get('orient'), model.getScaleComponent(channel).get('type'));
// only set property if it is explicitly set or has no config value (otherwise we will accidentally override config)
if (explicit || configValue === undefined) {
// Do not apply implicit rule if there is a config value
axisComponent.set(property, value, explicit);
}
else if (util_contains(['grid', 'orient'], property) && configValue) {
// - Grid is an exception because we need to set grid = true to generate another grid axis
// - Orient is not an axis config in Vega, so we need to set too.
axisComponent.set(property, configValue, false);
}
}
});
// 2) Add guide encode definition groups
const axisEncoding = (_a = axis.encoding, (_a !== null && _a !== void 0 ? _a : {}));
const axisEncode = axis_AXIS_PARTS.reduce((e, part) => {
var _a;
if (!axisComponent.hasAxisPart(part)) {
// No need to create encode for a disabled part.
return e;
}
const axisEncodingPart = guide_guideEncodeEntry((_a = axisEncoding[part], (_a !== null && _a !== void 0 ? _a : {})), model);
const value = part === 'labels' ? axis_encode_labels(model, channel, axisEncodingPart) : axisEncodingPart;
if (value !== undefined && util_keys(value).length > 0) {
e[part] = { update: value };
}
return e;
}, {});
// FIXME: By having encode as one property, we won't have fine grained encode merging.
if (util_keys(axisEncode).length > 0) {
axisComponent.set('encode', axisEncode, !!axis.encoding || axis.labelAngle !== undefined);
}
return axisComponent;
}
function axis_parse_getProperty(property, specifiedAxis, channel, model) {
const fieldDef = model.fieldDef(channel);
// Some properties depend on labelAngle so we have to declare it here.
// Also, we don't use `getFirstDefined` for labelAngle
// as we want to normalize specified value to be within [0,360)
const labelAngle = properties_labelAngle(model, specifiedAxis, channel, fieldDef);
const orient = util_getFirstDefined(specifiedAxis.orient, properties_orient(channel));
const { mark, config } = model;
switch (property) {
case 'scale':
return model.scaleName(channel);
case 'gridScale':
return properties_gridScale(model, channel);
case 'format':
// We don't include temporal field here as we apply format in encode block
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
return undefined;
}
return common_numberFormat(fieldDef, specifiedAxis.format, config);
case 'formatType':
// As with format, we don't include temporal field here as we apply format in encode block
if (channeldef_isTimeFormatFieldDef(fieldDef)) {
return undefined;
}
return specifiedAxis.formatType;
case 'grid': {
if (bin_isBinned(model.fieldDef(channel).bin)) {
return false;
}
else {
const scaleType = model.getScaleComponent(channel).get('type');
return util_getFirstDefined(specifiedAxis.grid, properties_defaultGrid(scaleType, fieldDef));
}
}
case 'labelAlign':
return util_getFirstDefined(specifiedAxis.labelAlign, properties_defaultLabelAlign(labelAngle, orient));
case 'labelAngle':
return labelAngle;
case 'labelBaseline':
return util_getFirstDefined(specifiedAxis.labelBaseline, properties_defaultLabelBaseline(labelAngle, orient));
case 'labelFlush':
return util_getFirstDefined(specifiedAxis.labelFlush, properties_defaultLabelFlush(fieldDef, channel));
case 'labelOverlap': {
const scaleType = model.getScaleComponent(channel).get('type');
return util_getFirstDefined(specifiedAxis.labelOverlap, properties_defaultLabelOverlap(fieldDef, scaleType));
}
case 'orient':
return orient;
case 'tickCount': {
const scaleType = model.getScaleComponent(channel).get('type');
const sizeType = channel === 'x' ? 'width' : channel === 'y' ? 'height' : undefined;
const size = sizeType ? model.getSizeSignalRef(sizeType) : undefined;
return util_getFirstDefined(specifiedAxis.tickCount, properties_defaultTickCount({ fieldDef, scaleType, size }));
}
case 'title': {
const channel2 = channel === 'x' ? 'x2' : 'y2';
const fieldDef2 = model.fieldDef(channel2);
// Keep undefined so we use default if title is unspecified.
// For other falsy value, keep them so we will hide the title.
return util_getFirstDefined(specifiedAxis.title, parse_getFieldDefTitle(model, channel), // If title not specified, store base parts of fieldDef (and fieldDef2 if exists)
common_mergeTitleFieldDefs([channeldef_toFieldDefBase(fieldDef)], fieldDef2 ? [channeldef_toFieldDefBase(fieldDef2)] : []));
}
case 'values':
return properties_values(specifiedAxis, model, fieldDef);
case 'zindex':
return util_getFirstDefined(specifiedAxis.zindex, properties_defaultZindex(mark, fieldDef));
}
// Otherwise, return specified property.
return axis_isAxisProperty(property) ? specifiedAxis[property] : undefined;
}
//# sourceMappingURL=parse.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/layoutsize/init.js
function init_initLayoutSize({ encoding, size }) {
for (const channel of channel_POSITION_SCALE_CHANNELS) {
const sizeType = channel_getSizeType(channel);
const fieldDef = channeldef_getFieldDef(encoding[channel]);
if (base_isStep(size[sizeType])) {
if (fieldDef) {
if (channeldef_isContinuous(fieldDef)) {
delete size[sizeType];
src_log_warn(log_message.stepDropped(sizeType));
}
}
}
}
return size;
}
//# sourceMappingURL=init.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/init.js
function init_normalizeMarkDef(mark, encoding, config, { graticule }) {
var _a, _b;
const markDef = mark_isMarkDef(mark) ? Object.assign({}, mark) : { type: mark };
// set orient, which can be overridden by rules as sometimes the specified orient is invalid.
const specifiedOrient = (_a = markDef.orient, (_a !== null && _a !== void 0 ? _a : common_getMarkConfig('orient', markDef, config)));
markDef.orient = init_orient(markDef.type, encoding, specifiedOrient);
if (specifiedOrient !== undefined && specifiedOrient !== markDef.orient) {
src_log_warn(log_message.orientOverridden(markDef.orient, specifiedOrient));
}
// set opacity and filled if not specified in mark config
const specifiedOpacity = util_getFirstDefined(markDef.opacity, common_getMarkConfig('opacity', markDef, config));
if (specifiedOpacity === undefined) {
markDef.opacity = init_opacity(markDef.type, encoding);
}
const specifiedFilled = markDef.filled;
if (specifiedFilled === undefined) {
markDef.filled = graticule ? false : init_filled(markDef, config);
}
// set cursor, which should be pointer if href channel is present unless otherwise specified
const specifiedCursor = (_b = markDef.cursor, (_b !== null && _b !== void 0 ? _b : common_getMarkConfig('cursor', markDef, config)));
if (specifiedCursor === undefined) {
markDef.cursor = init_cursor(markDef, encoding, config);
}
return markDef;
}
function init_cursor(markDef, encoding, config) {
if (encoding.href || markDef.href || common_getMarkConfig('href', markDef, config)) {
return 'pointer';
}
return markDef.cursor;
}
function init_opacity(mark, encoding) {
if (util_contains([mark_POINT, mark_TICK, mark_CIRCLE, mark_SQUARE], mark)) {
// point-based marks
if (!encoding_isAggregate(encoding)) {
return 0.7;
}
}
return undefined;
}
function init_filled(markDef, config) {
const filledConfig = common_getMarkConfig('filled', markDef, config);
const mark = markDef.type;
return util_getFirstDefined(filledConfig, mark !== mark_POINT && mark !== mark_LINE && mark !== mark_RULE);
}
function init_orient(mark, encoding, specifiedOrient) {
switch (mark) {
case mark_POINT:
case mark_CIRCLE:
case mark_SQUARE:
case mark_TEXT:
case mark_RECT:
case mark_IMAGE:
// orient is meaningless for these marks.
return undefined;
}
const { x, y, x2, y2 } = encoding;
switch (mark) {
case mark_BAR:
if (channeldef_isFieldDef(x) && (bin_isBinned(x.bin) || (channeldef_isFieldDef(y) && y.aggregate && !x.aggregate))) {
return 'vertical';
}
if (channeldef_isFieldDef(y) && (bin_isBinned(y.bin) || (channeldef_isFieldDef(x) && x.aggregate && !y.aggregate))) {
return 'horizontal';
}
if (y2 || x2) {
// Ranged bar does not always have clear orientation, so we allow overriding
if (specifiedOrient) {
return specifiedOrient;
}
// If y is range and x is non-range, non-bin Q, y is likely a prebinned field
if (!x2 && channeldef_isFieldDef(x) && x.type === QUANTITATIVE && !bin_isBinning(x.bin)) {
return 'horizontal';
}
// If x is range and y is non-range, non-bin Q, x is likely a prebinned field
if (!y2 && channeldef_isFieldDef(y) && y.type === QUANTITATIVE && !bin_isBinning(y.bin)) {
return 'vertical';
}
}
// falls through
case mark_RULE:
// return undefined for line segment rule and bar with both axis ranged
if (x2 && y2) {
return undefined;
}
// falls through
case mark_AREA:
// If there are range for both x and y, y (vertical) has higher precedence.
if (y2) {
if (channeldef_isFieldDef(y) && bin_isBinned(y.bin)) {
return 'horizontal';
}
else {
return 'vertical';
}
}
else if (x2) {
if (channeldef_isFieldDef(x) && bin_isBinned(x.bin)) {
return 'vertical';
}
else {
return 'horizontal';
}
}
else if (mark === mark_RULE) {
if (x && !y) {
return 'vertical';
}
else if (y && !x) {
return 'horizontal';
}
}
// falls through
case mark_LINE:
case mark_TICK: {
// Tick is opposite to bar, line, area and never have ranged mark.
const xIsContinuous = channeldef_isFieldDef(x) && channeldef_isContinuous(x);
const yIsContinuous = channeldef_isFieldDef(y) && channeldef_isContinuous(y);
if (xIsContinuous && !yIsContinuous) {
return mark !== 'tick' ? 'horizontal' : 'vertical';
}
else if (!xIsContinuous && yIsContinuous) {
return mark !== 'tick' ? 'vertical' : 'horizontal';
}
else if (xIsContinuous && yIsContinuous) {
const xDef = x; // we can cast here since they are surely fieldDef
const yDef = y;
const xIsTemporal = xDef.type === TEMPORAL;
const yIsTemporal = yDef.type === TEMPORAL;
// temporal without timeUnit is considered continuous, but better serves as dimension
if (xIsTemporal && !yIsTemporal) {
return mark !== 'tick' ? 'vertical' : 'horizontal';
}
else if (!xIsTemporal && yIsTemporal) {
return mark !== 'tick' ? 'horizontal' : 'vertical';
}
if (!xDef.aggregate && yDef.aggregate) {
return mark !== 'tick' ? 'vertical' : 'horizontal';
}
else if (xDef.aggregate && !yDef.aggregate) {
return mark !== 'tick' ? 'horizontal' : 'vertical';
}
if (specifiedOrient) {
// When ambiguous, use user specified one.
return specifiedOrient;
}
return 'vertical';
}
else {
// Discrete x Discrete case
if (specifiedOrient) {
// When ambiguous, use user specified one.
return specifiedOrient;
}
return undefined;
}
}
}
return 'vertical';
}
//# sourceMappingURL=init.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/area.js
const area_area = {
vgMark: 'area',
encodeEntry: (model) => {
return Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
orient: 'include',
size: 'ignore'
})), position_range_pointOrRangePosition('x', model, {
defaultPos: 'zeroOrMin',
defaultPos2: 'zeroOrMin',
range: model.markDef.orient === 'horizontal'
})), position_range_pointOrRangePosition('y', model, {
defaultPos: 'zeroOrMin',
defaultPos2: 'zeroOrMin',
range: model.markDef.orient === 'vertical'
})), defined_defined(model));
}
};
//# sourceMappingURL=area.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/bar.js
const bar_bar = {
vgMark: 'rect',
encodeEntry: (model) => {
return Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
orient: 'ignore',
size: 'ignore'
})), position_rect_rectPosition(model, 'x', 'bar')), position_rect_rectPosition(model, 'y', 'bar'));
}
};
//# sourceMappingURL=bar.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/geoshape.js
const geoshape_geoshape = {
vgMark: 'shape',
encodeEntry: (model) => {
return Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
size: 'ignore',
orient: 'ignore'
}));
},
postEncodingTransform: (model) => {
const { encoding } = model;
const shapeDef = encoding.shape;
const transform = Object.assign({ type: 'geoshape', projection: model.projectionName() }, (shapeDef && channeldef_isFieldDef(shapeDef) && shapeDef.type === GEOJSON
? { field: channeldef_vgField(shapeDef, { expr: 'datum' }) }
: {}));
return [transform];
}
};
//# sourceMappingURL=geoshape.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/image.js
const image_image = {
vgMark: 'image',
encodeEntry: (model) => {
return Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'ignore',
orient: 'ignore',
size: 'ignore'
})), position_rect_rectPosition(model, 'x', 'image')), position_rect_rectPosition(model, 'y', 'image')), text_text(model, 'url'));
}
};
//# sourceMappingURL=image.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/line.js
const line_line = {
vgMark: 'line',
encodeEntry: (model) => {
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
size: 'ignore',
orient: 'ignore'
})), position_point_pointPosition('x', model, { defaultPos: 'mid' })), position_point_pointPosition('y', model, { defaultPos: 'mid' })), nonposition_nonPosition('size', model, {
vgChannel: 'strokeWidth' // VL's line size is strokeWidth
})), defined_defined(model));
}
};
const line_trail = {
vgMark: 'trail',
encodeEntry: (model) => {
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
size: 'include',
orient: 'ignore'
})), position_point_pointPosition('x', model, { defaultPos: 'mid' })), position_point_pointPosition('y', model, { defaultPos: 'mid' })), nonposition_nonPosition('size', model)), defined_defined(model));
}
};
//# sourceMappingURL=line.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/point.js
function point_encodeEntry(model, fixedShape) {
const { config } = model;
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
size: 'include',
orient: 'ignore'
})), position_point_pointPosition('x', model, { defaultPos: 'mid' })), position_point_pointPosition('y', model, { defaultPos: 'mid' })), nonposition_nonPosition('size', model)), point_shapeMixins(model, config, fixedShape));
}
function point_shapeMixins(model, config, fixedShape) {
if (fixedShape) {
return { shape: { value: fixedShape } };
}
return nonposition_nonPosition('shape', model);
}
const point_point = {
vgMark: 'symbol',
encodeEntry: (model) => {
return point_encodeEntry(model);
}
};
const point_circle = {
vgMark: 'symbol',
encodeEntry: (model) => {
return point_encodeEntry(model, 'circle');
}
};
const point_square = {
vgMark: 'symbol',
encodeEntry: (model) => {
return point_encodeEntry(model, 'square');
}
};
//# sourceMappingURL=point.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/rect.js
const rect_rect = {
vgMark: 'rect',
encodeEntry: (model) => {
return Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
orient: 'ignore',
size: 'ignore'
})), position_rect_rectPosition(model, 'x', 'rect')), position_rect_rectPosition(model, 'y', 'rect'));
}
};
//# sourceMappingURL=rect.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/rule.js
const rule_rule = {
vgMark: 'rule',
encodeEntry: (model) => {
const { markDef } = model;
const orient = markDef.orient;
if (!model.encoding.x && !model.encoding.y && !model.encoding.latitude && !model.encoding.longitude) {
// Show nothing if we have none of x, y, lat, and long.
return {};
}
return Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
orient: 'ignore',
size: 'ignore'
})), position_range_pointOrRangePosition('x', model, {
defaultPos: orient === 'horizontal' ? 'zeroOrMin' : 'mid',
defaultPos2: 'zeroOrMax',
range: orient !== 'vertical' // include x2 for horizontal or line segment rule
})), position_range_pointOrRangePosition('y', model, {
defaultPos: orient === 'vertical' ? 'zeroOrMin' : 'mid',
defaultPos2: 'zeroOrMax',
range: orient !== 'horizontal' // include y2 for vertical or line segment rule
})), nonposition_nonPosition('size', model, {
vgChannel: 'strokeWidth' // VL's rule size is strokeWidth
}));
}
};
//# sourceMappingURL=rule.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/text.js
const mark_text_text = {
vgMark: 'text',
encodeEntry: (model) => {
const { config, encoding } = model;
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'include',
baseline: 'include',
color: 'include',
size: 'ignore',
orient: 'ignore'
})), position_point_pointPosition('x', model, { defaultPos: 'mid' })), position_point_pointPosition('y', model, { defaultPos: 'mid' })), text_text(model)), nonposition_nonPosition('size', model, {
vgChannel: 'fontSize' // VL's text size is fontSize
})), defined_valueIfDefined('align', text_align(model.markDef, encoding, config))), defined_valueIfDefined('baseline', text_baseline(model.markDef, encoding, config)));
}
};
function text_align(markDef, encoding, config) {
var _a;
const a = (_a = markDef.align, (_a !== null && _a !== void 0 ? _a : common_getMarkConfig('align', markDef, config)));
if (a === undefined) {
return 'center';
}
// If there is a config, Vega-parser will process this already.
return undefined;
}
function text_baseline(markDef, encoding, config) {
var _a;
const b = (_a = markDef.baseline, (_a !== null && _a !== void 0 ? _a : common_getMarkConfig('baseline', markDef, config)));
if (b === undefined) {
return 'middle';
}
// If there is a config, Vega-parser will process this already.
return undefined;
}
//# sourceMappingURL=text.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/tick.js
const tick_tick = {
vgMark: 'rect',
encodeEntry: (model) => {
const { config, markDef } = model;
const orient = markDef.orient;
const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';
const vgThicknessChannel = orient === 'horizontal' ? 'height' : 'width';
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, base_baseEncodeEntry(model, {
align: 'ignore',
baseline: 'ignore',
color: 'include',
orient: 'ignore',
size: 'ignore'
})), position_point_pointPosition('x', model, { defaultPos: 'mid', vgChannel: 'xc' })), position_point_pointPosition('y', model, { defaultPos: 'mid', vgChannel: 'yc' })), nonposition_nonPosition('size', model, {
defaultValue: tick_defaultSize(model),
vgChannel: vgSizeChannel
})), { [vgThicknessChannel]: { value: util_getFirstDefined(markDef.thickness, config.tick.thickness) } });
}
};
function tick_defaultSize(model) {
const { config, markDef } = model;
const { orient } = markDef;
const vgSizeChannel = orient === 'horizontal' ? 'width' : 'height';
const scale = model.getScaleComponent(orient === 'horizontal' ? 'x' : 'y');
const markPropOrConfig = util_getFirstDefined(markDef[vgSizeChannel], markDef.size, common_getMarkConfig('size', markDef, config, { vgChannel: vgSizeChannel }), config.tick.bandSize);
if (markPropOrConfig !== undefined) {
return markPropOrConfig;
}
else {
const scaleRange = scale ? scale.get('range') : undefined;
if (scaleRange && vega_schema_isVgRangeStep(scaleRange) && src_isNumber(scaleRange.step)) {
return (scaleRange.step * 3) / 4;
}
const defaultViewStep = config_getViewConfigDiscreteStep(config.view, vgSizeChannel);
return (defaultViewStep * 3) / 4;
}
}
//# sourceMappingURL=tick.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/mark/mark.js
const mark_markCompiler = {
area: area_area,
bar: bar_bar,
circle: point_circle,
geoshape: geoshape_geoshape,
image: image_image,
line: line_line,
point: point_point,
rect: rect_rect,
rule: rule_rule,
square: point_square,
text: mark_text_text,
tick: tick_tick,
trail: line_trail
};
function mark_parseMarkGroups(model) {
if (util_contains([mark_LINE, mark_AREA, mark_TRAIL], model.mark)) {
return mark_parsePathMark(model);
}
else if (util_contains([mark_BAR], model.mark)) {
return mark_getStackGroups(model);
}
else {
return mark_getMarkGroups(model);
}
}
const mark_FACETED_PATH_PREFIX = 'faceted_path_';
function mark_parsePathMark(model) {
const details = encoding_pathGroupingFields(model.mark, model.encoding);
const pathMarks = mark_getMarkGroups(model, {
// If has subfacet for line/area group, need to use faceted data from below.
fromPrefix: details.length > 0 ? mark_FACETED_PATH_PREFIX : ''
});
if (details.length > 0) {
// have level of details - need to facet line into subgroups
// TODO: for non-stacked plot, map order to zindex. (Maybe rename order for layer to zindex?)
return [
{
name: model.getName('pathgroup'),
type: 'group',
from: {
facet: {
name: mark_FACETED_PATH_PREFIX + model.requestDataName(MAIN),
data: model.requestDataName(MAIN),
groupby: details
}
},
encode: {
update: {
width: { field: { group: 'width' } },
height: { field: { group: 'height' } }
}
},
marks: pathMarks
}
];
}
else {
return pathMarks;
}
}
const mark_STACK_GROUP_PREFIX = 'stack_group_';
/**
* We need to put stacked bars into groups in order to enable cornerRadius for stacks.
* If stack is used and the model doesn't have size encoding, we put the mark into groups,
* and apply cornerRadius properties at the group.
*/
function mark_getStackGroups(model) {
var _a;
// Don't use nested groups when cornerRadius is not specified, or specified as 0
const hasCornerRadius = vega_schema_VG_CORNERRADIUS_CHANNELS.some(prop => model.markDef[prop] || common_getMarkConfig(prop, model.markDef, model.config));
// Activate groups if stack is used and the model doesn't have size encoding
if (model.stack && !model.fieldDef('size') && hasCornerRadius) {
// Generate the mark
const [mark] = mark_getMarkGroups(model, { fromPrefix: mark_STACK_GROUP_PREFIX });
// Get the scale for the stacked field
const fieldScale = model.scaleName(model.stack.fieldChannel);
const stackField = (opt = {}) => model.vgField(model.stack.fieldChannel, opt);
// Find the min/max of the pixel value on the stacked direction
const stackFieldGroup = (func, expr) => {
const vgFieldMinMax = [
stackField({ prefix: 'min', suffix: 'start', expr }),
stackField({ prefix: 'max', suffix: 'start', expr }),
stackField({ prefix: 'min', suffix: 'end', expr }),
stackField({ prefix: 'max', suffix: 'end', expr })
];
return `${func}(${vgFieldMinMax.map(field => `scale('${fieldScale}',${field})`).join(',')})`;
};
let groupUpdate;
let innerGroupUpdate;
// Build the encoding for group and an inner group
if (model.stack.fieldChannel === 'x') {
// Move cornerRadius, y/yc/y2/height properties to group
// Group x/x2 should be the min/max of the marks within
groupUpdate = Object.assign(Object.assign({}, util_pick(mark.encode.update, ['y', 'yc', 'y2', 'height', ...vega_schema_VG_CORNERRADIUS_CHANNELS])), { x: { signal: stackFieldGroup('min', 'datum') }, x2: { signal: stackFieldGroup('max', 'datum') }, clip: { value: true } });
// Inner group should revert the x translation, and pass height through
innerGroupUpdate = {
x: { field: { group: 'x' }, mult: -1 },
height: { field: { group: 'height' } }
};
// The marks should use the same height as group, without y/yc/y2 properties (because it's already done by group)
// This is why size encoding is not supported yet
mark.encode.update = Object.assign(Object.assign({}, util_omit(mark.encode.update, ['y', 'yc', 'y2'])), { height: { field: { group: 'height' } } });
}
else {
groupUpdate = Object.assign(Object.assign({}, util_pick(mark.encode.update, ['x', 'xc', 'x2', 'width'])), { y: { signal: stackFieldGroup('min', 'datum') }, y2: { signal: stackFieldGroup('max', 'datum') }, clip: { value: true } });
innerGroupUpdate = {
y: { field: { group: 'y' }, mult: -1 },
width: { field: { group: 'width' } }
};
mark.encode.update = Object.assign(Object.assign({}, util_omit(mark.encode.update, ['x', 'xc', 'x2'])), { width: { field: { group: 'width' } } });
}
// Deal with cornerRadius properties
for (const key of vega_schema_VG_CORNERRADIUS_CHANNELS) {
const configValue = common_getMarkConfig(key, model.markDef, model.config);
// Move from mark to group
if (mark.encode.update[key]) {
groupUpdate[key] = mark.encode.update[key];
delete mark.encode.update[key];
}
else if (configValue) {
groupUpdate[key] = { value: configValue };
}
// Overwrite any cornerRadius on mark set by config --- they are already moved to the group
if (configValue) {
mark.encode.update[key] = { value: 0 };
}
}
// For bin we have to add bin channels.
const groupby = model.vgField(model.stack.groupbyChannel)
? [model.vgField(model.stack.groupbyChannel)]
: [];
if ((_a = model.fieldDef(model.stack.groupbyChannel)) === null || _a === void 0 ? void 0 : _a.bin) {
groupby.push(model.vgField(model.stack.groupbyChannel, { binSuffix: 'end' }));
}
const strokeProperties = [
'stroke',
'strokeWidth',
'strokeJoin',
'strokeCap',
'strokeDash',
'strokeDashOffset',
'strokeMiterLimit',
'strokeOpacity'
];
// Generate stroke properties for the group
groupUpdate = strokeProperties.reduce((encode, prop) => {
if (mark.encode.update[prop]) {
return Object.assign(Object.assign({}, encode), { [prop]: mark.encode.update[prop] });
}
else {
const configValue = common_getMarkConfig(prop, model.markDef, model.config);
if (configValue !== undefined) {
return Object.assign(Object.assign({}, encode), { [prop]: { value: configValue } });
}
else {
return encode;
}
}
}, groupUpdate);
// Apply strokeForeground and strokeOffset if stroke is used
if (groupUpdate.stroke) {
groupUpdate.strokeForeground = { value: true };
groupUpdate.strokeOffset = { value: 0 };
}
return [
{
type: 'group',
from: {
facet: {
data: model.requestDataName(MAIN),
name: mark_STACK_GROUP_PREFIX + model.requestDataName(MAIN),
groupby,
aggregate: {
fields: [
stackField({ suffix: 'start' }),
stackField({ suffix: 'start' }),
stackField({ suffix: 'end' }),
stackField({ suffix: 'end' })
],
ops: ['min', 'max', 'min', 'max']
}
}
},
encode: {
update: groupUpdate
},
marks: [
{
type: 'group',
encode: { update: innerGroupUpdate },
marks: [mark]
}
]
}
];
}
else {
return mark_getMarkGroups(model);
}
}
function mark_getSort(model) {
const { encoding, stack, mark, markDef, config } = model;
const order = encoding.order;
if ((!isArray(order) && channeldef_isValueDef(order) && util_isNullOrFalse(order.value)) ||
(!order && util_isNullOrFalse(markDef.order)) ||
util_isNullOrFalse(common_getMarkConfig('order', markDef, config))) {
return undefined;
}
else if ((isArray(order) || channeldef_isFieldDef(order)) && !stack) {
// Sort by the order field if it is specified and the field is not stacked. (For stacked field, order specify stack order.)
return common_sortParams(order, { expr: 'datum' });
}
else if (mark_isPathMark(mark)) {
// For both line and area, we sort values based on dimension by default
const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';
const dimensionChannelDef = encoding[dimensionChannel];
if (channeldef_isFieldDef(dimensionChannelDef)) {
const s = dimensionChannelDef.sort;
if (isArray(s)) {
return {
field: channeldef_vgField(dimensionChannelDef, { prefix: dimensionChannel, suffix: 'sort_index', expr: 'datum' })
};
}
else if (sort_isSortField(s)) {
return {
field: channeldef_vgField({
// FIXME: this op might not already exist?
// FIXME: what if dimensionChannel (x or y) contains custom domain?
aggregate: encoding_isAggregate(model.encoding) ? s.op : undefined,
field: s.field
}, { expr: 'datum' })
};
}
else if (sort_isSortByEncoding(s)) {
const fieldDefToSort = model.fieldDef(s.encoding);
return {
field: channeldef_vgField(fieldDefToSort, { expr: 'datum' }),
order: s.order
};
}
else {
return {
field: channeldef_vgField(dimensionChannelDef, {
// For stack with imputation, we only have bin_mid
binSuffix: model.stack && model.stack.impute ? 'mid' : undefined,
expr: 'datum'
})
};
}
}
return undefined;
}
return undefined;
}
function mark_getMarkGroups(model, opt = { fromPrefix: '' }) {
const mark = model.mark;
const clip = util_getFirstDefined(model.markDef.clip, mark_scaleClip(model), mark_projectionClip(model));
const style = common_getStyles(model.markDef);
const key = model.encoding.key;
const sort = mark_getSort(model);
const interactive = mark_interactiveFlag(model);
const postEncodingTransform = mark_markCompiler[mark].postEncodingTransform
? mark_markCompiler[mark].postEncodingTransform(model)
: null;
return [
Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name: model.getName('marks'), type: mark_markCompiler[mark].vgMark }, (clip ? { clip: true } : {})), (style ? { style } : {})), (key ? { key: key.field } : {})), (sort ? { sort } : {})), (interactive ? interactive : {})), { from: { data: opt.fromPrefix + model.requestDataName(MAIN) }, encode: {
update: mark_markCompiler[mark].encodeEntry(model)
} }), (postEncodingTransform
? {
transform: postEncodingTransform
}
: {}))
];
}
/**
* If scales are bound to interval selections, we want to automatically clip
* marks to account for panning/zooming interactions. We identify bound scales
* by the selectionExtent property, which gets added during scale parsing.
*/
function mark_scaleClip(model) {
const xScale = model.getScaleComponent('x');
const yScale = model.getScaleComponent('y');
return (xScale && xScale.get('selectionExtent')) || (yScale && yScale.get('selectionExtent')) ? true : undefined;
}
/**
* If we use a custom projection with auto-fitting to the geodata extent,
* we need to clip to ensure the chart size doesn't explode.
*/
function mark_projectionClip(model) {
const projection = model.component.projection;
return projection && !projection.isFit ? true : undefined;
}
/**
* Only output interactive flags if we have selections defined somewhere in our model hierarchy.
*/
function mark_interactiveFlag(model) {
if (!model.component.selection)
return null;
const unitCount = util_keys(model.component.selection).length;
let parentCount = unitCount;
let parent = model.parent;
while (parent && parentCount === 0) {
parentCount = util_keys(parent.component.selection).length;
parent = parent.parent;
}
return parentCount ? { interactive: unitCount > 0 } : null;
}
//# sourceMappingURL=mark.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/unit.js
/**
* Internal model of Vega-Lite specification for the compiler.
*/
class unit_UnitModel extends model_ModelWithField {
constructor(spec, parent, parentGivenName, parentGivenSize = {}, repeater, config) {
var _a;
super(spec, 'unit', parent, parentGivenName, config, repeater, undefined, spec.view);
this.specifiedScales = {};
this.specifiedAxes = {};
this.specifiedLegends = {};
this.specifiedProjection = {};
this.selection = {};
this.children = [];
const mark = mark_isMarkDef(spec.mark) ? spec.mark.type : spec.mark;
const encodingWithRepeaterReplaced = repeater_replaceRepeaterInEncoding((_a = spec.encoding, (_a !== null && _a !== void 0 ? _a : {})), repeater);
this.markDef = init_normalizeMarkDef(spec.mark, encodingWithRepeaterReplaced, config, {
graticule: spec.data && isGraticuleGenerator(spec.data)
});
const encoding = (this.encoding = encoding_normalizeEncoding(encodingWithRepeaterReplaced, this.markDef));
this.size = init_initLayoutSize({
encoding,
size: Object.assign(Object.assign(Object.assign({}, parentGivenSize), (spec.width ? { width: spec.width } : {})), (spec.height ? { height: spec.height } : {}))
});
// calculate stack properties
this.stack = stack_stack(mark, encoding);
this.specifiedScales = this.initScales(mark, encoding);
this.specifiedAxes = this.initAxes(encoding);
this.specifiedLegends = this.initLegend(encoding);
this.specifiedProjection = spec.projection;
// Selections will be initialized upon parse.
this.selection = spec.selection;
}
get hasProjection() {
const { encoding } = this;
const isGeoShapeMark = this.mark === mark_GEOSHAPE;
const hasGeoPosition = encoding && channel_GEOPOSITION_CHANNELS.some(channel => channeldef_isFieldDef(encoding[channel]));
return isGeoShapeMark || hasGeoPosition;
}
/**
* Return specified Vega-Lite scale domain for a particular channel
* @param channel
*/
scaleDomain(channel) {
const scale = this.specifiedScales[channel];
return scale ? scale.domain : undefined;
}
axis(channel) {
return this.specifiedAxes[channel];
}
legend(channel) {
return this.specifiedLegends[channel];
}
initScales(mark, encoding) {
return channel_SCALE_CHANNELS.reduce((scales, channel) => {
let fieldDef;
let specifiedScale;
const channelDef = encoding[channel];
if (channeldef_isFieldDef(channelDef)) {
fieldDef = channelDef;
specifiedScale = channelDef.scale;
}
else if (channeldef_hasConditionalFieldDef(channelDef)) {
// Need to specify generic for hasConditionalFieldDef as the value type can vary across channels
fieldDef = channelDef.condition;
specifiedScale = channelDef.condition['scale'];
}
if (fieldDef) {
scales[channel] = (specifiedScale !== null && specifiedScale !== void 0 ? specifiedScale : {});
}
return scales;
}, {});
}
initAxes(encoding) {
return [channel_X, channel_Y].reduce((_axis, channel) => {
// Position Axis
// TODO: handle ConditionFieldDef
const channelDef = encoding[channel];
if (channeldef_isFieldDef(channelDef) ||
(channel === channel_X && channeldef_isFieldDef(encoding.x2)) ||
(channel === channel_Y && channeldef_isFieldDef(encoding.y2))) {
const axisSpec = channeldef_isFieldDef(channelDef) ? channelDef.axis : null;
if (axisSpec !== null) {
_axis[channel] = Object.assign({}, axisSpec);
}
}
return _axis;
}, {});
}
initLegend(encoding) {
return channel_NONPOSITION_SCALE_CHANNELS.reduce((_legend, channel) => {
const channelDef = encoding[channel];
if (channelDef) {
const legend = channeldef_isFieldDef(channelDef)
? channelDef.legend
: channeldef_hasConditionalFieldDef(channelDef) // Need to specify generic for hasConditionalFieldDef as the value type can vary across channels
? channelDef.condition['legend']
: null;
if (legend !== null && legend !== false && channel_supportLegend(channel)) {
_legend[channel] = Object.assign({}, legend);
}
}
return _legend;
}, {});
}
parseData() {
this.component.data = parse_parseData(this);
}
parseLayoutSize() {
parse_parseUnitLayoutSize(this);
}
parseSelections() {
this.component.selection = parse_parseUnitSelection(this, this.selection);
}
parseMarkGroup() {
this.component.mark = mark_parseMarkGroups(this);
}
parseAxesAndHeaders() {
this.component.axes = parse_parseUnitAxes(this);
}
assembleSelectionTopLevelSignals(signals) {
return assemble_assembleTopLevelSignals(this, signals);
}
assembleSignals() {
return [...assemble_assembleAxisSignals(this), ...assemble_assembleUnitSelectionSignals(this, [])];
}
assembleSelectionData(data) {
return assemble_assembleUnitSelectionData(this, data);
}
assembleLayout() {
return null;
}
assembleLayoutSignals() {
return assemble_assembleLayoutSignals(this);
}
assembleMarks() {
var _a;
let marks = (_a = this.component.mark, (_a !== null && _a !== void 0 ? _a : []));
// If this unit is part of a layer, selections should augment
// all in concert rather than each unit individually. This
// ensures correct interleaving of clipping and brushed marks.
if (!this.parent || !model_isLayerModel(this.parent)) {
marks = assemble_assembleUnitSelectionMarks(this, marks);
}
return marks.map(this.correctDataNames);
}
getMapping() {
return this.encoding;
}
get mark() {
return this.markDef.type;
}
channelHasField(channel) {
return encoding_channelHasField(this.encoding, channel);
}
fieldDef(channel) {
const channelDef = this.encoding[channel];
return channeldef_getTypedFieldDef(channelDef);
}
}
//# sourceMappingURL=unit.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/layer.js
class layer_LayerModel extends model_Model {
constructor(spec, parent, parentGivenName, parentGivenSize, repeater, config) {
super(spec, 'layer', parent, parentGivenName, config, repeater, spec.resolve, spec.view);
const layoutSize = Object.assign(Object.assign(Object.assign({}, parentGivenSize), (spec.width ? { width: spec.width } : {})), (spec.height ? { height: spec.height } : {}));
this.children = spec.layer.map((layer, i) => {
if (isLayerSpec(layer)) {
return new layer_LayerModel(layer, this, this.getName('layer_' + i), layoutSize, repeater, config);
}
else if (isUnitSpec(layer)) {
return new unit_UnitModel(layer, this, this.getName('layer_' + i), layoutSize, repeater, config);
}
throw new Error(log_message.invalidSpec(layer));
});
}
parseData() {
this.component.data = parse_parseData(this);
for (const child of this.children) {
child.parseData();
}
}
parseLayoutSize() {
parse_parseLayerLayoutSize(this);
}
parseSelections() {
// Merge selections up the hierarchy so that they may be referenced
// across unit specs. Persist their definitions within each child
// to assemble signals which remain within output Vega unit groups.
this.component.selection = {};
for (const child of this.children) {
child.parseSelections();
util_keys(child.component.selection).forEach(key => {
this.component.selection[key] = child.component.selection[key];
});
}
}
parseMarkGroup() {
for (const child of this.children) {
child.parseMarkGroup();
}
}
parseAxesAndHeaders() {
parse_parseLayerAxes(this);
}
assembleSelectionTopLevelSignals(signals) {
return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);
}
// TODO: Support same named selections across children.
assembleSignals() {
return this.children.reduce((signals, child) => {
return signals.concat(child.assembleSignals());
}, assemble_assembleAxisSignals(this));
}
assembleLayoutSignals() {
return this.children.reduce((signals, child) => {
return signals.concat(child.assembleLayoutSignals());
}, assemble_assembleLayoutSignals(this));
}
assembleSelectionData(data) {
return this.children.reduce((db, child) => child.assembleSelectionData(db), data);
}
assembleTitle() {
let title = super.assembleTitle();
if (title) {
return title;
}
// If title does not provide layer, look into children
for (const child of this.children) {
title = child.assembleTitle();
if (title) {
return title;
}
}
return undefined;
}
assembleLayout() {
return null;
}
assembleMarks() {
return assemble_assembleLayerSelectionMarks(this, this.children.flatMap(child => {
return child.assembleMarks();
}));
}
assembleLegends() {
return this.children.reduce((legends, child) => {
return legends.concat(child.assembleLegends());
}, assemble_assembleLegends(this));
}
}
//# sourceMappingURL=layer.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/repeat.js
class repeat_RepeatModel extends baseconcat_BaseConcatModel {
constructor(spec, parent, parentGivenName, repeatValues, config) {
super(spec, 'repeat', parent, parentGivenName, config, repeatValues, spec.resolve);
if (spec.resolve && spec.resolve.axis && (spec.resolve.axis.x === 'shared' || spec.resolve.axis.y === 'shared')) {
src_log_warn(log_message.REPEAT_CANNOT_SHARE_AXIS);
}
this.repeat = spec.repeat;
this.children = this._initChildren(spec, this.repeat, repeatValues, config);
}
_initChildren(spec, repeat, repeater, config) {
const children = [];
const row = (!isArray(repeat) && repeat.row) || [repeater ? repeater.row : null];
const column = (!isArray(repeat) && repeat.column) || [repeater ? repeater.column : null];
const repeatValues = (isArray(repeat) && repeat) || [repeater ? repeater.repeat : null];
// cross product
for (const repeatValue of repeatValues) {
for (const rowValue of row) {
for (const columnValue of column) {
const name = (repeatValue ? `__repeat_repeat_${repeatValue}` : '') +
(rowValue ? `__repeat_row_${rowValue}` : '') +
(columnValue ? `__repeat_column_${columnValue}` : '');
const childRepeat = {
repeat: repeatValue,
row: rowValue,
column: columnValue
};
children.push(buildmodel_buildModel(spec.spec, this, this.getName('child' + name), undefined, childRepeat, config));
}
}
}
return children;
}
parseLayoutSize() {
parse_parseRepeatLayoutSize(this);
}
assembleDefaultLayout() {
const { repeat } = this;
const columns = isArray(repeat) ? undefined : repeat.column ? repeat.column.length : 1;
return Object.assign(Object.assign({}, (columns ? { columns } : {})), { bounds: 'full', align: 'all' });
}
}
//# sourceMappingURL=repeat.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/buildmodel.js
function buildmodel_buildModel(spec, parent, parentGivenName, unitSize, repeater, config) {
if (isFacetSpec(spec)) {
return new facet_FacetModel(spec, parent, parentGivenName, repeater, config);
}
else if (isLayerSpec(spec)) {
return new layer_LayerModel(spec, parent, parentGivenName, unitSize, repeater, config);
}
else if (isUnitSpec(spec)) {
return new unit_UnitModel(spec, parent, parentGivenName, unitSize, repeater, config);
}
else if (isRepeatSpec(spec)) {
return new repeat_RepeatModel(spec, parent, parentGivenName, repeater, config);
}
else if (isAnyConcatSpec(spec)) {
return new concat_ConcatModel(spec, parent, parentGivenName, repeater, config);
}
throw new Error(log_message.invalidSpec(spec));
}
//# sourceMappingURL=buildmodel.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/compile/compile.js
/**
* Vega-Lite's main function, for compiling Vega-Lite spec into Vega spec.
*
* At a high-level, we make the following transformations in different phases:
*
* Input spec
* |
* | (Normalization)
* v
* Normalized Spec (Row/Column channels in single-view specs becomes faceted specs, composite marks becomes layered specs.)
* |
* | (Build Model)
* v
* A model tree of the spec
* |
* | (Parse)
* v
* A model tree with parsed components (intermediate structure of visualization primitives in a format that can be easily merged)
* |
* | (Optimize)
* v
* A model tree with parsed components with the data component optimized
* |
* | (Assemble)
* v
* Vega spec
*
* @param inputSpec The Vega-Lite specification.
* @param opt Optional arguments passed to the Vega-Lite compiler.
* @returns An object containing the compiled Vega spec and normalized Vega-Lite spec.
*/
function compile_compile(inputSpec, opt = {}) {
// 0. Augment opt with default opts
if (opt.logger) {
// set the singleton logger to the provided logger
log_set(opt.logger);
}
if (opt.fieldTitle) {
// set the singleton field title formatter
channeldef_setTitleFormatter(opt.fieldTitle);
}
try {
// 1. Initialize config by deep merging default config with the config provided via option and the input spec.
const config = config_initConfig(mergeConfig_mergeConfig({}, opt.config, inputSpec.config));
// 2. Normalize: Convert input spec -> normalized spec
// - Decompose all extended unit specs into composition of unit spec. For example, a box plot get expanded into multiple layers of bars, ticks, and rules. The shorthand row/column channel is also expanded to a facet spec.
// - Normalize autosize and width or height spec
const spec = normalize_normalize(inputSpec, config);
// 3. Build Model: normalized spec -> Model (a tree structure)
// This phases instantiates the models with default config by doing a top-down traversal. This allows us to pass properties that child models derive from their parents via their constructors.
// See the abstract `Model` class and its children (UnitModel, LayerModel, FacetModel, RepeatModel, ConcatModel) for different types of models.
const model = buildmodel_buildModel(spec, null, '', undefined, undefined, config);
// 4 Parse: Model --> Model with components
// Note that components = intermediate representations that are equivalent to Vega specs.
// We need these intermediate representation because we need to merge many visualization "components" like projections, scales, axes, and legends.
// We will later convert these components into actual Vega specs in the assemble phase.
// In this phase, we do a bottom-up traversal over the whole tree to
// parse for each type of components once (e.g., data, layout, mark, scale).
// By doing bottom-up traversal, we start parsing components of unit specs and
// then merge child components of parent composite specs.
//
// Please see inside model.parse() for order of different components parsed.
model.parse();
// draw(model.component.data.sources);
// 5. Optimize the dataflow. This will modify the data component of the model.
optimize_optimizeDataflow(model.component.data, model);
// 6. Assemble: convert model components --> Vega Spec.
const vgSpec = compile_assembleTopLevelModel(model, compile_getTopLevelProperties(inputSpec, spec.autosize, config, model), inputSpec.datasets, inputSpec.usermeta);
return {
spec: vgSpec,
normalized: spec
};
}
finally {
// Reset the singleton logger if a logger is provided
if (opt.logger) {
log_reset();
}
// Reset the singleton field title formatter if provided
if (opt.fieldTitle) {
channeldef_resetTitleFormatter();
}
}
}
function compile_getTopLevelProperties(inputSpec, autosize, config, model) {
const width = model.component.layoutSize.get('width');
const height = model.component.layoutSize.get('height');
if (autosize === undefined) {
autosize = { type: 'pad' };
}
else if (isString(autosize)) {
autosize = { type: autosize };
}
if (width && height && toplevel_isFitType(autosize.type)) {
if (width === 'step' && height === 'step') {
src_log_warn(log_message.droppingFit());
autosize.type = 'pad';
}
else if (width === 'step' || height === 'step') {
// effectively XOR, because else if
// get step dimension
const sizeType = width === 'step' ? 'width' : 'height';
// log that we're dropping fit for respective channel
src_log_warn(log_message.droppingFit(channel_getPositionScaleChannel(sizeType)));
// setting type to inverse fit (so if we dropped fit-x, type is now fit-y)
const inverseSizeType = sizeType === 'width' ? 'height' : 'width';
autosize.type = toplevel_getFitType(inverseSizeType);
}
}
return Object.assign(Object.assign(Object.assign({}, (util_keys(autosize).length === 1 && autosize.type
? autosize.type === 'pad'
? {}
: { autosize: autosize.type }
: { autosize })), toplevel_extractTopLevelProperties(config)), toplevel_extractTopLevelProperties(inputSpec));
}
/*
* Assemble the top-level model to a Vega spec.
*
* Note: this couldn't be `model.assemble()` since the top-level model
* needs some special treatment to generate top-level properties.
*/
function compile_assembleTopLevelModel(model, topLevelProperties, datasets = {}, usermeta) {
// Config with Vega-Lite only config removed.
const vgConfig = model.config ? config_stripAndRedirectConfig(model.config) : undefined;
const data = [].concat(model.assembleSelectionData([]),
// only assemble data in the root
assemble_assembleRootData(model.component.data, datasets));
const projections = model.assembleProjections();
const title = model.assembleTitle();
const style = model.assembleGroupStyle();
const encodeEntry = model.assembleGroupEncodeEntry(true);
let layoutSignals = model.assembleLayoutSignals();
// move width and height signals with values to top level
layoutSignals = layoutSignals.filter(signal => {
if ((signal.name === 'width' || signal.name === 'height') && signal.value !== undefined) {
topLevelProperties[signal.name] = +signal.value;
return false;
}
return true;
});
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ $schema: 'https://vega.github.io/schema/vega/v5.json' }, (model.description ? { description: model.description } : {})), topLevelProperties), (title ? { title } : {})), (style ? { style } : {})), (encodeEntry ? { encode: { update: encodeEntry } } : {})), { data }), (projections.length > 0 ? { projections: projections } : {})), model.assembleGroup([...layoutSignals, ...model.assembleSelectionTopLevelSignals([])])), (vgConfig ? { config: vgConfig } : {})), (usermeta ? { usermeta } : {}));
}
//# sourceMappingURL=compile.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/transformextract.js
class transformextract_TransformExtractMapper extends map_SpecMapper {
mapUnit(spec, { config }) {
if (spec.encoding) {
const { encoding: oldEncoding, transform: oldTransforms } = spec;
const { bins, timeUnits, aggregate, groupby, encoding } = encoding_extractTransformsFromEncoding(oldEncoding, config);
const transform = [
...(oldTransforms ? oldTransforms : []),
...bins,
...timeUnits,
...(aggregate.length === 0 ? [] : [{ aggregate, groupby }])
];
return Object.assign(Object.assign(Object.assign({}, spec), (transform.length > 0 ? { transform } : {})), { encoding });
}
else {
return spec;
}
}
}
const transformextract_extractor = new transformextract_TransformExtractMapper();
/**
* Modifies spec extracting transformations from encoding and moving them to the transforms array
*/
function transformextract_extractTransforms(spec, config) {
return transformextract_extractor.map(spec, { config });
}
//# sourceMappingURL=transformextract.js.map
// CONCATENATED MODULE: ./node_modules/vega-lite/build/src/index.js
const src_version = build_package.version;
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: ./node_modules/vega-schema-url-parser/index.js
var vega_schema_url_parser = __webpack_require__(195);
var vega_schema_url_parser_default = /*#__PURE__*/__webpack_require__.n(vega_schema_url_parser);
// EXTERNAL MODULE: ./node_modules/vega-themes/build/package.json
var vega_themes_build_package = __webpack_require__(284);
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-dark.js
const lightColor = '#fff';
const medColor = '#888';
const darkTheme = {
background: '#333',
title: { color: lightColor },
style: {
'guide-label': {
fill: lightColor,
},
'guide-title': {
fill: lightColor,
},
},
axis: {
domainColor: lightColor,
gridColor: medColor,
tickColor: lightColor,
},
};
/* harmony default export */ var theme_dark = (darkTheme);
//# sourceMappingURL=theme-dark.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-excel.js
const markColor = '#4572a7';
const excelTheme = {
background: '#fff',
arc: { fill: markColor },
area: { fill: markColor },
line: { stroke: markColor, strokeWidth: 2 },
path: { stroke: markColor },
rect: { fill: markColor },
shape: { stroke: markColor },
symbol: { fill: markColor, strokeWidth: 1.5, size: 50 },
axis: {
bandPosition: 0.5,
grid: true,
gridColor: '#000000',
gridOpacity: 1,
gridWidth: 0.5,
labelPadding: 10,
tickSize: 5,
tickWidth: 0.5,
},
axisBand: {
grid: false,
tickExtra: true,
},
legend: {
labelBaseline: 'middle',
labelFontSize: 11,
symbolSize: 50,
symbolType: 'square',
},
range: {
category: [
'#4572a7',
'#aa4643',
'#8aa453',
'#71598e',
'#4598ae',
'#d98445',
'#94aace',
'#d09393',
'#b9cc98',
'#a99cbc',
],
},
};
/* harmony default export */ var theme_excel = (excelTheme);
//# sourceMappingURL=theme-excel.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-fivethirtyeight.js
const theme_fivethirtyeight_markColor = '#30a2da';
const axisColor = '#cbcbcb';
const guideLabelColor = '#999';
const guideTitleColor = '#333';
const backgroundColor = '#f0f0f0';
const blackTitle = '#333';
const fiveThirtyEightTheme = {
arc: { fill: theme_fivethirtyeight_markColor },
area: { fill: theme_fivethirtyeight_markColor },
axis: {
domainColor: axisColor,
grid: true,
gridColor: axisColor,
gridWidth: 1,
labelColor: guideLabelColor,
labelFontSize: 10,
titleColor: guideTitleColor,
tickColor: axisColor,
tickSize: 10,
titleFontSize: 14,
titlePadding: 10,
labelPadding: 4,
},
axisBand: {
grid: false,
},
background: backgroundColor,
group: {
fill: backgroundColor,
},
legend: {
labelColor: blackTitle,
labelFontSize: 11,
padding: 1,
symbolSize: 30,
symbolType: 'square',
titleColor: blackTitle,
titleFontSize: 14,
titlePadding: 10,
},
line: {
stroke: theme_fivethirtyeight_markColor,
strokeWidth: 2,
},
path: { stroke: theme_fivethirtyeight_markColor, strokeWidth: 0.5 },
rect: { fill: theme_fivethirtyeight_markColor },
range: {
category: [
'#30a2da',
'#fc4f30',
'#e5ae38',
'#6d904f',
'#8b8b8b',
'#b96db8',
'#ff9e27',
'#56cc60',
'#52d2ca',
'#52689e',
'#545454',
'#9fe4f8',
],
diverging: ['#cc0020', '#e77866', '#f6e7e1', '#d6e8ed', '#91bfd9', '#1d78b5'],
heatmap: ['#d6e8ed', '#cee0e5', '#91bfd9', '#549cc6', '#1d78b5'],
},
point: {
filled: true,
shape: 'circle',
},
shape: { stroke: theme_fivethirtyeight_markColor },
bar: {
binSpacing: 2,
fill: theme_fivethirtyeight_markColor,
stroke: null,
},
title: {
anchor: 'start',
fontSize: 24,
fontWeight: 600,
offset: 20,
},
};
/* harmony default export */ var theme_fivethirtyeight = (fiveThirtyEightTheme);
//# sourceMappingURL=theme-fivethirtyeight.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-ggplot2.js
const theme_ggplot2_markColor = '#000';
const ggplot2Theme = {
group: {
fill: '#e5e5e5',
},
arc: { fill: theme_ggplot2_markColor },
area: { fill: theme_ggplot2_markColor },
line: { stroke: theme_ggplot2_markColor },
path: { stroke: theme_ggplot2_markColor },
rect: { fill: theme_ggplot2_markColor },
shape: { stroke: theme_ggplot2_markColor },
symbol: { fill: theme_ggplot2_markColor, size: 40 },
axis: {
domain: false,
grid: true,
gridColor: '#FFFFFF',
gridOpacity: 1,
labelColor: '#7F7F7F',
labelPadding: 4,
tickColor: '#7F7F7F',
tickSize: 5.67,
titleFontSize: 16,
titleFontWeight: 'normal',
},
legend: {
labelBaseline: 'middle',
labelFontSize: 11,
symbolSize: 40,
},
range: {
category: [
'#000000',
'#7F7F7F',
'#1A1A1A',
'#999999',
'#333333',
'#B0B0B0',
'#4D4D4D',
'#C9C9C9',
'#666666',
'#DCDCDC',
],
},
};
/* harmony default export */ var theme_ggplot2 = (ggplot2Theme);
//# sourceMappingURL=theme-ggplot2.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-latimes.js
const headlineFontSize = 22;
const headlineFontWeight = 'normal';
const labelFont = 'Benton Gothic, sans-serif';
const labelFontSize = 11.5;
const labelFontWeight = 'normal';
const theme_latimes_markColor = '#82c6df';
// const markHighlight = '#006d8f';
// const markDemocrat = '#5789b8';
// const markRepublican = '#d94f54';
const titleFont = 'Benton Gothic Bold, sans-serif';
const titleFontWeight = 'normal';
const titleFontSize = 13;
const colorSchemes = {
'category-6': ['#ec8431', '#829eb1', '#c89d29', '#3580b1', '#adc839', '#ab7fb4'],
'fire-7': ['#fbf2c7', '#f9e39c', '#f8d36e', '#f4bb6a', '#e68a4f', '#d15a40', '#ab4232'],
'fireandice-6': ['#e68a4f', '#f4bb6a', '#f9e39c', '#dadfe2', '#a6b7c6', '#849eae'],
'ice-7': ['#edefee', '#dadfe2', '#c4ccd2', '#a6b7c6', '#849eae', '#607785', '#47525d'],
};
const latimesTheme = {
background: '#ffffff',
title: {
anchor: 'start',
color: '#000000',
font: titleFont,
fontSize: headlineFontSize,
fontWeight: headlineFontWeight,
},
arc: { fill: theme_latimes_markColor },
area: { fill: theme_latimes_markColor },
line: { stroke: theme_latimes_markColor, strokeWidth: 2 },
path: { stroke: theme_latimes_markColor },
rect: { fill: theme_latimes_markColor },
shape: { stroke: theme_latimes_markColor },
symbol: { fill: theme_latimes_markColor, size: 30 },
axis: {
labelFont,
labelFontSize,
labelFontWeight,
titleFont,
titleFontSize,
titleFontWeight,
},
axisX: {
labelAngle: 0,
labelPadding: 4,
tickSize: 3,
},
axisY: {
labelBaseline: 'middle',
maxExtent: 45,
minExtent: 45,
tickSize: 2,
titleAlign: 'left',
titleAngle: 0,
titleX: -45,
titleY: -11,
},
legend: {
labelFont,
labelFontSize,
symbolType: 'square',
titleFont,
titleFontSize,
titleFontWeight,
},
range: {
category: colorSchemes['category-6'],
diverging: colorSchemes['fireandice-6'],
heatmap: colorSchemes['fire-7'],
ordinal: colorSchemes['fire-7'],
ramp: colorSchemes['fire-7'],
},
};
/* harmony default export */ var theme_latimes = (latimesTheme);
//# sourceMappingURL=theme-latimes.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-quartz.js
const theme_quartz_markColor = '#ab5787';
const theme_quartz_axisColor = '#979797';
const quartzTheme = {
background: '#f9f9f9',
arc: { fill: theme_quartz_markColor },
area: { fill: theme_quartz_markColor },
line: { stroke: theme_quartz_markColor },
path: { stroke: theme_quartz_markColor },
rect: { fill: theme_quartz_markColor },
shape: { stroke: theme_quartz_markColor },
symbol: { fill: theme_quartz_markColor, size: 30 },
axis: {
domainColor: theme_quartz_axisColor,
domainWidth: 0.5,
gridWidth: 0.2,
labelColor: theme_quartz_axisColor,
tickColor: theme_quartz_axisColor,
tickWidth: 0.2,
titleColor: theme_quartz_axisColor,
},
axisBand: {
grid: false,
},
axisX: {
grid: true,
tickSize: 10,
},
axisY: {
domain: false,
grid: true,
tickSize: 0,
},
legend: {
labelFontSize: 11,
padding: 1,
symbolSize: 30,
symbolType: 'square',
},
range: {
category: [
'#ab5787',
'#51b2e5',
'#703c5c',
'#168dd9',
'#d190b6',
'#00609f',
'#d365ba',
'#154866',
'#666666',
'#c4c4c4',
],
},
};
/* harmony default export */ var theme_quartz = (quartzTheme);
//# sourceMappingURL=theme-quartz.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-vox.js
const theme_vox_markColor = '#3e5c69';
const voxTheme = {
background: '#fff',
arc: { fill: theme_vox_markColor },
area: { fill: theme_vox_markColor },
line: { stroke: theme_vox_markColor },
path: { stroke: theme_vox_markColor },
rect: { fill: theme_vox_markColor },
shape: { stroke: theme_vox_markColor },
symbol: { fill: theme_vox_markColor },
axis: {
domainWidth: 0.5,
grid: true,
labelPadding: 2,
tickSize: 5,
tickWidth: 0.5,
titleFontWeight: 'normal',
},
axisBand: {
grid: false,
},
axisX: {
gridWidth: 0.2,
},
axisY: {
gridDash: [3],
gridWidth: 0.4,
},
legend: {
labelFontSize: 11,
padding: 1,
symbolType: 'square',
},
range: {
category: ['#3e5c69', '#6793a6', '#182429', '#0570b0', '#3690c0', '#74a9cf', '#a6bddb', '#e2ddf2'],
},
};
/* harmony default export */ var theme_vox = (voxTheme);
//# sourceMappingURL=theme-vox.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-urbaninstitute.js
const theme_urbaninstitute_markColor = '#1696d2';
const theme_urbaninstitute_axisColor = '#000000';
const theme_urbaninstitute_backgroundColor = '#FFFFFF';
const theme_urbaninstitute_font = 'Lato';
const theme_urbaninstitute_labelFont = 'Lato';
const sourceFont = 'Lato';
const gridColor = '#DEDDDD';
const theme_urbaninstitute_titleFontSize = 18;
const theme_urbaninstitute_colorSchemes = {
'main-colors': ['#1696d2', '#d2d2d2', '#000000', '#fdbf11', '#ec008b', '#55b748', '#5c5859', '#db2b27'],
'shades-blue': ['#CFE8F3', '#A2D4EC', '#73BFE2', '#46ABDB', '#1696D2', '#12719E', '#0A4C6A', '#062635'],
'shades-gray': ['#F5F5F5', '#ECECEC', '#E3E3E3', '#DCDBDB', '#D2D2D2', '#9D9D9D', '#696969', '#353535'],
'shades-yellow': ['#FFF2CF', '#FCE39E', '#FDD870', '#FCCB41', '#FDBF11', '#E88E2D', '#CA5800', '#843215'],
'shades-magenta': ['#F5CBDF', '#EB99C2', '#E46AA7', '#E54096', '#EC008B', '#AF1F6B', '#761548', '#351123'],
'shades-green': ['#DCEDD9', '#BCDEB4', '#98CF90', '#78C26D', '#55B748', '#408941', '#2C5C2D', '#1A2E19'],
'shades-black': ['#D5D5D4', '#ADABAC', '#848081', '#5C5859', '#332D2F', '#262223', '#1A1717', '#0E0C0D'],
'shades-red': ['#F8D5D4', '#F1AAA9', '#E9807D', '#E25552', '#DB2B27', '#A4201D', '#6E1614', '#370B0A'],
'one-group': ['#1696d2', '#000000'],
'two-groups-cat-1': ['#1696d2', '#000000'],
'two-groups-cat-2': ['#1696d2', '#fdbf11'],
'two-groups-cat-3': ['#1696d2', '#db2b27'],
'two-groups-seq': ['#a2d4ec', '#1696d2'],
'three-groups-cat': ['#1696d2', '#fdbf11', '#000000'],
'three-groups-seq': ['#a2d4ec', '#1696d2', '#0a4c6a'],
'four-groups-cat-1': ['#000000', '#d2d2d2', '#fdbf11', '#1696d2'],
'four-groups-cat-2': ['#1696d2', '#ec0008b', '#fdbf11', '#5c5859'],
'four-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a'],
'five-groups-cat-1': ['#1696d2', '#fdbf11', '#d2d2d2', '#ec008b', '#000000'],
'five-groups-cat-2': ['#1696d2', '#0a4c6a', '#d2d2d2', '#fdbf11', '#332d2f'],
'five-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a', '#000000'],
'six-groups-cat-1': ['#1696d2', '#ec008b', '#fdbf11', '#000000', '#d2d2d2', '#55b748'],
'six-groups-cat-2': ['#1696d2', '#d2d2d2', '#ec008b', '#fdbf11', '#332d2f', '#0a4c6a'],
'six-groups-seq': ['#cfe8f3', '#a2d4ec', '#73bfe2', '#46abdb', '#1696d2', '#12719e'],
'diverging-colors': ['#ca5800', '#fdbf11', '#fdd870', '#fff2cf', '#cfe8f3', '#73bfe2', '#1696d2', '#0a4c6a'],
};
const urbanInstituteTheme = {
background: theme_urbaninstitute_backgroundColor,
title: {
anchor: 'start',
fontSize: theme_urbaninstitute_titleFontSize,
font: theme_urbaninstitute_font,
},
axisX: {
domain: true,
domainColor: theme_urbaninstitute_axisColor,
domainWidth: 1,
grid: false,
labelFontSize: 12,
labelFont: theme_urbaninstitute_labelFont,
labelAngle: 0,
tickColor: theme_urbaninstitute_axisColor,
tickSize: 5,
titleFontSize: 12,
titlePadding: 10,
titleFont: theme_urbaninstitute_font,
},
axisY: {
domain: false,
domainWidth: 1,
grid: true,
gridColor: gridColor,
gridWidth: 1,
labelFontSize: 12,
labelFont: theme_urbaninstitute_labelFont,
labelPadding: 8,
ticks: false,
titleFontSize: 12,
titlePadding: 10,
titleFont: theme_urbaninstitute_font,
titleAngle: 0,
titleY: -10,
titleX: 18,
},
legend: {
labelFontSize: 12,
labelFont: theme_urbaninstitute_labelFont,
symbolSize: 100,
titleFontSize: 12,
titlePadding: 10,
titleFont: theme_urbaninstitute_font,
orient: 'right',
offset: 10,
},
view: {
stroke: 'transparent',
},
range: {
category: theme_urbaninstitute_colorSchemes['six-groups-cat-1'],
diverging: theme_urbaninstitute_colorSchemes['diverging-colors'],
heatmap: theme_urbaninstitute_colorSchemes['diverging-colors'],
ordinal: theme_urbaninstitute_colorSchemes['six-groups-seq'],
ramp: theme_urbaninstitute_colorSchemes['shades-blue'],
},
area: {
fill: theme_urbaninstitute_markColor,
},
rect: {
fill: theme_urbaninstitute_markColor,
},
line: {
color: theme_urbaninstitute_markColor,
stroke: theme_urbaninstitute_markColor,
strokeWidth: 5,
},
trail: {
color: theme_urbaninstitute_markColor,
stroke: theme_urbaninstitute_markColor,
strokeWidth: 0,
size: 1,
},
path: {
stroke: theme_urbaninstitute_markColor,
strokeWidth: 0.5,
},
point: {
filled: true,
},
text: {
font: sourceFont,
color: theme_urbaninstitute_markColor,
fontSize: 11,
align: 'center',
fontWeight: 400,
size: 11,
},
style: {
bar: {
fill: theme_urbaninstitute_markColor,
stroke: null,
},
},
arc: { fill: theme_urbaninstitute_markColor },
shape: { stroke: theme_urbaninstitute_markColor },
symbol: { fill: theme_urbaninstitute_markColor, size: 30 },
};
/* harmony default export */ var theme_urbaninstitute = (urbanInstituteTheme);
//# sourceMappingURL=theme-urbaninstitute.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/theme-googlecharts.js
/**
* Copyright 2020 Google LLC.
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
const theme_googlecharts_markColor = '#3366CC';
const theme_googlecharts_gridColor = '#ccc';
const theme_googlecharts_defaultFont = 'Arial, sans-serif';
const googlechartsTheme = {
arc: { fill: theme_googlecharts_markColor },
area: { fill: theme_googlecharts_markColor },
path: { stroke: theme_googlecharts_markColor },
rect: { fill: theme_googlecharts_markColor },
shape: { stroke: theme_googlecharts_markColor },
symbol: { stroke: theme_googlecharts_markColor },
circle: { fill: theme_googlecharts_markColor },
background: '#fff',
padding: {
top: 10,
right: 10,
bottom: 10,
left: 10,
},
style: {
'guide-label': {
font: theme_googlecharts_defaultFont,
fontSize: 12,
},
'guide-title': {
font: theme_googlecharts_defaultFont,
fontSize: 12,
},
'group-title': {
font: theme_googlecharts_defaultFont,
fontSize: 12,
},
},
title: {
font: theme_googlecharts_defaultFont,
fontSize: 14,
fontWeight: 'bold',
dy: -3,
anchor: 'start',
},
axis: {
gridColor: theme_googlecharts_gridColor,
tickColor: theme_googlecharts_gridColor,
domain: false,
grid: true,
},
range: {
category: [
'#4285F4',
'#DB4437',
'#F4B400',
'#0F9D58',
'#AB47BC',
'#00ACC1',
'#FF7043',
'#9E9D24',
'#5C6BC0',
'#F06292',
'#00796B',
'#C2185B',
],
heatmap: ['#c6dafc', '#5e97f6', '#2a56c6'],
},
};
/* harmony default export */ var theme_googlecharts = (googlechartsTheme);
//# sourceMappingURL=theme-googlecharts.js.map
// CONCATENATED MODULE: ./node_modules/vega-themes/build/src/index.js
const build_src_version = vega_themes_build_package.version;
//# sourceMappingURL=index.js.map
// EXTERNAL MODULE: ./node_modules/vega-tooltip/build/package.json
var vega_tooltip_build_package = __webpack_require__(283);
// CONCATENATED MODULE: ./node_modules/vega-tooltip/build/src/style.js
// generated with build-style.sh
/* harmony default export */ var src_style = (`#vg-tooltip-element {
visibility: hidden;
padding: 8px;
position: fixed;
z-index: 1000;
font-family: sans-serif;
font-size: 11px;
border-radius: 3px;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
/* The default theme is the light theme. */
background-color: rgba(255, 255, 255, 0.95);
border: 1px solid #d9d9d9;
color: black; }
#vg-tooltip-element.visible {
visibility: visible; }
#vg-tooltip-element h2 {
margin-top: 0;
margin-bottom: 10px;
font-size: 13px; }
#vg-tooltip-element table {
border-spacing: 0; }
#vg-tooltip-element table tr {
border: none; }
#vg-tooltip-element table tr td {
overflow: hidden;
text-overflow: ellipsis;
padding-top: 2px;
padding-bottom: 2px; }
#vg-tooltip-element table tr td.key {
color: #808080;
max-width: 150px;
text-align: right;
padding-right: 4px; }
#vg-tooltip-element table tr td.value {
display: block;
max-width: 300px;
max-height: 7em;
text-align: left; }
#vg-tooltip-element.dark-theme {
background-color: rgba(32, 32, 32, 0.9);
border: 1px solid #f5f5f5;
color: white; }
#vg-tooltip-element.dark-theme td.key {
color: #bfbfbf; }
`);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic3R5bGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc3R5bGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsZ0NBQWdDO0FBQ2hDLGVBQWU7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0NBNENkLENBQUMifQ==
// CONCATENATED MODULE: ./node_modules/vega-tooltip/build/src/defaults.js
const defaults_EL_ID = 'vg-tooltip-element';
const defaults_DEFAULT_OPTIONS = {
/**
* X offset.
*/
offsetX: 10,
/**
* Y offset.
*/
offsetY: 10,
/**
* ID of the tooltip element.
*/
id: defaults_EL_ID,
/**
* ID of the tooltip CSS style.
*/
styleId: 'vega-tooltip-style',
/**
* The name of the theme. You can use the CSS class called [THEME]-theme to style the tooltips.
*
* There are two predefined themes: "light" (default) and "dark".
*/
theme: 'light',
/**
* Do not use the default styles provided by Vega Tooltip. If you enable this option, you need to use your own styles. It is not necessary to disable the default style when using a custom theme.
*/
disableDefaultStyle: false,
/**
* HTML sanitizer function that removes dangerous HTML to prevent XSS.
*
* This should be a function from string to string. You may replace it with a formatter such as a markdown formatter.
*/
sanitize: defaults_escapeHTML,
/**
* The maximum recursion depth when printing objects in the tooltip.
*/
maxDepth: 2
};
/**
* Escape special HTML characters.
*
* @param value A value to convert to string and HTML-escape.
*/
function defaults_escapeHTML(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;');
}
function defaults_createDefaultStyle(id) {
// Just in case this id comes from a user, ensure these is no security issues
if (!/^[A-Za-z]+[-:.\w]*$/.test(id)) {
throw new Error('Invalid HTML ID');
}
return src_style.toString().replace(defaults_EL_ID, id);
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdHMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZGVmYXVsdHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxZQUFZLE1BQU0sU0FBUyxDQUFDO0FBRW5DLE1BQU0sS0FBSyxHQUFHLG9CQUFvQixDQUFDO0FBRW5DLE1BQU0sQ0FBQyxNQUFNLGVBQWUsR0FBRztJQUM3Qjs7T0FFRztJQUNILE9BQU8sRUFBRSxFQUFFO0lBRVg7O09BRUc7SUFDSCxPQUFPLEVBQUUsRUFBRTtJQUVYOztPQUVHO0lBQ0gsRUFBRSxFQUFFLEtBQUs7SUFFVDs7T0FFRztJQUNILE9BQU8sRUFBRSxvQkFBb0I7SUFFN0I7Ozs7T0FJRztJQUNILEtBQUssRUFBRSxPQUFPO0lBRWQ7O09BRUc7SUFDSCxtQkFBbUIsRUFBRSxLQUFLO0lBRTFCOzs7O09BSUc7SUFDSCxRQUFRLEVBQUUsVUFBVTtJQUVwQjs7T0FFRztJQUNILFFBQVEsRUFBRSxDQUFDO0NBQ1osQ0FBQztBQUlGOzs7O0dBSUc7QUFDSCxNQUFNLFVBQVUsVUFBVSxDQUFDLEtBQVU7SUFDbkMsT0FBTyxNQUFNLENBQUMsS0FBSyxDQUFDO1NBQ2pCLE9BQU8sQ0FBQyxJQUFJLEVBQUUsT0FBTyxDQUFDO1NBQ3RCLE9BQU8sQ0FBQyxJQUFJLEVBQUUsTUFBTSxDQUFDLENBQUM7QUFDM0IsQ0FBQztBQUVELE1BQU0sVUFBVSxrQkFBa0IsQ0FBQyxFQUFVO0lBQzNDLDZFQUE2RTtJQUM3RSxJQUFJLENBQUMscUJBQXFCLENBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxFQUFFO1FBQ25DLE1BQU0sSUFBSSxLQUFLLENBQUMsaUJBQWlCLENBQUMsQ0FBQztLQUNwQztJQUVELE9BQU8sWUFBWSxDQUFDLFFBQVEsRUFBRSxDQUFDLE9BQU8sQ0FBQyxLQUFLLEVBQUUsRUFBRSxDQUFDLENBQUM7QUFDcEQsQ0FBQyJ9
// CONCATENATED MODULE: ./node_modules/vega-tooltip/build/src/formatValue.js
var formatValue_rest = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
/**
* Format the value to be shown in the toolip.
*
* @param value The value to show in the tooltip.
* @param valueToHtml Function to convert a single cell value to an HTML string
*/
function formatValue_formatValue(value, valueToHtml, maxDepth) {
if (Object(vega_util["A" /* isArray */])(value)) {
return `[${value.map(v => valueToHtml(Object(vega_util["H" /* isString */])(v) ? v : formatValue_stringify(v, maxDepth))).join(', ')}]`;
}
if (Object(vega_util["F" /* isObject */])(value)) {
let content = '';
const _a = value, { title } = _a, rest = formatValue_rest(_a, ["title"]);
if (title) {
content += `<h2>${valueToHtml(title)}</h2>`;
}
const keys = Object.keys(rest);
if (keys.length > 0) {
content += '<table>';
for (const key of keys) {
let val = rest[key];
// ignore undefined properties
if (val === undefined) {
continue;
}
if (Object(vega_util["F" /* isObject */])(val)) {
val = formatValue_stringify(val, maxDepth);
}
content += `<tr><td class="key">${valueToHtml(key)}:</td><td class="value">${valueToHtml(val)}</td></tr>`;
}
content += `</table>`;
}
return content || '{}'; // show empty object if there are no properties
}
return valueToHtml(value);
}
function formatValue_replacer(maxDepth) {
const stack = [];
return function (key, value) {
if (typeof value !== 'object' || value === null) {
return value;
}
const pos = stack.indexOf(this) + 1;
stack.length = pos;
if (stack.length > maxDepth) {
return '[Object]';
}
if (stack.indexOf(value) >= 0) {
return '[Circular]';
}
stack.push(value);
return value;
};
}
/**
* Stringify any JS object to valid JSON
*/
function formatValue_stringify(obj, maxDepth) {
return JSON.stringify(obj, formatValue_replacer(maxDepth));
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9ybWF0VmFsdWUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZm9ybWF0VmFsdWUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQSxPQUFPLEVBQUMsT0FBTyxFQUFFLFFBQVEsRUFBRSxRQUFRLEVBQUMsTUFBTSxXQUFXLENBQUM7QUFFdEQ7Ozs7O0dBS0c7QUFDSCxNQUFNLFVBQVUsV0FBVyxDQUFDLEtBQVUsRUFBRSxXQUFtQyxFQUFFLFFBQWdCO0lBQzNGLElBQUksT0FBTyxDQUFDLEtBQUssQ0FBQyxFQUFFO1FBQ2xCLE9BQU8sSUFBSSxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsV0FBVyxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxTQUFTLENBQUMsQ0FBQyxFQUFFLFFBQVEsQ0FBQyxDQUFDLENBQUMsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQztLQUNoRztJQUVELElBQUksUUFBUSxDQUFDLEtBQUssQ0FBQyxFQUFFO1FBQ25CLElBQUksT0FBTyxHQUFHLEVBQUUsQ0FBQztRQUVqQixNQUFNLFVBQStCLEVBQS9CLEVBQUMsS0FBSyxPQUF5QixFQUF2Qiw0QkFBdUIsQ0FBQztRQUV0QyxJQUFJLEtBQUssRUFBRTtZQUNULE9BQU8sSUFBSSxPQUFPLFdBQVcsQ0FBQyxLQUFLLENBQUMsT0FBTyxDQUFDO1NBQzdDO1FBRUQsTUFBTSxJQUFJLEdBQUcsTUFBTSxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztRQUMvQixJQUFJLElBQUksQ0FBQyxNQUFNLEdBQUcsQ0FBQyxFQUFFO1lBQ25CLE9BQU8sSUFBSSxTQUFTLENBQUM7WUFDckIsS0FBSyxNQUFNLEdBQUcsSUFBSSxJQUFJLEVBQUU7Z0JBQ3RCLElBQUksR0FBRyxHQUFJLElBQVksQ0FBQyxHQUFHLENBQUMsQ0FBQztnQkFFN0IsOEJBQThCO2dCQUM5QixJQUFJLEdBQUcsS0FBSyxTQUFTLEVBQUU7b0JBQ3JCLFNBQVM7aUJBQ1Y7Z0JBRUQsSUFBSSxRQUFRLENBQUMsR0FBRyxDQUFDLEVBQUU7b0JBQ2pCLEdBQUcsR0FBRyxTQUFTLENBQUMsR0FBRyxFQUFFLFFBQVEsQ0FBQyxDQUFDO2lCQUNoQztnQkFFRCxPQUFPLElBQUksdUJBQXVCLFdBQVcsQ0FBQyxHQUFHLENBQUMsMkJBQTJCLFdBQVcsQ0FBQyxHQUFHLENBQUMsWUFBWSxDQUFDO2FBQzNHO1lBQ0QsT0FBTyxJQUFJLFVBQVUsQ0FBQztTQUN2QjtRQUVELE9BQU8sT0FBTyxJQUFJLElBQUksQ0FBQyxDQUFDLCtDQUErQztLQUN4RTtJQUVELE9BQU8sV0FBVyxDQUFDLEtBQUssQ0FBQyxDQUFDO0FBQzVCLENBQUM7QUFFRCxNQUFNLFVBQVUsUUFBUSxDQUFDLFFBQWdCO0lBQ3ZDLE1BQU0sS0FBSyxHQUFVLEVBQUUsQ0FBQztJQUV4QixPQUFPLFVBQW9CLEdBQVcsRUFBRSxLQUFVO1FBQ2hELElBQUksT0FBTyxLQUFLLEtBQUssUUFBUSxJQUFJLEtBQUssS0FBSyxJQUFJLEVBQUU7WUFDL0MsT0FBTyxLQUFLLENBQUM7U0FDZDtRQUNELE1BQU0sR0FBRyxHQUFHLEtBQUssQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1FBQ3BDLEtBQUssQ0FBQyxNQUFNLEdBQUcsR0FBRyxDQUFDO1FBQ25CLElBQUksS0FBSyxDQUFDLE1BQU0sR0FBRyxRQUFRLEVBQUU7WUFDM0IsT0FBTyxVQUFVLENBQUM7U0FDbkI7UUFDRCxJQUFJLEtBQUssQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxFQUFFO1lBQzdCLE9BQU8sWUFBWSxDQUFDO1NBQ3JCO1FBQ0QsS0FBSyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsQ0FBQztRQUNsQixPQUFPLEtBQUssQ0FBQztJQUNmLENBQUMsQ0FBQztBQUNKLENBQUM7QUFFRDs7R0FFRztBQUNILE1BQU0sVUFBVSxTQUFTLENBQUMsR0FBUSxFQUFFLFFBQWdCO0lBQ2xELE9BQU8sSUFBSSxDQUFDLFNBQVMsQ0FBQyxHQUFHLEVBQUUsUUFBUSxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUM7QUFDakQsQ0FBQyJ9
// CONCATENATED MODULE: ./node_modules/vega-tooltip/build/src/position.js
/**
* Position the tooltip
*
* @param event The mouse event.
* @param tooltipBox
* @param offsetX Horizontal offset.
* @param offsetY Vertical offset.
*/
function calculatePosition(event, tooltipBox, offsetX, offsetY) {
let x = event.clientX + offsetX;
if (x + tooltipBox.width > window.innerWidth) {
x = +event.clientX - offsetX - tooltipBox.width;
}
let y = event.clientY + offsetY;
if (y + tooltipBox.height > window.innerHeight) {
y = +event.clientY - offsetY - tooltipBox.height;
}
return { x, y };
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9zaXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvcG9zaXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7R0FPRztBQUNILE1BQU0sVUFBVSxpQkFBaUIsQ0FDL0IsS0FBaUIsRUFDakIsVUFBMkMsRUFDM0MsT0FBZSxFQUNmLE9BQWU7SUFFZixJQUFJLENBQUMsR0FBRyxLQUFLLENBQUMsT0FBTyxHQUFHLE9BQU8sQ0FBQztJQUNoQyxJQUFJLENBQUMsR0FBRyxVQUFVLENBQUMsS0FBSyxHQUFHLE1BQU0sQ0FBQyxVQUFVLEVBQUU7UUFDNUMsQ0FBQyxHQUFHLENBQUMsS0FBSyxDQUFDLE9BQU8sR0FBRyxPQUFPLEdBQUcsVUFBVSxDQUFDLEtBQUssQ0FBQztLQUNqRDtJQUVELElBQUksQ0FBQyxHQUFHLEtBQUssQ0FBQyxPQUFPLEdBQUcsT0FBTyxDQUFDO0lBQ2hDLElBQUksQ0FBQyxHQUFHLFVBQVUsQ0FBQyxNQUFNLEdBQUcsTUFBTSxDQUFDLFdBQVcsRUFBRTtRQUM5QyxDQUFDLEdBQUcsQ0FBQyxLQUFLLENBQUMsT0FBTyxHQUFHLE9BQU8sR0FBRyxVQUFVLENBQUMsTUFBTSxDQUFDO0tBQ2xEO0lBRUQsT0FBTyxFQUFDLENBQUMsRUFBRSxDQUFDLEVBQUMsQ0FBQztBQUNoQixDQUFDIn0=
// CONCATENATED MODULE: ./node_modules/vega-tooltip/build/src/Handler.js
/**
* The tooltip handler class.
*/
class src_Handler_Handler {
/**
* Create the tooltip handler and initialize the element and style.
*
* @param options Tooltip Options
*/
constructor(options) {
this.options = Object.assign(Object.assign({}, defaults_DEFAULT_OPTIONS), options);
const elementId = this.options.id;
// bind this to call
this.call = this.tooltipHandler.bind(this);
// prepend a default stylesheet for tooltips to the head
if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) {
const style = document.createElement('style');
style.setAttribute('id', this.options.styleId);
style.innerHTML = defaults_createDefaultStyle(elementId);
const head = document.head;
if (head.childNodes.length > 0) {
head.insertBefore(style, head.childNodes[0]);
}
else {
head.appendChild(style);
}
}
// append a div element that we use as a tooltip unless it already exists
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.el = document.getElementById(elementId);
if (!this.el) {
this.el = document.createElement('div');
this.el.setAttribute('id', elementId);
this.el.classList.add('vg-tooltip');
document.body.appendChild(this.el);
}
}
/**
* The tooltip handler function.
*/
tooltipHandler(handler, event, item, value) {
// console.log(handler, event, item, value);
// hide tooltip for null, undefined, or empty string values
if (value == null || value === '') {
this.el.classList.remove('visible', `${this.options.theme}-theme`);
return;
}
// set the tooltip content
this.el.innerHTML = formatValue_formatValue(value, this.options.sanitize, this.options.maxDepth);
// make the tooltip visible
this.el.classList.add('visible', `${this.options.theme}-theme`);
const { x, y } = calculatePosition(event, this.el.getBoundingClientRect(), this.options.offsetX, this.options.offsetY);
this.el.setAttribute('style', `top: ${y}px; left: ${x}px`);
}
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiSGFuZGxlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9IYW5kbGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUVBLE9BQU8sRUFBQyxrQkFBa0IsRUFBRSxlQUFlLEVBQVUsTUFBTSxZQUFZLENBQUM7QUFDeEUsT0FBTyxFQUFDLFdBQVcsRUFBQyxNQUFNLGVBQWUsQ0FBQztBQUMxQyxPQUFPLEVBQUMsaUJBQWlCLEVBQUMsTUFBTSxZQUFZLENBQUM7QUFFN0M7O0dBRUc7QUFDSCxNQUFNLE9BQU8sT0FBTztJQWdCbEI7Ozs7T0FJRztJQUNILFlBQVksT0FBMEI7UUFDcEMsSUFBSSxDQUFDLE9BQU8sbUNBQU8sZUFBZSxHQUFLLE9BQU8sQ0FBQyxDQUFDO1FBQ2hELE1BQU0sU0FBUyxHQUFHLElBQUksQ0FBQyxPQUFPLENBQUMsRUFBRSxDQUFDO1FBRWxDLG9CQUFvQjtRQUNwQixJQUFJLENBQUMsSUFBSSxHQUFHLElBQUksQ0FBQyxjQUFjLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO1FBRTNDLHdEQUF3RDtRQUN4RCxJQUFJLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxtQkFBbUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxjQUFjLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxPQUFPLENBQUMsRUFBRTtZQUN2RixNQUFNLEtBQUssR0FBRyxRQUFRLENBQUMsYUFBYSxDQUFDLE9BQU8sQ0FBQyxDQUFDO1lBQzlDLEtBQUssQ0FBQyxZQUFZLENBQUMsSUFBSSxFQUFFLElBQUksQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUM7WUFDL0MsS0FBSyxDQUFDLFNBQVMsR0FBRyxrQkFBa0IsQ0FBQyxTQUFTLENBQUMsQ0FBQztZQUVoRCxNQUFNLElBQUksR0FBRyxRQUFRLENBQUMsSUFBSSxDQUFDO1lBQzNCLElBQUksSUFBSSxDQUFDLFVBQVUsQ0FBQyxNQUFNLEdBQUcsQ0FBQyxFQUFFO2dCQUM5QixJQUFJLENBQUMsWUFBWSxDQUFDLEtBQUssRUFBRSxJQUFJLENBQUMsVUFBVSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7YUFDOUM7aUJBQU07Z0JBQ0wsSUFBSSxDQUFDLFdBQVcsQ0FBQyxLQUFLLENBQUMsQ0FBQzthQUN6QjtTQUNGO1FBRUQseUVBQXlFO1FBQ3pFLG9FQUFvRTtRQUNwRSxJQUFJLENBQUMsRUFBRSxHQUFHLFFBQVEsQ0FBQyxjQUFjLENBQUMsU0FBUyxDQUFFLENBQUM7UUFDOUMsSUFBSSxDQUFDLElBQUksQ0FBQyxFQUFFLEVBQUU7WUFDWixJQUFJLENBQUMsRUFBRSxHQUFHLFFBQVEsQ0FBQyxhQUFhLENBQUMsS0FBSyxDQUFDLENBQUM7WUFDeEMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxZQUFZLENBQUMsSUFBSSxFQUFFLFNBQVMsQ0FBQyxDQUFDO1lBQ3RDLElBQUksQ0FBQyxFQUFFLENBQUMsU0FBUyxDQUFDLEdBQUcsQ0FBQyxZQUFZLENBQUMsQ0FBQztZQUVwQyxRQUFRLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRSxDQUFDLENBQUM7U0FDcEM7SUFDSCxDQUFDO0lBRUQ7O09BRUc7SUFDSyxjQUFjLENBQUMsT0FBWSxFQUFFLEtBQWlCLEVBQUUsSUFBUyxFQUFFLEtBQVU7UUFDM0UsNENBQTRDO1FBRTVDLDJEQUEyRDtRQUMzRCxJQUFJLEtBQUssSUFBSSxJQUFJLElBQUksS0FBSyxLQUFLLEVBQUUsRUFBRTtZQUNqQyxJQUFJLENBQUMsRUFBRSxDQUFDLFNBQVMsQ0FBQyxNQUFNLENBQUMsU0FBUyxFQUFFLEdBQUcsSUFBSSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFFBQVEsQ0FBQyxDQUFDO1lBQ25FLE9BQU87U0FDUjtRQUVELDBCQUEwQjtRQUMxQixJQUFJLENBQUMsRUFBRSxDQUFDLFNBQVMsR0FBRyxXQUFXLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxPQUFPLENBQUMsUUFBUSxFQUFFLElBQUksQ0FBQyxPQUFPLENBQUMsUUFBUSxDQUFDLENBQUM7UUFFckYsMkJBQTJCO1FBQzNCLElBQUksQ0FBQyxFQUFFLENBQUMsU0FBUyxDQUFDLEdBQUcsQ0FBQyxTQUFTLEVBQUUsR0FBRyxJQUFJLENBQUMsT0FBTyxDQUFDLEtBQUssUUFBUSxDQUFDLENBQUM7UUFFaEUsTUFBTSxFQUFDLENBQUMsRUFBRSxDQUFDLEVBQUMsR0FBRyxpQkFBaUIsQ0FDOUIsS0FBSyxFQUNMLElBQUksQ0FBQyxFQUFFLENBQUMscUJBQXFCLEVBQUUsRUFDL0IsSUFBSSxDQUFDLE9BQU8sQ0FBQyxPQUFPLEVBQ3BCLElBQUksQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUNyQixDQUFDO1FBRUYsSUFBSSxDQUFDLEVBQUUsQ0FBQyxZQUFZLENBQUMsT0FBTyxFQUFFLFFBQVEsQ0FBQyxhQUFhLENBQUMsSUFBSSxDQUFDLENBQUM7SUFDN0QsQ0FBQztDQUNGIn0=
// CONCATENATED MODULE: ./node_modules/vega-tooltip/build/src/index.js
const vega_tooltip_build_src_version = vega_tooltip_build_package.version;
/**
* Create a tooltip handler and register it with the provided view.
*
* @param view The Vega view.
* @param opt Tooltip options.
*/
/* harmony default export */ var build_src = (function (view, opt) {
const handler = new src_Handler_Handler(opt);
view.tooltip(handler.call).run();
return handler;
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxHQUFHLE1BQU0saUJBQWlCLENBQUM7QUFJbEMsT0FBTyxFQUFDLE9BQU8sRUFBQyxNQUFNLFdBQVcsQ0FBQztBQUVsQyxNQUFNLE9BQU8sR0FBRyxHQUFHLENBQUMsT0FBTyxDQUFDO0FBRTVCLGNBQWMsWUFBWSxDQUFDO0FBQzNCLGNBQWMsZUFBZSxDQUFDO0FBQzlCLGNBQWMsWUFBWSxDQUFDO0FBQzNCLGNBQWMsV0FBVyxDQUFDO0FBQzFCLE9BQU8sRUFBQyxPQUFPLEVBQUMsQ0FBQztBQUVqQjs7Ozs7R0FLRztBQUNILE1BQU0sQ0FBQyxPQUFPLFdBQVUsSUFBVSxFQUFFLEdBQXNCO0lBQ3hELE1BQU0sT0FBTyxHQUFHLElBQUksT0FBTyxDQUFDLEdBQUcsQ0FBQyxDQUFDO0lBRWpDLElBQUksQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBRWpDLE9BQU8sT0FBTyxDQUFDO0FBQ2pCLENBQUMifQ==
// CONCATENATED MODULE: ./node_modules/vega-embed/build/src/post.js
/**
* Open editor url in a new window, and pass a message.
*/
/* harmony default export */ var src_post = (function (window, url, data) {
const editor = window.open(url);
const wait = 10000;
const step = 250;
// eslint-disable-next-line no-bitwise
let count = ~~(wait / step);
function listen(evt) {
if (evt.source === editor) {
count = 0;
window.removeEventListener('message', listen, false);
}
}
window.addEventListener('message', listen, false);
// send message
// periodically resend until ack received or timeout
function send() {
if (count <= 0) {
return;
}
editor.postMessage(data, '*');
setTimeout(send, step);
count -= 1;
}
setTimeout(send, step);
});
//# sourceMappingURL=post.js.map
// CONCATENATED MODULE: ./node_modules/vega-embed/build/src/style.js
// generated with build-style.sh
/* harmony default export */ var build_src_style = (`.vega-embed {
position: relative;
display: inline-block;
padding-right: 38px; }
.vega-embed details:not([open]) > :not(summary) {
display: none !important; }
.vega-embed summary {
list-style: none;
position: absolute;
top: 0;
right: 0;
padding: 6px;
z-index: 1000;
background: white;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
color: #1b1e23;
border: 1px solid #aaa;
border-radius: 999px;
opacity: 0.2;
transition: opacity 0.4s ease-in;
outline: none;
cursor: pointer;
line-height: 0px; }
.vega-embed summary::-webkit-details-marker {
display: none; }
.vega-embed summary:active {
box-shadow: #aaa 0px 0px 0px 1px inset; }
.vega-embed summary svg {
width: 14px;
height: 14px; }
.vega-embed details[open] summary {
opacity: 0.7; }
.vega-embed:hover summary,
.vega-embed:focus summary {
opacity: 1 !important;
transition: opacity 0.2s ease; }
.vega-embed .vega-actions {
position: absolute;
top: 35px;
right: -9px;
display: flex;
flex-direction: column;
padding-bottom: 8px;
padding-top: 8px;
border-radius: 4px;
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
border: 1px solid #d9d9d9;
background: white;
animation-duration: 0.15s;
animation-name: scale-in;
animation-timing-function: cubic-bezier(0.2, 0, 0.13, 1.5); }
.vega-embed .vega-actions a {
padding: 8px 16px;
font-family: sans-serif;
font-size: 14px;
font-weight: 600;
white-space: nowrap;
color: #434a56;
text-decoration: none; }
.vega-embed .vega-actions a:hover {
background-color: #f7f7f9;
color: black; }
.vega-embed .vega-actions::before, .vega-embed .vega-actions::after {
content: "";
display: inline-block;
position: absolute; }
.vega-embed .vega-actions::before {
left: auto;
right: 14px;
top: -16px;
border: 8px solid #0000;
border-bottom-color: #d9d9d9; }
.vega-embed .vega-actions::after {
left: auto;
right: 15px;
top: -14px;
border: 7px solid #0000;
border-bottom-color: #fff; }
.vega-embed-wrapper {
max-width: 100%;
overflow: scroll;
padding-right: 14px; }
@keyframes scale-in {
from {
opacity: 0;
transform: scale(0.6); }
to {
opacity: 1;
transform: scale(1); } }
`);
//# sourceMappingURL=style.js.map
// CONCATENATED MODULE: ./node_modules/vega-embed/build/src/embed.js
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "vega", function() { return embed_vega; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "vegaLite", function() { return embed_vegaLite; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "guessMode", function() { return embed_guessMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return embed_embed; });
const embed_vega = vega_namespaceObject;
let embed_vegaLite = build_src_namespaceObject;
// For backwards compatibility with Vega-Lite before v4.
const embed_w = window;
if (embed_vegaLite === undefined && embed_w['vl'] && embed_w['vl'].compile) {
embed_vegaLite = embed_w['vl'];
}
const embed_I18N = {
CLICK_TO_VIEW_ACTIONS: 'Click to view actions',
COMPILED_ACTION: 'View Compiled Vega',
EDITOR_ACTION: 'Open in Vega Editor',
PNG_ACTION: 'Save as PNG',
SOURCE_ACTION: 'View Source',
SVG_ACTION: 'Save as SVG'
};
const embed_NAMES = {
vega: 'Vega',
'vega-lite': 'Vega-Lite'
};
const embed_VERSION = {
vega: embed_vega.version,
'vega-lite': embed_vegaLite ? embed_vegaLite.version : 'not available'
};
const embed_PREPROCESSOR = {
vega: vgSpec => vgSpec,
'vega-lite': (vlSpec, config) => embed_vegaLite.compile(vlSpec, { config: config }).spec
};
const embed_SVG_CIRCLES = `
<svg viewBox="0 0 16 16" fill="currentColor" stroke="none" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
<circle r="2" cy="8" cx="2"></circle>
<circle r="2" cy="8" cx="8"></circle>
<circle r="2" cy="8" cx="14"></circle>
</svg>`;
function embed_isTooltipHandler(h) {
return typeof h === 'function';
}
function embed_viewSource(source, sourceHeader, sourceFooter, mode) {
const header = `<html><head>${sourceHeader}</head><body><pre><code class="json">`;
const footer = `</code></pre>${sourceFooter}</body></html>`;
const win = window.open('');
win.document.write(header + source + footer);
win.document.title = `${embed_NAMES[mode]} JSON Source`;
}
/**
* Try to guess the type of spec.
*
* @param spec Vega or Vega-Lite spec.
*/
function embed_guessMode(spec, providedMode) {
// Decide mode
if (spec.$schema) {
const parsed = vega_schema_url_parser_default()(spec.$schema);
if (providedMode && providedMode !== parsed.library) {
console.warn(`The given visualization spec is written in ${embed_NAMES[parsed.library]}, but mode argument sets ${embed_NAMES[providedMode] || providedMode}.`);
}
const mode = parsed.library;
if (!Object(semver["satisfies"])(embed_VERSION[mode], `^${parsed.version.slice(1)}`)) {
console.warn(`The input spec uses ${embed_NAMES[mode]} ${parsed.version}, but the current version of ${embed_NAMES[mode]} is v${embed_VERSION[mode]}.`);
}
return mode;
}
// try to guess from the provided spec
if ('mark' in spec ||
'encoding' in spec ||
'layer' in spec ||
'hconcat' in spec ||
'vconcat' in spec ||
'facet' in spec ||
'repeat' in spec) {
return 'vega-lite';
}
if ('marks' in spec || 'signals' in spec || 'scales' in spec || 'axes' in spec) {
return 'vega';
}
return providedMode || 'vega';
}
function embed_isLoader(o) {
return !!(o && 'load' in o);
}
/**
* Embed a Vega visualization component in a web page. This function returns a promise.
*
* @param el DOM element in which to place component (DOM node or CSS selector).
* @param spec String : A URL string from which to load the Vega specification.
* Object : The Vega/Vega-Lite specification as a parsed JSON object.
* @param opt A JavaScript object containing options for embedding.
*/
function embed_embed(el, spec, opt = {}) {
return __awaiter(this, void 0, void 0, function* () {
const loader = embed_isLoader(opt.loader) ? opt.loader : embed_vega.loader(opt.loader);
// Load the visualization specification.
if (embed_vega.isString(spec)) {
const data = yield loader.load(spec);
return embed_embed(el, JSON.parse(data), opt);
}
opt = cjs_default()(opt, (spec.usermeta && spec.usermeta['embedOptions']) || {});
// Load Vega theme/configuration.
let config = opt.config || {};
if (embed_vega.isString(config)) {
const data = yield loader.load(config);
return embed_embed(el, spec, Object.assign(Object.assign({}, opt), { config: JSON.parse(data) }));
}
const actions = Object(vega_util["B" /* isBoolean */])(opt.actions)
? opt.actions
: cjs_default()({ export: { svg: true, png: true }, source: true, compiled: true, editor: true }, opt.actions || {});
const i18n = Object.assign(Object.assign({}, embed_I18N), opt.i18n);
const renderer = opt.renderer || 'canvas';
const logLevel = opt.logLevel || embed_vega.Warn;
const downloadFileName = opt.downloadFileName || 'visualization';
if (opt.defaultStyle !== false) {
// Add a default stylesheet to the head of the document.
const ID = 'vega-embed-style';
if (!document.getElementById(ID)) {
const style = document.createElement('style');
style.id = ID;
style.innerText =
opt.defaultStyle === undefined || opt.defaultStyle === true ? (build_src_style || '').toString() : opt.defaultStyle;
document.head.appendChild(style);
}
}
if (opt.theme) {
config = cjs_default()(vega_themes_build_src_namespaceObject[opt.theme], config);
}
const mode = embed_guessMode(spec, opt.mode);
let vgSpec = embed_PREPROCESSOR[mode](spec, config);
if (mode === 'vega-lite') {
if (vgSpec.$schema) {
const parsed = vega_schema_url_parser_default()(vgSpec.$schema);
if (!Object(semver["satisfies"])(embed_VERSION.vega, `^${parsed.version.slice(1)}`)) {
console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${embed_VERSION.vega}.`);
}
}
}
// ensure container div has class 'vega-embed'
const div = src_select(el) // d3.select supports elements and strings
.classed('vega-embed', true)
.html(''); // clear container
const patch = opt.patch;
if (patch) {
if (patch instanceof Function) {
vgSpec = patch(vgSpec);
}
else if (embed_vega.isString(patch)) {
const patchString = yield loader.load(patch);
// eslint-disable-next-line require-atomic-updates
vgSpec = cjs_default()(vgSpec, JSON.parse(patchString));
}
else {
vgSpec = cjs_default()(vgSpec, patch);
}
}
// Do not apply the config to Vega when we have already applied it to Vega-Lite.
// This call may throw an Error if parsing fails.
const runtime = embed_vega.parse(vgSpec, mode === 'vega-lite' ? {} : config);
const view = new embed_vega.View(runtime, {
loader,
logLevel,
renderer
});
if (opt.tooltip !== false) {
let handler;
if (embed_isTooltipHandler(opt.tooltip)) {
handler = opt.tooltip;
}
else {
// user provided boolean true or tooltip options
handler = new src_Handler_Handler(opt.tooltip === true ? {} : opt.tooltip).call;
}
view.tooltip(handler);
}
let { hover } = opt;
if (hover === undefined) {
hover = mode === 'vega';
}
if (hover) {
const { hoverSet, updateSet } = (typeof hover === 'boolean' ? {} : hover);
view.hover(hoverSet, updateSet);
}
if (opt) {
if (opt.width) {
view.width(opt.width);
}
if (opt.height) {
view.height(opt.height);
}
if (opt.padding) {
view.padding(opt.padding);
}
}
yield view.initialize(el).runAsync();
if (actions !== false) {
let wrapper = div;
if (opt.defaultStyle !== false) {
const details = div.append('details').attr('title', i18n.CLICK_TO_VIEW_ACTIONS);
wrapper = details;
const summary = details.insert('summary');
summary.html(embed_SVG_CIRCLES);
const dn = details.node();
document.addEventListener('click', evt => {
if (!dn.contains(evt.target)) {
dn.removeAttribute('open');
}
});
}
const ctrl = wrapper.insert('div').attr('class', 'vega-actions');
// add 'Export' action
if (actions === true || actions.export !== false) {
for (const ext of ['svg', 'png']) {
if (actions === true || actions.export === true || actions.export[ext]) {
const i18nExportAction = i18n[`${ext.toUpperCase()}_ACTION`];
ctrl
.append('a')
.text(i18nExportAction)
.attr('href', '#')
.attr('target', '_blank')
.attr('download', `${downloadFileName}.${ext}`)
// eslint-disable-next-line func-names
.on('mousedown', function () {
view
.toImageURL(ext, opt.scaleFactor)
.then(url => {
this.href = url;
})
.catch(error => {
throw error;
});
on_event.preventDefault();
});
}
}
}
// add 'View Source' action
if (actions === true || actions.source !== false) {
ctrl
.append('a')
.text(i18n.SOURCE_ACTION)
.attr('href', '#')
.on('mousedown', () => {
embed_viewSource(json_stringify_pretty_compact_default()(spec), opt.sourceHeader || '', opt.sourceFooter || '', mode);
on_event.preventDefault();
});
}
// add 'View Compiled' action
if (mode === 'vega-lite' && (actions === true || actions.compiled !== false)) {
ctrl
.append('a')
.text(i18n.COMPILED_ACTION)
.attr('href', '#')
.on('mousedown', () => {
embed_viewSource(json_stringify_pretty_compact_default()(vgSpec), opt.sourceHeader || '', opt.sourceFooter || '', 'vega');
on_event.preventDefault();
});
}
// add 'Open in Vega Editor' action
if (actions === true || actions.editor !== false) {
const editorUrl = opt.editorUrl || 'https://vega.github.io/editor/';
ctrl
.append('a')
.text(i18n.EDITOR_ACTION)
.attr('href', '#')
.on('mousedown', () => {
src_post(window, editorUrl, {
config: config,
mode,
renderer,
spec: json_stringify_pretty_compact_default()(spec)
});
on_event.preventDefault();
});
}
}
return { view, spec, vgSpec };
});
}
//# sourceMappingURL=embed.js.map
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
} else {
return (0, _from2.default)(arr);
}
};
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var P5Util = function () {
function P5Util() {
(0, _classCallCheck3.default)(this, P5Util);
this.p5Instance = window;
}
/**
* Set p5 instance globally.
* @param {Object} p5Instance
*/
(0, _createClass3.default)(P5Util, [{
key: 'setP5Instance',
value: function setP5Instance(p5Instance) {
this.p5Instance = p5Instance;
}
/**
* This function will check if the p5 is in the environment
* Either it is in the p5Instance mode OR it is in the window
* @returns {boolean} if it is in p5
*/
}, {
key: 'checkP5',
value: function checkP5() {
// typeof this.p5Instance !== 'undefined' && this.p5Instance.p5 && this.p5Instance.p5.Image && typeof this.p5Instance.p5.Image === 'function'
if (typeof this.p5Instance !== 'undefined' && typeof this.p5Instance.loadImage === 'function' || typeof this.p5Instance.p5 !== 'undefined' && typeof this.p5Instance.p5.Image !== 'undefined' && typeof this.p5Instance.p5.Image === 'function') return true;
return false;
}
/**
* Convert a canvas to Blob
* @param {HTMLCanvasElement} inputCanvas
* @returns {Blob} blob object
*/
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["getBlob"] }] */
}, {
key: 'getBlob',
value: function getBlob(inputCanvas) {
return new _promise2.default(function (resolve) {
inputCanvas.toBlob(function (blob) {
resolve(blob);
});
});
}
}, {
key: 'loadAsync',
/**
* Load image in async way.
* @param {String} url
*/
value: function loadAsync(url) {
var _this = this;
return new _promise2.default(function (resolve) {
_this.p5Instance.loadImage(url, function (img) {
resolve(img);
});
});
}
}, {
key: 'rawToBlob',
/**
* convert raw bytes to blob object
* @param {Array} raws
* @param {number} x
* @param {number} y
* @returns {Blob}
*/
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(raws, x, y) {
var arr, canvas, ctx, imgData, data, i, blob;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
arr = (0, _from2.default)(raws);
canvas = document.createElement('canvas'); // Consider using offScreenCanvas when it is ready?
ctx = canvas.getContext('2d');
canvas.width = x;
canvas.height = y;
imgData = ctx.createImageData(x, y);
data = imgData.data;
for (i = 0; i < x * y * 4; i += 1) {
data[i] = arr[i];
}ctx.putImageData(imgData, 0, 0);
_context.next = 11;
return this.getBlob(canvas);
case 11:
blob = _context.sent;
return _context.abrupt('return', blob);
case 13:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function rawToBlob(_x, _x2, _x3) {
return _ref.apply(this, arguments);
}
return rawToBlob;
}()
}, {
key: 'blobToP5Image',
/**
* Conver Blob to P5.Image
* @param {Blob} blob
* @param {Object} p5Img
*/
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(blob) {
var p5Img;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!this.checkP5()) {
_context2.next = 5;
break;
}
_context2.next = 3;
return this.loadAsync(URL.createObjectURL(blob));
case 3:
p5Img = _context2.sent;
return _context2.abrupt('return', p5Img);
case 5:
return _context2.abrupt('return', null);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function blobToP5Image(_x4) {
return _ref2.apply(this, arguments);
}
return blobToP5Image;
}()
}]);
return P5Util;
}();
var p5Utils = new P5Util();
exports.default = p5Utils;
/***/ }),
/* 84 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__(424)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(152)(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(484)
var ieee754 = __webpack_require__(483)
var isArray = __webpack_require__(482)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53)))
/***/ }),
/* 87 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(245);
var enumBugKeys = __webpack_require__(158);
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(489), __esModule: true };
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _assign = __webpack_require__(89);
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _assign2.default || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/***/ }),
/* 91 */
/***/ (function(module, exports) {
module.exports = {};
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var defined = __webpack_require__(51);
var fails = __webpack_require__(12);
var spaces = __webpack_require__(186);
var space = '[' + spaces + ']';
var non = '\u200b\u0085';
var ltrim = RegExp('^' + space + space + '*');
var rtrim = RegExp(space + space + '*$');
var exporter = function (KEY, exec, ALIAS) {
var exp = {};
var FORCE = fails(function () {
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if (ALIAS) exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function (string, TYPE) {
string = String(defined(string));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(42);
var TAG = __webpack_require__(16)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__(21).f;
var has = __webpack_require__(36);
var TAG = __webpack_require__(16)('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isMergeableObject = function isMergeableObject(value) {
return isNonNullObject(value)
&& !isSpecial(value)
};
function isNonNullObject(value) {
return !!value && typeof value === 'object'
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === '[object RegExp]'
|| stringValue === '[object Date]'
|| isReactElement(value)
}
// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {}
}
function cloneUnlessOtherwiseSpecified(value, options) {
return (options.clone !== false && options.isMergeableObject(value))
? deepmerge(emptyTarget(value), value, options)
: value
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function(element) {
return cloneUnlessOtherwiseSpecified(element, options)
})
}
function getMergeFunction(key, options) {
if (!options.customMerge) {
return deepmerge
}
var customMerge = options.customMerge(key);
return typeof customMerge === 'function' ? customMerge : deepmerge
}
function getEnumerableOwnPropertySymbols(target) {
return Object.getOwnPropertySymbols
? Object.getOwnPropertySymbols(target).filter(function(symbol) {
return target.propertyIsEnumerable(symbol)
})
: []
}
function getKeys(target) {
return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
}
function propertyIsOnObject(object, property) {
try {
return property in object
} catch(_) {
return false
}
}
// Protects from prototype poisoning and unexpected merging up the prototype chain.
function propertyIsUnsafe(target, key) {
return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) {
getKeys(target).forEach(function(key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
}
getKeys(source).forEach(function(key) {
if (propertyIsUnsafe(target, key)) {
return
}
if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
} else {
destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
}
});
return destination
}
function deepmerge(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
// implementations can use it. The caller may not replace it.
options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
var sourceIsArray = Array.isArray(source);
var targetIsArray = Array.isArray(target);
var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
if (!sourceAndTargetTypesMatch) {
return cloneUnlessOtherwiseSpecified(source, options)
} else if (sourceIsArray) {
return options.arrayMerge(target, source, options)
} else {
return mergeObject(target, source, options)
}
}
deepmerge.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error('first argument should be an array')
}
return array.reduce(function(prev, next) {
return deepmerge(prev, next, options)
}, {})
};
var deepmerge_1 = deepmerge;
module.exports = deepmerge_1;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _setPrototypeOf = __webpack_require__(356);
var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
var _create = __webpack_require__(352);
var _create2 = _interopRequireDefault(_create);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
}
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(358), __esModule: true };
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(367), __esModule: true };
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(56);
var call = __webpack_require__(230);
var isArrayIter = __webpack_require__(229);
var anObject = __webpack_require__(48);
var toLength = __webpack_require__(122);
var getIterFn = __webpack_require__(150);
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var length, step, iterator, result;
if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if (result === BREAK || result === RETURN) return result;
} else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
if (result === BREAK || result === RETURN) return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(421);
var global = __webpack_require__(26);
var hide = __webpack_require__(60);
var Iterators = __webpack_require__(84);
var TO_STRING_TAG = __webpack_require__(25)('toStringTag');
var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
'TextTrackList,TouchList').split(',');
for (var i = 0; i < DOMIterables.length; i++) {
var NAME = DOMIterables[i];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
var def = __webpack_require__(39).f;
var has = __webpack_require__(67);
var TAG = __webpack_require__(25)('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isPrefixedValue;
var regex = /-webkit-|-moz-|-ms-/;
function isPrefixedValue(value) {
return typeof value === 'string' && regex.test(value);
}
module.exports = exports['default'];
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.compose = exports.merge = exports.$ = exports.style = exports.presets = exports.keyframes = exports.fontFace = exports.insertGlobal = exports.insertRule = exports.plugins = exports.styleSheet = undefined;
exports.speedy = speedy;
exports.simulations = simulations;
exports.simulate = simulate;
exports.cssLabels = cssLabels;
exports.isLikeRule = isLikeRule;
exports.idFor = idFor;
exports.css = css;
exports.rehydrate = rehydrate;
exports.flush = flush;
exports.select = select;
exports.parent = parent;
exports.media = media;
exports.pseudo = pseudo;
exports.active = active;
exports.any = any;
exports.checked = checked;
exports.disabled = disabled;
exports.empty = empty;
exports.enabled = enabled;
exports._default = _default;
exports.first = first;
exports.firstChild = firstChild;
exports.firstOfType = firstOfType;
exports.fullscreen = fullscreen;
exports.focus = focus;
exports.hover = hover;
exports.indeterminate = indeterminate;
exports.inRange = inRange;
exports.invalid = invalid;
exports.lastChild = lastChild;
exports.lastOfType = lastOfType;
exports.left = left;
exports.link = link;
exports.onlyChild = onlyChild;
exports.onlyOfType = onlyOfType;
exports.optional = optional;
exports.outOfRange = outOfRange;
exports.readOnly = readOnly;
exports.readWrite = readWrite;
exports.required = required;
exports.right = right;
exports.root = root;
exports.scope = scope;
exports.target = target;
exports.valid = valid;
exports.visited = visited;
exports.dir = dir;
exports.lang = lang;
exports.not = not;
exports.nthChild = nthChild;
exports.nthLastChild = nthLastChild;
exports.nthLastOfType = nthLastOfType;
exports.nthOfType = nthOfType;
exports.after = after;
exports.before = before;
exports.firstLetter = firstLetter;
exports.firstLine = firstLine;
exports.selection = selection;
exports.backdrop = backdrop;
exports.placeholder = placeholder;
exports.cssFor = cssFor;
exports.attribsFor = attribsFor;
var _objectAssign = __webpack_require__(156);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _sheet = __webpack_require__(467);
var _CSSPropertyOperations = __webpack_require__(240);
var _clean = __webpack_require__(458);
var _clean2 = _interopRequireDefault(_clean);
var _plugins = __webpack_require__(457);
var _hash = __webpack_require__(440);
var _hash2 = _interopRequireDefault(_hash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/* stylesheet */
var styleSheet = exports.styleSheet = new _sheet.StyleSheet();
// an isomorphic StyleSheet shim. hides all the nitty gritty.
// /**************** LIFTOFF IN 3... 2... 1... ****************/
styleSheet.inject(); //eslint-disable-line indent
// /**************** TO THE MOOOOOOON ****************/
// convenience function to toggle speedy
function speedy(bool) {
return styleSheet.speedy(bool);
}
// plugins
// we include these by default
var plugins = exports.plugins = styleSheet.plugins = new _plugins.PluginSet([_plugins.prefixes, _plugins.contentWrap, _plugins.fallbacks]);
plugins.media = new _plugins.PluginSet(); // neat! media, font-face, keyframes
plugins.fontFace = new _plugins.PluginSet();
plugins.keyframes = new _plugins.PluginSet([_plugins.prefixes, _plugins.fallbacks]);
// define some constants
var isDev = "production" === 'development' || !"production";
var isTest = "production" === 'test';
var isBrowser = typeof window !== 'undefined';
/**** simulations ****/
// a flag to enable simulation meta tags on dom nodes
// defaults to true in dev mode. recommend *not* to
// toggle often.
var canSimulate = isDev;
// we use these flags for issuing warnings when simulate is called
// in prod / in incorrect order
var warned1 = false,
warned2 = false;
// toggles simulation activity. shouldn't be needed in most cases
function simulations() {
var bool = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
canSimulate = !!bool;
}
// use this on dom nodes to 'simulate' pseudoclasses
// <div {...hover({ color: 'red' })} {...simulate('hover', 'visited')}>...</div>
// you can even send in some weird ones, as long as it's in simple format
// and matches an existing rule on the element
// eg simulate('nthChild2', ':hover:active') etc
function simulate() {
for (var _len = arguments.length, pseudos = Array(_len), _key = 0; _key < _len; _key++) {
pseudos[_key] = arguments[_key];
}
pseudos = (0, _clean2.default)(pseudos);
if (!pseudos) return {};
if (!canSimulate) {
if (!warned1) {
console.warn('can\'t simulate without once calling simulations(true)'); //eslint-disable-line no-console
warned1 = true;
}
if (!isDev && !isTest && !warned2) {
console.warn('don\'t use simulation outside dev'); //eslint-disable-line no-console
warned2 = true;
}
return {};
}
return pseudos.reduce(function (o, p) {
return o['data-simulate-' + simple(p)] = '', o;
}, {});
}
/**** labels ****/
// toggle for debug labels.
// *shouldn't* have to mess with this manually
var hasLabels = isDev;
function cssLabels(bool) {
hasLabels = !!bool;
}
// takes a string, converts to lowercase, strips out nonalphanumeric.
function simple(str) {
var char = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return str.toLowerCase().replace(/[^a-z0-9]/g, char);
}
// hashes a string to something 'unique'
// we use this to generate ids for styles
function hashify(obj) {
var str = JSON.stringify(obj);
var toRet = (0, _hash2.default)(str).toString(36);
if (obj.label && obj.label.length > 0 && isDev) {
return simple(obj.label.join('.'), '-') + '-' + toRet;
}
return toRet;
}
// of shape { 'data-css-<id>': '' }
function isLikeRule(rule) {
var keys = Object.keys(rule).filter(function (x) {
return x !== 'toString';
});
if (keys.length !== 1) {
return false;
}
return !!/data\-css\-([a-zA-Z0-9\-_]+)/.exec(keys[0]);
}
// extracts id from a { 'data-css-<id>': ''} like object
function idFor(rule) {
var keys = Object.keys(rule).filter(function (x) {
return x !== 'toString';
});
if (keys.length !== 1) throw new Error('not a rule');
var regex = /data\-css\-([a-zA-Z0-9\-_]+)/;
var match = regex.exec(keys[0]);
if (!match) throw new Error('not a rule');
return match[1];
}
// from https://github.com/j2css/j2c/blob/5d381c2d721d04b54fabe6a165d587247c3087cb/src/helpers.js#L28-L61
// "Tokenizes" the selectors into parts relevant for the next function.
// Strings and comments are matched, but ignored afterwards.
// This is not a full tokenizers. It only recognizes comas, parentheses,
// strings and comments.
// regexp generated by scripts/regexps.js then trimmed by hand
var selectorTokenizer = /[(),]|"(?:\\.|[^"\n])*"|'(?:\\.|[^'\n])*'|\/\*[\s\S]*?\*\//g;
/**
* This will split a coma-separated selector list into individual selectors,
* ignoring comas in strings, comments and in :pseudo-selectors(parameter, lists).
*
* @param {string} selector
* @return {string[]}
*/
function splitSelector(selector) {
if (selector.indexOf(',') === -1) {
return [selector];
}
var indices = [],
res = [],
inParen = 0,
o;
/*eslint-disable no-cond-assign*/
while (o = selectorTokenizer.exec(selector)) {
/*eslint-enable no-cond-assign*/
switch (o[0]) {
case '(':
inParen++;break;
case ')':
inParen--;break;
case ',':
if (inParen) break;indices.push(o.index);
}
}
for (o = indices.length; o--;) {
res.unshift(selector.slice(indices[o] + 1));
selector = selector.slice(0, indices[o]);
}
res.unshift(selector);
return res;
}
function selector(id, path) {
if (!id) {
return path.replace(/\&/g, '');
}
if (!path) return '.css-' + id + ',[data-css-' + id + ']';
var x = splitSelector(path).map(function (x) {
return x.indexOf('&') >= 0 ? [x.replace(/\&/mg, '.css-' + id), x.replace(/\&/mg, '[data-css-' + id + ']')].join(',') // todo - make sure each sub selector has an &
: '.css-' + id + x + ',[data-css-' + id + ']' + x;
}).join(',');
if (canSimulate && /^\&\:/.exec(path) && !/\s/.exec(path)) {
x += ',.css-' + id + '[data-simulate-' + simple(path) + '],[data-css-' + id + '][data-simulate-' + simple(path) + ']';
}
return x;
}
// end https://github.com/j2css/j2c/blob/5d381c2d721d04b54fabe6a165d587247c3087cb/src/helpers.js#L28-L61
function toCSS(_ref) {
var selector = _ref.selector,
style = _ref.style;
var result = plugins.transform({ selector: selector, style: style });
return result.selector + '{' + (0, _CSSPropertyOperations.createMarkupForStyles)(result.style) + '}';
}
function deconstruct(style) {
// we can be sure it's not infinitely nested here
var plain = void 0,
selects = void 0,
medias = void 0,
supports = void 0;
Object.keys(style).forEach(function (key) {
if (key.indexOf('&') >= 0) {
selects = selects || {};
selects[key] = style[key];
} else if (key.indexOf('@media') === 0) {
medias = medias || {};
medias[key] = deconstruct(style[key]);
} else if (key.indexOf('@supports') === 0) {
supports = supports || {};
supports[key] = deconstruct(style[key]);
} else if (key === 'label') {
if (style.label.length > 0) {
plain = plain || {};
plain.label = hasLabels ? style.label.join('.') : '';
}
} else {
plain = plain || {};
plain[key] = style[key];
}
});
return { plain: plain, selects: selects, medias: medias, supports: supports };
}
function deconstructedStyleToCSS(id, style) {
var css = [];
// plugins here
var plain = style.plain,
selects = style.selects,
medias = style.medias,
supports = style.supports;
if (plain) {
css.push(toCSS({ style: plain, selector: selector(id) }));
}
if (selects) {
Object.keys(selects).forEach(function (key) {
return css.push(toCSS({ style: selects[key], selector: selector(id, key) }));
});
}
if (medias) {
Object.keys(medias).forEach(function (key) {
return css.push(key + '{' + deconstructedStyleToCSS(id, medias[key]).join('') + '}');
});
}
if (supports) {
Object.keys(supports).forEach(function (key) {
return css.push(key + '{' + deconstructedStyleToCSS(id, supports[key]).join('') + '}');
});
}
return css;
}
// this cache to track which rules have
// been inserted into the stylesheet
var inserted = styleSheet.inserted = {};
// and helpers to insert rules into said styleSheet
function insert(spec) {
if (!inserted[spec.id]) {
inserted[spec.id] = true;
var deconstructed = deconstruct(spec.style);
var rules = deconstructedStyleToCSS(spec.id, deconstructed);
inserted[spec.id] = isBrowser ? true : rules;
rules.forEach(function (cssRule) {
return styleSheet.insert(cssRule);
});
}
}
// a simple cache to store generated rules
var registered = styleSheet.registered = {};
function register(spec) {
if (!registered[spec.id]) {
registered[spec.id] = spec;
}
}
function _getRegistered(rule) {
if (isLikeRule(rule)) {
var ret = registered[idFor(rule)];
if (ret == null) {
throw new Error('[glamor] an unexpected rule cache miss occurred. This is probably a sign of multiple glamor instances in your app. See https://github.com/threepointone/glamor/issues/79');
}
return ret;
}
return rule;
}
// todo - perf
var ruleCache = {};
function toRule(spec) {
register(spec);
insert(spec);
if (ruleCache[spec.id]) {
return ruleCache[spec.id];
}
var ret = _defineProperty({}, 'data-css-' + spec.id, hasLabels ? spec.label || '' : '');
Object.defineProperty(ret, 'toString', {
enumerable: false, value: function value() {
return 'css-' + spec.id;
}
});
ruleCache[spec.id] = ret;
return ret;
}
function log() {
//eslint-disable-line no-unused-vars
console.log(this); //eslint-disable-line no-console
return this;
}
function isSelector(key) {
var possibles = [':', '.', '[', '>', ' '],
found = false,
ch = key.charAt(0);
for (var i = 0; i < possibles.length; i++) {
if (ch === possibles[i]) {
found = true;
break;
}
}
return found || key.indexOf('&') >= 0;
}
function joinSelectors(a, b) {
var as = splitSelector(a).map(function (a) {
return !(a.indexOf('&') >= 0) ? '&' + a : a;
});
var bs = splitSelector(b).map(function (b) {
return !(b.indexOf('&') >= 0) ? '&' + b : b;
});
return bs.reduce(function (arr, b) {
return arr.concat(as.map(function (a) {
return b.replace(/\&/g, a);
}));
}, []).join(',');
}
function joinMediaQueries(a, b) {
return a ? '@media ' + a.substring(6) + ' and ' + b.substring(6) : b;
}
function isMediaQuery(key) {
return key.indexOf('@media') === 0;
}
function isSupports(key) {
return key.indexOf('@supports') === 0;
}
function joinSupports(a, b) {
return a ? '@supports ' + a.substring(9) + ' and ' + b.substring(9) : b;
}
// flatten a nested array
function flatten(inArr) {
var arr = [];
for (var i = 0; i < inArr.length; i++) {
if (Array.isArray(inArr[i])) arr = arr.concat(flatten(inArr[i]));else arr = arr.concat(inArr[i]);
}
return arr;
}
var prefixedPseudoSelectors = {
'::placeholder': ['::-webkit-input-placeholder', '::-moz-placeholder', '::-ms-input-placeholder'],
':fullscreen': [':-webkit-full-screen', ':-moz-full-screen', ':-ms-fullscreen']
// mutable! modifies dest.
};function build(dest, _ref2) {
var _ref2$selector = _ref2.selector,
selector = _ref2$selector === undefined ? '' : _ref2$selector,
_ref2$mq = _ref2.mq,
mq = _ref2$mq === undefined ? '' : _ref2$mq,
_ref2$supp = _ref2.supp,
supp = _ref2$supp === undefined ? '' : _ref2$supp,
_ref2$src = _ref2.src,
src = _ref2$src === undefined ? {} : _ref2$src;
if (!Array.isArray(src)) {
src = [src];
}
src = flatten(src);
src.forEach(function (_src) {
if (isLikeRule(_src)) {
var reg = _getRegistered(_src);
if (reg.type !== 'css') {
throw new Error('cannot merge this rule');
}
_src = reg.style;
}
_src = (0, _clean2.default)(_src);
if (_src && _src.composes) {
build(dest, { selector: selector, mq: mq, supp: supp, src: _src.composes });
}
Object.keys(_src || {}).forEach(function (key) {
if (isSelector(key)) {
if (prefixedPseudoSelectors[key]) {
prefixedPseudoSelectors[key].forEach(function (p) {
return build(dest, { selector: joinSelectors(selector, p), mq: mq, supp: supp, src: _src[key] });
});
}
build(dest, { selector: joinSelectors(selector, key), mq: mq, supp: supp, src: _src[key] });
} else if (isMediaQuery(key)) {
build(dest, { selector: selector, mq: joinMediaQueries(mq, key), supp: supp, src: _src[key] });
} else if (isSupports(key)) {
build(dest, { selector: selector, mq: mq, supp: joinSupports(supp, key), src: _src[key] });
} else if (key === 'composes') {
// ignore, we already dealth with it
} else {
var _dest = dest;
if (supp) {
_dest[supp] = _dest[supp] || {};
_dest = _dest[supp];
}
if (mq) {
_dest[mq] = _dest[mq] || {};
_dest = _dest[mq];
}
if (selector) {
_dest[selector] = _dest[selector] || {};
_dest = _dest[selector];
}
if (key === 'label') {
if (hasLabels) {
dest.label = dest.label.concat(_src.label);
}
} else {
_dest[key] = _src[key];
}
}
});
});
}
function _css(rules) {
var style = { label: [] };
build(style, { src: rules }); // mutative! but worth it.
var spec = {
id: hashify(style),
style: style, label: hasLabels ? style.label.join('.') : '',
type: 'css'
};
return toRule(spec);
}
var nullrule = {
// 'data-css-nil': ''
};
Object.defineProperty(nullrule, 'toString', {
enumerable: false, value: function value() {
return 'css-nil';
}
});
var inputCaches = typeof WeakMap !== 'undefined' ? [nullrule, new WeakMap(), new WeakMap(), new WeakMap()] : [nullrule];
var warnedWeakMapError = false;
function multiIndexCache(fn) {
return function (args) {
if (inputCaches[args.length]) {
var coi = inputCaches[args.length];
var ctr = 0;
while (ctr < args.length - 1) {
if (!coi.has(args[ctr])) {
coi.set(args[ctr], new WeakMap());
}
coi = coi.get(args[ctr]);
ctr++;
}
if (coi.has(args[args.length - 1])) {
var ret = coi.get(args[ctr]);
if (registered[ret.toString().substring(4)]) {
// make sure it hasn't been flushed
return ret;
}
}
}
var value = fn(args);
if (inputCaches[args.length]) {
var _ctr = 0,
_coi = inputCaches[args.length];
while (_ctr < args.length - 1) {
_coi = _coi.get(args[_ctr]);
_ctr++;
}
try {
_coi.set(args[_ctr], value);
} catch (err) {
if (isDev && !warnedWeakMapError) {
var _console;
warnedWeakMapError = true;
(_console = console).warn.apply(_console, ['failed setting the WeakMap cache for args:'].concat(_toConsumableArray(args))); // eslint-disable-line no-console
console.warn('this should NOT happen, please file a bug on the github repo.'); // eslint-disable-line no-console
}
}
}
return value;
};
}
var cachedCss = typeof WeakMap !== 'undefined' ? multiIndexCache(_css) : _css;
function css() {
for (var _len2 = arguments.length, rules = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
rules[_key2] = arguments[_key2];
}
if (rules[0] && rules[0].length && rules[0].raw) {
throw new Error('you forgot to include glamor/babel in your babel plugins.');
}
rules = (0, _clean2.default)(rules);
if (!rules) {
return nullrule;
}
return cachedCss(rules);
}
css.insert = function (css) {
var spec = {
id: hashify(css),
css: css,
type: 'raw'
};
register(spec);
if (!inserted[spec.id]) {
styleSheet.insert(spec.css);
inserted[spec.id] = isBrowser ? true : [spec.css];
}
};
var insertRule = exports.insertRule = css.insert;
css.global = function (selector, style) {
style = (0, _clean2.default)(style);
if (style) {
return css.insert(toCSS({ selector: selector, style: style }));
}
};
var insertGlobal = exports.insertGlobal = css.global;
function insertKeyframe(spec) {
if (!inserted[spec.id]) {
var inner = Object.keys(spec.keyframes).map(function (kf) {
var result = plugins.keyframes.transform({ id: spec.id, name: kf, style: spec.keyframes[kf] });
return result.name + '{' + (0, _CSSPropertyOperations.createMarkupForStyles)(result.style) + '}';
}).join('');
var rules = ['-webkit-', '-moz-', '-o-', ''].map(function (prefix) {
return '@' + prefix + 'keyframes ' + (spec.name + '_' + spec.id) + '{' + inner + '}';
});
rules.forEach(function (rule) {
return styleSheet.insert(rule);
});
inserted[spec.id] = isBrowser ? true : rules;
}
}
css.keyframes = function (name, kfs) {
if (!kfs) {
kfs = name, name = 'animation';
}
// do not ignore empty keyframe definitions for now.
kfs = (0, _clean2.default)(kfs) || {};
var spec = {
id: hashify({ name: name, kfs: kfs }),
type: 'keyframes',
name: name,
keyframes: kfs
};
register(spec);
insertKeyframe(spec);
return name + '_' + spec.id;
};
// we don't go all out for fonts as much, giving a simple font loading strategy
// use a fancier lib if you need moar power
css.fontFace = function (font) {
font = (0, _clean2.default)(font);
var spec = {
id: hashify(font),
type: 'font-face',
font: font
};
register(spec);
insertFontFace(spec);
return font.fontFamily;
};
var fontFace = exports.fontFace = css.fontFace;
var keyframes = exports.keyframes = css.keyframes;
function insertFontFace(spec) {
if (!inserted[spec.id]) {
var rule = '@font-face{' + (0, _CSSPropertyOperations.createMarkupForStyles)(spec.font) + '}';
styleSheet.insert(rule);
inserted[spec.id] = isBrowser ? true : [rule];
}
}
// rehydrate the insertion cache with ids sent from
// renderStatic / renderStaticOptimized
function rehydrate(ids) {
// load up ids
(0, _objectAssign2.default)(inserted, ids.reduce(function (o, i) {
return o[i] = true, o;
}, {}));
// assume css loaded separately
}
// clears out the cache and empties the stylesheet
// best for tests, though there might be some value for SSR.
function flush() {
inserted = styleSheet.inserted = {};
registered = styleSheet.registered = {};
ruleCache = {};
styleSheet.flush();
styleSheet.inject();
}
var presets = exports.presets = {
mobile: '(min-width: 400px)',
Mobile: '@media (min-width: 400px)',
phablet: '(min-width: 550px)',
Phablet: '@media (min-width: 550px)',
tablet: '(min-width: 750px)',
Tablet: '@media (min-width: 750px)',
desktop: '(min-width: 1000px)',
Desktop: '@media (min-width: 1000px)',
hd: '(min-width: 1200px)',
Hd: '@media (min-width: 1200px)'
};
var style = exports.style = css;
function select(selector) {
for (var _len3 = arguments.length, styles = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
styles[_key3 - 1] = arguments[_key3];
}
if (!selector) {
return style(styles);
}
return css(_defineProperty({}, selector, styles));
}
var $ = exports.$ = select;
function parent(selector) {
for (var _len4 = arguments.length, styles = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
styles[_key4 - 1] = arguments[_key4];
}
return css(_defineProperty({}, selector + ' &', styles));
}
var merge = exports.merge = css;
var compose = exports.compose = css;
function media(query) {
for (var _len5 = arguments.length, rules = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
rules[_key5 - 1] = arguments[_key5];
}
return css(_defineProperty({}, '@media ' + query, rules));
}
function pseudo(selector) {
for (var _len6 = arguments.length, styles = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) {
styles[_key6 - 1] = arguments[_key6];
}
return css(_defineProperty({}, selector, styles));
}
// allllll the pseudoclasses
function active(x) {
return pseudo(':active', x);
}
function any(x) {
return pseudo(':any', x);
}
function checked(x) {
return pseudo(':checked', x);
}
function disabled(x) {
return pseudo(':disabled', x);
}
function empty(x) {
return pseudo(':empty', x);
}
function enabled(x) {
return pseudo(':enabled', x);
}
function _default(x) {
return pseudo(':default', x); // note '_default' name
}
function first(x) {
return pseudo(':first', x);
}
function firstChild(x) {
return pseudo(':first-child', x);
}
function firstOfType(x) {
return pseudo(':first-of-type', x);
}
function fullscreen(x) {
return pseudo(':fullscreen', x);
}
function focus(x) {
return pseudo(':focus', x);
}
function hover(x) {
return pseudo(':hover', x);
}
function indeterminate(x) {
return pseudo(':indeterminate', x);
}
function inRange(x) {
return pseudo(':in-range', x);
}
function invalid(x) {
return pseudo(':invalid', x);
}
function lastChild(x) {
return pseudo(':last-child', x);
}
function lastOfType(x) {
return pseudo(':last-of-type', x);
}
function left(x) {
return pseudo(':left', x);
}
function link(x) {
return pseudo(':link', x);
}
function onlyChild(x) {
return pseudo(':only-child', x);
}
function onlyOfType(x) {
return pseudo(':only-of-type', x);
}
function optional(x) {
return pseudo(':optional', x);
}
function outOfRange(x) {
return pseudo(':out-of-range', x);
}
function readOnly(x) {
return pseudo(':read-only', x);
}
function readWrite(x) {
return pseudo(':read-write', x);
}
function required(x) {
return pseudo(':required', x);
}
function right(x) {
return pseudo(':right', x);
}
function root(x) {
return pseudo(':root', x);
}
function scope(x) {
return pseudo(':scope', x);
}
function target(x) {
return pseudo(':target', x);
}
function valid(x) {
return pseudo(':valid', x);
}
function visited(x) {
return pseudo(':visited', x);
}
// parameterized pseudoclasses
function dir(p, x) {
return pseudo(':dir(' + p + ')', x);
}
function lang(p, x) {
return pseudo(':lang(' + p + ')', x);
}
function not(p, x) {
// should this be a plugin?
var selector = p.split(',').map(function (x) {
return x.trim();
}).map(function (x) {
return ':not(' + x + ')';
});
if (selector.length === 1) {
return pseudo(':not(' + p + ')', x);
}
return select(selector.join(''), x);
}
function nthChild(p, x) {
return pseudo(':nth-child(' + p + ')', x);
}
function nthLastChild(p, x) {
return pseudo(':nth-last-child(' + p + ')', x);
}
function nthLastOfType(p, x) {
return pseudo(':nth-last-of-type(' + p + ')', x);
}
function nthOfType(p, x) {
return pseudo(':nth-of-type(' + p + ')', x);
}
// pseudoelements
function after(x) {
return pseudo('::after', x);
}
function before(x) {
return pseudo('::before', x);
}
function firstLetter(x) {
return pseudo('::first-letter', x);
}
function firstLine(x) {
return pseudo('::first-line', x);
}
function selection(x) {
return pseudo('::selection', x);
}
function backdrop(x) {
return pseudo('::backdrop', x);
}
function placeholder(x) {
// https://github.com/threepointone/glamor/issues/14
return css({ '::placeholder': x });
}
/*** helpers for web components ***/
// https://github.com/threepointone/glamor/issues/16
function cssFor() {
for (var _len7 = arguments.length, rules = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
rules[_key7] = arguments[_key7];
}
rules = (0, _clean2.default)(rules);
return rules ? rules.map(function (r) {
var style = { label: [] };
build(style, { src: r }); // mutative! but worth it.
return deconstructedStyleToCSS(hashify(style), deconstruct(style)).join('');
}).join('') : '';
}
function attribsFor() {
for (var _len8 = arguments.length, rules = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
rules[_key8] = arguments[_key8];
}
rules = (0, _clean2.default)(rules);
var htmlAttributes = rules ? rules.map(function (rule) {
idFor(rule); // throwaway check for rule
var key = Object.keys(rule)[0],
value = rule[key];
return key + '="' + (value || '') + '"';
}).join(' ') : '';
return htmlAttributes;
}
/***/ }),
/* 105 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 106 */
/***/ (function(module, exports) {
module.exports = true;
/***/ }),
/* 107 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
/***/ }),
/* 108 */
/***/ (function(module, exports) {
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
/***/ }),
/* 109 */
/***/ (function(module, exports) {
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(6);
var aFunction = __webpack_require__(27);
var SPECIES = __webpack_require__(16)('species');
module.exports = function (O, D) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(6);
module.exports = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
/***/ }),
/* 112 */
/***/ (function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(42);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__(44);
var global = __webpack_require__(11);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__(63) ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loadFile = exports.saveBlob = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var saveBlob = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(data, name, type) {
var link, blob;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
link = document.createElement('a');
link.style.display = 'none';
document.body.appendChild(link);
blob = new Blob([data], { type: type });
link.href = URL.createObjectURL(blob);
link.download = name;
link.click();
case 7:
case 'end':
return _context.stop();
}
}
}, _callee, undefined);
}));
return function saveBlob(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}(); // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var loadFile = function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(path, callback) {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt('return', _axios2.default.get(path).then(function (response) {
return response.data;
}).then(function (json) {
if (callback) {
callback(null, json);
}
return json;
}).catch(function (error) {
if (callback) {
callback(error);
}
console.error('There has been a problem loading the file: ' + error.message);
throw error;
}));
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, undefined);
}));
return function loadFile(_x4, _x5) {
return _ref2.apply(this, arguments);
};
}();
exports.saveBlob = saveBlob;
exports.loadFile = loadFile;
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(107);
var TAG = __webpack_require__(25)('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(48);
var dPs = __webpack_require__(422);
var enumBugKeys = __webpack_require__(158);
var IE_PROTO = __webpack_require__(160)('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(165)('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
__webpack_require__(233).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
const d3_format_1 = __webpack_require__(45);
const d3_selection_1 = __webpack_require__(289);
const glamor_1 = __webpack_require__(104);
const render_utils_1 = __webpack_require__(37);
/**
* Renders a table
*
* ```js
* const headers = [
* 'Col 1',
* 'Col 2',
* 'Col 3',
* ];
*
* const values = [
* [1, 2, 3],
* ['4', '5', '6'],
* ['strong>7</strong>', true, false],
* ];
*
* const surface = { name: 'Table', tab: 'Charts' };
* tfvis.render.table(surface, { headers, values });
* ```
*
* @param opts.fontSize fontSize in pixels for text in the chart.
*
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function table(container,
// tslint:disable-next-line:no-any
data, opts = {}) {
if (data && data.headers == null) {
throw new Error('Data to render must have a "headers" property');
}
if (data && data.values == null) {
throw new Error('Data to render must have a "values" property');
}
const drawArea = render_utils_1.getDrawArea(container);
const options = Object.assign({}, defaultOpts, opts);
let table = d3_selection_1.select(drawArea).select('table.tf-table');
const tableStyle = glamor_1.css({
fontSize: options.fontSize || '.875rem',
width: '100%',
maxWidth: '64rem',
marginRight: 'auto',
marginLeft: 'auto',
});
// If a table is not already present on this element add one
if (table.size() === 0) {
table = d3_selection_1.select(drawArea).append('table');
table.attr('class', ` ${tableStyle} tf-table`);
table.append('thead').append('tr');
table.append('tbody');
}
if (table.size() !== 1) {
throw new Error('Error inserting table');
}
//
// Add the reader row
//
const headerRowStyle = glamor_1.css({
fontWeight: '600',
borderBottomStyle: 'solid',
borderBottomWidth: '1px',
borderColor: 'rgba( 0, 0, 0, .2 )',
textAlign: 'left',
paddingBottom: '1rem',
paddingRight: '1rem',
backgroundColor: '#fff',
});
const headers = table.select('thead').select('tr').selectAll('th').data(data.headers);
const headersEnter = headers.enter().append('th').attr('class', `${headerRowStyle}`);
headers.merge(headersEnter).html(d => d);
headers.exit().remove();
//
// Add the data rows
//
const format = d3_format_1.format(',.4~f');
const rows = table.select('tbody').selectAll('tr').data(data.values);
const rowsEnter = rows.enter().append('tr');
// Nested selection to add individual cells
const cellStyle = glamor_1.css({
padding: '0.25rem',
borderBottomStyle: 'solid',
borderBottomWidth: '1px',
borderColor: 'rgba( 0, 0, 0, .2 )',
});
const cells = rows.merge(rowsEnter).selectAll('td').data(d => d);
const cellsEnter = cells.enter().append('td').attr('class', `${cellStyle}`);
cells.merge(cellsEnter).html(d => typeof d === 'number' ? format(d) : d);
cells.exit().remove();
rows.exit().remove();
}
exports.table = table;
const defaultOpts = {
fontSize: 14,
};
//# sourceMappingURL=table.js.map
/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const tfjs_1 = __webpack_require__(4);
const utils_1 = __webpack_require__(120);
/**
* Returns summary statistics for an array of numbers
*
* @param input
*/
function arrayStats(input) {
if (!Array.isArray(input)) {
throw new Error('input must be an array');
}
if (input.length === 0) {
return {
numVals: 0,
numNans: 0,
numZeros: 0,
max: undefined,
min: undefined,
};
}
const numVals = input.length;
let max = -Infinity;
let min = Infinity;
let numZeros = 0;
let numNans = 0;
let numInfs = 0;
for (let i = 0; i < numVals; i++) {
const curr = input[i];
if (curr > max) {
max = curr;
}
if (curr < min) {
min = curr;
}
if (curr === 0) {
numZeros += 1;
}
if (isNaN(curr)) {
numNans += 1;
}
else if (!isFinite(curr)) {
// Make sure NaNs are not double counted as Infs
numInfs += 1;
}
}
const result = {
numVals,
numZeros,
numNans,
max,
min,
numInfs,
};
// Handle all NaN input
if (result.max === -Infinity) {
result.max = NaN;
}
if (result.min === Infinity) {
result.min = NaN;
}
return result;
}
exports.arrayStats = arrayStats;
/**
* Returns summary statistics for a numeric tensor. *
*
* @param input
*/
function tensorStats(input) {
return __awaiter(this, void 0, void 0, function* () {
// TODO. Benchmark this and consider having one of the *stats functions
// delegate to the other.
const [min, max, numZeros] = tfjs_1.tidy(() => {
const zero = tfjs_1.scalar(0, input.dtype);
const min = input.min();
const max = input.max();
const numZeros = input.equal(zero).sum();
return [min, max, numZeros];
});
return Promise
.all([input.data(), min.data(), max.data(), numZeros.data()])
.then(([tensorVal, minVal, maxVal, numZerosVal]) => {
// We currently need to count NaNs on CPU.
const numVals = tensorVal.length;
let numNans = 0;
let numInfs = 0;
for (let i = 0; i < numVals; i++) {
const curr = tensorVal[i];
if (isNaN(curr)) {
numNans += 1;
}
else if (!isFinite(curr)) {
// Make sure NaNs are not double counted as Infs
numInfs += 1;
}
}
let trueMin = minVal[0];
let trueMax = maxVal[0];
if (numNans === numVals) {
// on gpu the min and max won't be accurate if all values are NaN
trueMin = NaN;
trueMax = NaN;
}
const stats = {
numVals,
numZeros: numZerosVal[0],
numNans,
min: trueMin,
max: trueMax,
numInfs,
};
return stats;
});
});
}
exports.tensorStats = tensorStats;
/**
* Computes a confusion matrix from predictions and labels. Each value in
* labels and predictions should correspond to some output class. It is assumed
* that these values go from 0 to numClasses - 1.
*
* ```js
* const labels = tf.tensor1d([1, 2, 4]);
* const predictions = tf.tensor1d([2, 2, 4]);
* const result = await tfvis.metrics.confusionMatrix(labels, predictions);
* console.log(JSON.stringify(result, null, 2))
* ```
*
* @param labels 1D tensor of true values
* @param predictions 1D tensor of predicted values
* @param numClasses Number of distinct classes. Optional. If not passed in
* numClasses will equal the highest number in either labels or predictions
* plus 1
* @param weights 1d tensor that is the same size as predictions.
* If weights is passed in then each prediction contributes its corresponding
* weight to the total value of the confusion matrix cell.
*
*/
/**
* @doc {heading: 'Metrics', namespace: 'metrics'}
*/
function confusionMatrix(labels, predictions, numClasses, weights) {
return __awaiter(this, void 0, void 0, function* () {
utils_1.assert(labels.rank === 1, 'labels must be a 1D tensor');
utils_1.assert(predictions.rank === 1, 'predictions must be a 1D tensor');
utils_1.assert(labels.size === predictions.size, 'labels and predictions must be the same length');
if (weights != null) {
utils_1.assert(weights.size === predictions.size, 'labels and predictions must be the same length');
}
// Cast to int in case the caller didn't
const labelsInt = labels.cast('int32');
const predictionsInt = predictions.cast('int32');
if (numClasses == null) {
numClasses =
tfjs_1.tidy(() => {
const max = tfjs_1.maximum(labelsInt.max(), predictionsInt.max()).cast('int32');
return max.dataSync()[0] + 1;
});
}
let weightsPromise = Promise.resolve(null);
if (weights != null) {
weightsPromise = weights.data();
}
return Promise.all([labelsInt.data(), predictionsInt.data(), weightsPromise])
.then(([labelsArray, predsArray, weightsArray]) => {
const result = Array(numClasses).fill(0);
// Initialize the matrix
for (let i = 0; i < numClasses; i++) {
result[i] = Array(numClasses).fill(0);
}
for (let i = 0; i < labelsArray.length; i++) {
const label = labelsArray[i];
const pred = predsArray[i];
if (weightsArray != null) {
result[label][pred] += weightsArray[i];
}
else {
result[label][pred] += 1;
}
}
return result;
});
});
}
exports.confusionMatrix = confusionMatrix;
/**
* Computes how often predictions matches labels
*
* ```js
* const labels = tf.tensor1d([0, 0, 1, 2, 2, 2]);
* const predictions = tf.tensor1d([0, 0, 0, 2, 1, 1]);
*
* const result = await tfvis.metrics.accuracy(labels, predictions);
* console.log(result)
* ```
*
* @param labels tensor of true values
* @param predictions tensor of predicted values
*/
/**
* @doc {heading: 'Metrics', namespace: 'metrics'}
*/
function accuracy(labels, predictions) {
return __awaiter(this, void 0, void 0, function* () {
utils_1.assertShapesMatch(labels.shape, predictions.shape, 'Error computing accuracy.');
const eq = labels.equal(predictions);
const mean = eq.mean();
const acc = (yield mean.data())[0];
tfjs_1.dispose([eq, mean]);
return acc;
});
}
exports.accuracy = accuracy;
/**
* Computes per class accuracy between prediction and labels. Each value in
* labels and predictions should correspond to some output class. It is assumed
* that these values go from 0 to numClasses - 1.
*
* ```js
* const labels = tf.tensor1d([0, 0, 1, 2, 2, 2]);
* const predictions = tf.tensor1d([0, 0, 0, 2, 1, 1]);
*
* const result = await tfvis.metrics.perClassAccuracy(labels, predictions);
* console.log(JSON.stringify(result, null, 2))
* ```
*
* Returns an array of objects that each have an an `accuracy` and a `count`
* property for each class.
*
*
* @param labels 1D tensor of true values
* @param predictions 1D tensor of predicted values
* @param numClasses Number of distinct classes. Optional. If not passed in
* numClasses will equal the highest number in either labels or predictions
* plus 1
*/
/**
* @doc {heading: 'Metrics', namespace: 'metrics'}
*/
function perClassAccuracy(labels, predictions, numClasses) {
return __awaiter(this, void 0, void 0, function* () {
utils_1.assert(labels.rank === 1, 'labels must be a 1D tensor');
utils_1.assert(predictions.rank === 1, 'predictions must be a 1D tensor');
utils_1.assert(labels.size === predictions.size, 'labels and predictions must be the same length');
if (numClasses == null) {
numClasses = tfjs_1.tidy(() => {
return tfjs_1.maximum(labels.max(), predictions.max()).dataSync()[0] + 1;
});
}
return Promise.all([labels.data(), predictions.data()])
.then(([labelsArray, predsArray]) => {
// Per class total counts
const counts = Array(numClasses).fill(0);
// Per class accuracy
const accuracy = Array(numClasses).fill(0);
for (let i = 0; i < labelsArray.length; i++) {
const label = labelsArray[i];
const pred = predsArray[i];
counts[label] += 1;
if (label === pred) {
accuracy[label] += 1;
}
}
const results = [];
for (let i = 0; i < counts.length; i++) {
results.push({
count: counts[i],
accuracy: counts[i] === 0 ? 0 : accuracy[i] / counts[i],
});
}
return results;
});
});
}
exports.perClassAccuracy = perClassAccuracy;
//# sourceMappingURL=math.js.map
/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*
* @license
* Copyright 2018 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.
* =============================================================================
*/
/**
* Tests a boolean expression and throws a message if false.
*/
function assert(expr, msg) {
if (!expr) {
throw new Error(typeof msg === 'string' ? msg : msg());
}
}
exports.assert = assert;
function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = '') {
assert(arraysEqual(shapeA, shapeB), errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);
}
exports.assertShapesMatch = assertShapesMatch;
function arraysEqual(n1, n2) {
if (n1.length !== n2.length) {
return false;
}
for (let i = 0; i < n1.length; i++) {
if (n1[i] !== n2[i]) {
return false;
}
}
return true;
}
exports.arraysEqual = arraysEqual;
// Number of decimal places to when checking float similarity
exports.DECIMAL_PLACES_TO_CHECK = 4;
//# sourceMappingURL=utils.js.map
/***/ }),
/* 121 */
/***/ (function(module, exports) {
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(161);
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(5);
var aFunction = __webpack_require__(27);
var ctx = __webpack_require__(43);
var forOf = __webpack_require__(71);
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
var mapFn = arguments[1];
var mapping, A, n, cb;
aFunction(this);
mapping = mapFn !== undefined;
if (mapping) aFunction(mapFn);
if (source == undefined) return new this();
A = [];
if (mapping) {
n = 0;
cb = ctx(mapFn, arguments[2], 2);
forOf(source, false, function (nextItem) {
A.push(cb(nextItem, n++));
});
} else {
forOf(source, false, A.push, A);
}
return new this(A);
} });
};
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(5);
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { of: function of() {
var length = arguments.length;
var A = new Array(length);
while (length--) A[length] = arguments[length];
return new this(A);
} });
};
/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Forced replacement prototype accessors methods
module.exports = __webpack_require__(63) || !__webpack_require__(12)(function () {
var K = Math.random();
// In FF throws only define methods
// eslint-disable-next-line no-undef, no-useless-call
__defineSetter__.call(null, K, function () { /* empty */ });
delete __webpack_require__(11)[K];
});
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var hide = __webpack_require__(31);
var uid = __webpack_require__(78);
var TYPED = uid('typed_array');
var VIEW = uid('view');
var ABV = !!(global.ArrayBuffer && global.DataView);
var CONSTR = ABV;
var i = 0;
var l = 9;
var Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while (i < l) {
if (Typed = global[TypedArrayConstructors[i++]]) {
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(11);
var $export = __webpack_require__(5);
var redefine = __webpack_require__(30);
var redefineAll = __webpack_require__(70);
var meta = __webpack_require__(62);
var forOf = __webpack_require__(71);
var anInstance = __webpack_require__(72);
var isObject = __webpack_require__(13);
var fails = __webpack_require__(12);
var $iterDetect = __webpack_require__(131);
var setToStringTag = __webpack_require__(94);
var inheritIfRequired = __webpack_require__(185);
module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
var Base = global[NAME];
var C = Base;
var ADDER = IS_MAP ? 'set' : 'add';
var proto = C && C.prototype;
var O = {};
var fixMethod = function (KEY) {
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function (a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a) {
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a) {
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
new C().entries().next();
}))) {
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C();
// early implementations not supports chaining
var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });
// most early implementations doesn't supports iterables, most modern - not close it correctly
var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
var BUGGY_ZERO = !IS_WEAK && fails(function () {
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C();
var index = 5;
while (index--) $instance[ADDER](index, index);
return !$instance.has(-0);
});
if (!ACCEPT_ITERABLES) {
C = wrapper(function (target, iterable) {
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base(), target, C);
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);
// weak collections should not contains .clear method
if (IS_WEAK && proto.clear) delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__(263);
var redefine = __webpack_require__(30);
var hide = __webpack_require__(31);
var fails = __webpack_require__(12);
var defined = __webpack_require__(51);
var wks = __webpack_require__(16);
var regexpExec = __webpack_require__(171);
var SPECIES = wks('species');
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
// #replace needs built-in support for named groups.
// #match works fine because it just return the exec results, even if it has
// a "grops" property.
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(re, '$<a>') !== '7';
});
var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = (function () {
// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
var re = /(?:)/;
var originalExec = re.exec;
re.exec = function () { return originalExec.apply(this, arguments); };
var result = 'ab'.split(re);
return result.length === 2 && result[0] === 'a' && result[1] === 'b';
})();
module.exports = function (KEY, length, exec) {
var SYMBOL = wks(KEY);
var DELEGATES_TO_SYMBOL = !fails(function () {
// String methods call symbol-named RegEp methods
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
});
var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL ? !fails(function () {
// Symbol-named RegExp methods call .exec
var execCalled = false;
var re = /a/;
re.exec = function () { execCalled = true; return null; };
if (KEY === 'split') {
// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor = {};
re.constructor[SPECIES] = function () { return re; };
}
re[SYMBOL]('');
return !execCalled;
}) : undefined;
if (
!DELEGATES_TO_SYMBOL ||
!DELEGATES_TO_EXEC ||
(KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
(KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
) {
var nativeRegExpMethod = /./[SYMBOL];
var fns = exec(
defined,
SYMBOL,
''[KEY],
function maybeCallNative(nativeMethod, regexp, str, arg2, forceStringMethod) {
if (regexp.exec === regexpExec) {
if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
}
return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
return { done: false };
}
);
var strfn = fns[0];
var rxfn = fns[1];
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return rxfn.call(string, this); }
);
}
};
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var classof = __webpack_require__(93);
var builtinExec = RegExp.prototype.exec;
// `RegExpExec` abstract operation
// https://tc39.github.io/ecma262/#sec-regexpexec
module.exports = function (R, S) {
var exec = R.exec;
if (typeof exec === 'function') {
var result = exec.call(R, S);
if (typeof result !== 'object') {
throw new TypeError('RegExp exec method returned something other than an Object or null');
}
return result;
}
if (classof(R) !== 'RegExp') {
throw new TypeError('RegExp#exec called on incompatible receiver');
}
return builtinExec.call(R, S);
};
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(16)('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(13);
var cof = __webpack_require__(42);
var MATCH = __webpack_require__(16)('match');
module.exports = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(41);
var defined = __webpack_require__(51);
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(42);
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
/***/ }),
/* 135 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(35);
var toLength = __webpack_require__(17);
var toAbsoluteIndex = __webpack_require__(76);
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/* 137 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global, Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "array", function() { return array; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dataset", function() { return Dataset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return zip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CSVDataset", function() { return CSVDataset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextLineDataset", function() { return TextLineDataset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "csv", function() { return csv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "func", function() { return func; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generator", function() { return generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "microphone", function() { return microphone; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "webcam", function() { return webcam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FileDataSource", function() { return FileDataSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URLDataSource", function() { return URLDataSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version_data", function() { return version; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 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 extendStatics=function(t,e){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])})(t,e)};function __extends(t,e){function r(){this.constructor=t}extendStatics(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}function __awaiter(t,e,r,n){return new(r||(r=Promise))(function(i,o){function a(t){try{u(n.next(t))}catch(t){o(t)}}function s(t){try{u(n.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new r(function(e){e(t.value)}).then(a,s)}u((n=n.apply(t,e||[])).next())})}function __generator(t,e){var r,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var commonjsGlobal="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t,e){return t(e={exports:{}},e.exports),e.exports}var alea=createCommonjsModule(function(t){!function(t,e,r){function n(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 r=new function(t){var e,r=this,n=(e=4022871197,function(t){t=t.toString();for(var r=0;r<t.length;r++){var n=.02519603282416938*(e+=t.charCodeAt(r));n-=e=n>>>0,e=(n*=e)>>>0,e+=4294967296*(n-=e)}return 2.3283064365386963e-10*(e>>>0)});r.next=function(){var t=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=t-(r.c=0|t)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(t),r.s0<0&&(r.s0+=1),r.s1-=n(t),r.s1<0&&(r.s1+=1),r.s2-=n(t),r.s2<0&&(r.s2+=1),n=null}(t),i=e&&e.state,o=r.next;return o.int32=function(){return 4294967296*r.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.alea=i}(0,t,!1)}),xor128=createCommonjsModule(function(t){!function(t,e,r){function n(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 r=new function(t){var e=this,r="";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:r+=t;for(var n=0;n<r.length+64;n++)e.x^=0|r.charCodeAt(n),e.next()}(t),i=e&&e.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=r.next,o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i}(0,t,!1)}),xorwow=createCommonjsModule(function(t){!function(t,e,r){function n(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 r=new function(t){var e=this,r="";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:r+=t;for(var n=0;n<r.length+64;n++)e.x^=0|r.charCodeAt(n),n==r.length&&(e.d=e.x<<10^e.x>>>4),e.next()}(t),i=e&&e.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=r.next,o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i}(0,t,!1)}),xorshift7=createCommonjsModule(function(t){!function(t,e,r){function n(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var r=new function(t){var e=this;e.next=function(){var t,r,n=e.x,i=e.i;return t=n[i],r=(t^=t>>>7)^t<<24,r^=(t=n[i+1&7])^t>>>10,r^=(t=n[i+3&7])^t>>>3,r^=(t=n[i+4&7])^t<<7,t=n[i+7&7],r^=(t^=t<<13)^t<<9,n[i]=r,e.i=i+1&7,r},function(t,e){var r,n=[];if(e===(0|e))n[0]=e;else for(e=""+e,r=0;r<e.length;++r)n[7&r]=n[7&r]<<15^e.charCodeAt(r)+n[r+1&7]<<13;for(;n.length<8;)n.push(0);for(r=0;r<8&&0===n[r];++r);for(8==r?n[7]=-1:n[r],t.x=n,t.i=0,r=256;r>0;--r)t.next()}(e,t)}(t),i=e&&e.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=r.next,o.quick=o,i&&(i.x&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i}(0,t,!1)}),xor4096=createCommonjsModule(function(t){!function(t,e,r){function n(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 r=new function(t){var e=this;e.next=function(){var t,r,n=e.w,i=e.X,o=e.i;return e.w=n=n+1640531527|0,r=i[o+34&127],t=i[o=o+1&127],r^=r<<13,t^=t<<17,r^=r>>>15,t^=t>>>12,r=i[o]=r^t,e.i=o,r+(n^n>>>16)|0},function(t,e){var r,n,i,o,a,s=[],u=128;for(e===(0|e)?(n=e,e=null):(e+="\0",n=0,u=Math.max(u,e.length)),i=0,o=-32;o<u;++o)e&&(n^=e.charCodeAt((o+32)%e.length)),0===o&&(a=n),n^=n<<10,n^=n>>>15,n^=n<<4,n^=n>>>13,o>=0&&(a=a+1640531527|0,i=0==(r=s[127&o]^=n+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)n=s[i+34&127],r=s[i=i+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[i]=n^r;t.w=a,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=r.next,o.quick=o,i&&(i.X&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i}(0,t,!1)}),tychei=createCommonjsModule(function(t){!function(t,e,r){function n(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 r=new function(t){var e=this,r="";e.next=function(){var t=e.b,r=e.c,n=e.d,i=e.a;return t=t<<25^t>>>7^r,r=r-n|0,n=n<<24^n>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^r,e.c=r=r-n|0,e.d=n<<16^r>>>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):r+=t;for(var n=0;n<r.length+20;n++)e.b^=0|r.charCodeAt(n),e.next()}(t),i=e&&e.state,o=function(){return(r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=r.next,o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i}(0,t,!1)}),seedrandom=createCommonjsModule(function(t){!function(e,r){var n,i=this,o=256,a=6,s="random",u=r.pow(o,a),c=r.pow(2,52),l=2*c,h=o-1;function f(t,f,v){var _=[],w=p(function t(e,r){var n,i=[],o=typeof e;if(r&&"object"==o)for(n in e)try{i.push(t(e[n],r-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((f=1==f?{entropy:!0}:f||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return n&&(t=n.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var r=i.navigator,a=r&&r.plugins;return[+new Date,i,a,i.screen,m(e)]}}():t,3),_),y=new function(t){var e,r=t.length,n=this,i=0,a=n.i=n.j=0,s=n.S=[];r||(t=[r++]);for(;i<o;)s[i]=i++;for(i=0;i<o;i++)s[i]=s[a=h&a+t[i%r]+(e=s[i])],s[a]=e;(n.g=function(t){for(var e,r=0,i=n.i,a=n.j,s=n.S;t--;)e=s[i=h&i+1],r=r*o+s[h&(s[i]=s[a=h&a+e])+(s[a]=e)];return n.i=i,n.j=a,r})(o)}(_),g=function(){for(var t=y.g(a),e=u,r=0;t<c;)t=(t+r)*o,e*=o,r=y.g(1);for(;t>=l;)t/=2,e/=2,r>>>=1;return(t+r)/e};return g.int32=function(){return 0|y.g(4)},g.quick=function(){return y.g(4)/4294967296},g.double=g,p(m(y.S),e),(f.pass||v||function(t,e,n,i){return i&&(i.S&&d(i,y),t.state=function(){return d(y,{})}),n?(r[s]=t,e):t})(g,w,"global"in f?f.global:this==r,f.state)}function d(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function p(t,e){for(var r,n=t+"",i=0;i<n.length;)e[h&i]=h&(r^=19*e[h&i])+n.charCodeAt(i++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(r["seed"+s]=f,p(r.random(),e),t.exports){t.exports=f;try{n=__webpack_require__(477)}catch(t){}}else 0}([],Math)});seedrandom.alea=alea,seedrandom.xor128=xor128,seedrandom.xorwow=xorwow,seedrandom.xorshift7=xorshift7,seedrandom.xor4096=xor4096,seedrandom.tychei=tychei;var seedrandom$1=seedrandom,seedrandom_1=seedrandom$1.alea;function deepMap(t,e){return deepMapInternal(t,e)}function deepMapInternal(t,e,r,n){if(void 0===r&&(r=new Map),void 0===n&&(n=new Set),null==t)return null;if(n.has(t))throw new Error("Circular references are not supported.");if(r.has(t))return r.get(t);var i=e(t);if(i.recurse&&null!==i.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(i.recurse){if(isIterable(t)){var o=Array.isArray(t)?[]:{};for(var a in n.add(t),t){var s=deepMapInternal(t[a],e,r,n);o[a]=s}return n.delete(t),o}throw new Error("Can't recurse into non-iterable type: "+t)}return r.set(t,i.value),i.value}function deepZip(t,e){return void 0===e&&(e=zipToList),deepZipInternal(t,e)}function deepZipInternal(t,e,r){void 0===r&&(r=new Set);var n=t[0];if(r.has(n))throw new Error("Circular references are not supported.");var i=e(t);if(i.recurse&&null!==i.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(i.recurse){if(isIterable(n)){var o=Array.isArray(n)?[]:{};r.add(n);var a=function(n){var i=deepZipInternal(t.map(function(t){return t[n]}),e,r);o[n]=i};for(var s in n)a(s);return r.delete(n),o}throw new Error("Can't recurse into non-iterable type: "+n)}return i.value}function zipToList(t){return null===t?null:isIterable(t[0])?{value:null,recurse:!0}:{value:t,recurse:!1}}function deepMapAndAwaitAll(t,e){return __awaiter(this,void 0,void 0,function(){var r,n,i,o,a,s;return __generator(this,function(u){switch(u.label){case 0:r=new Map,deepMapInternal(t,e,r),n=0,i=Array.from(r.keys()),u.label=1;case 1:return n<i.length?(o=i[n],(a=r.get(o))instanceof Promise?[4,a]:[3,3]):[3,4];case 2:s=u.sent(),r.set(o,s),u.label=3;case 3:return n++,[3,1];case 4:return[2,deepMapInternal(t,e,r)]}})})}function isIterable(t){return null!=t&&!ArrayBuffer.isView(t)&&(Array.isArray(t)||"object"==typeof t&&!(t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]))}function canTensorify(t){return null==t||isPrimitive(t)||Array.isArray(t)||"object"==typeof t&&t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]||_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].isTypedArray(t)}function isPrimitive(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function deepClone(t){return deepMap(t,cloneIfTensor)}function cloneIfTensor(t){return t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?{value:t.clone(),recurse:!1}:isIterable(t)?{value:null,recurse:!0}:{value:t,recurse:!1}}var RingBuffer=function(){function t(t){if(this.capacity=t,this.begin=0,this.end=0,null==t)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(t<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(t),this.doubledCapacity=2*t}return t.prototype.wrap=function(t){for(;t<0;)t+=this.doubledCapacity;return t%this.doubledCapacity},t.prototype.get=function(t){if(t<0)throw new RangeError("Can't get item at a negative index.");return this.data[t%this.capacity]},t.prototype.set=function(t,e){if(t<0)throw new RangeError("Can't set item at a negative index.");this.data[t%this.capacity]=e},t.prototype.length=function(){var t=this.end-this.begin;return t<0&&(t=this.doubledCapacity+t),t},t.prototype.isFull=function(){return this.length()===this.capacity},t.prototype.isEmpty=function(){return 0===this.length()},t.prototype.push=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,t),this.end=this.wrap(this.end+1)},t.prototype.pushAll=function(t){for(var e=0,r=t;e<r.length;e++){var n=r[e];this.push(n)}},t.prototype.pop=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);var t=this.get(this.end);return this.set(this.end,void 0),t},t.prototype.unshift=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,t)},t.prototype.shift=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var t=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),t},t.prototype.shuffleExcise=function(t){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var e=this.wrap(this.begin+t),r=this.get(e);return this.set(e,this.pop()),r},t}(),GrowingRingBuffer=function(t){function e(){return t.call(this,e.INITIAL_CAPACITY)||this}return __extends(e,t),e.prototype.isFull=function(){return!1},e.prototype.push=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.push.call(this,e)},e.prototype.unshift=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.unshift.call(this,e)},e.prototype.expand=function(){for(var t=2*this.capacity,e=new Array(t),r=this.length(),n=0;n<r;n++)e[n]=this.get(this.wrap(this.begin+n));this.data=e,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=r},e.INITIAL_CAPACITY=32,e}(RingBuffer);function iteratorFromItems(t){return new ArrayIterator(t)}function iteratorFromFunction(t){return new FunctionCallIterator(t)}function iteratorFromConcatenated(t,e){return new ChainedIterator(t,e)}function iteratorFromZipped(t,e){return void 0===e&&(e=ZipMismatchMode.FAIL),new ZipIterator(t,e)}var ZipMismatchMode,LazyIterator=function(){function t(){}return t.prototype.toArray=function(){return __awaiter(this,void 0,void 0,function(){var t,e;return __generator(this,function(r){switch(r.label){case 0:return t=[],[4,this.next()];case 1:e=r.sent(),r.label=2;case 2:return e.done?[3,4]:(t.push(e.value),[4,this.next()]);case 3:return e=r.sent(),[3,2];case 4:return[2,t]}})})},t.prototype.toArrayForTest=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r;return __generator(this,function(n){switch(n.label){case 0:return t=this.prefetch(100),e=[],[4,t.next()];case 1:r=n.sent(),n.label=2;case 2:return r.done?[3,4]:(e.push(r.value),[4,t.next()]);case 3:return r=n.sent(),[3,2];case 4:return[2,e]}})})},t.prototype.resolveFully=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:t=e.sent(),e.label=2;case 2:return t.done?[3,4]:[4,this.next()];case 3:return t=e.sent(),[3,2];case 4:return[2]}})})},t.prototype.resolveWhile=function(t){return __awaiter(this,void 0,void 0,function(){var e,r;return __generator(this,function(n){switch(n.label){case 0:return[4,this.next()];case 1:e=n.sent(),r=t(e.value),n.label=2;case 2:return e.done||!r?[3,4]:[4,this.next()];case 3:return e=n.sent(),r=t(e.value),[3,2];case 4:return[2]}})})},t.prototype.handleErrors=function(t){return new ErrorHandlingLazyIterator(this,t)},t.prototype.filter=function(t){return new FilterIterator(this,t)},t.prototype.map=function(t){return new MapIterator(this,t)},t.prototype.mapAsync=function(t){return new AsyncMapIterator(this,t)},t.prototype.serialMapAsync=function(t){return new AsyncMapIterator(this,t).serial()},t.prototype.flatmap=function(t){return new FlatmapIterator(this,t)},t.prototype.forEachAsync=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.map(t).resolveFully()]})})},t.prototype.serialForEach=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,this.serialMapAsync(t).resolveWhile(function(t){return!0===t})]})})},t.prototype.rowMajorBatch=function(t,e){return void 0===e&&(e=!0),new RowMajorBatchIterator(this,t,e)},t.prototype.columnMajorBatch=function(t,e,r){return void 0===e&&(e=!0),void 0===r&&(r=zipToList),this.rowMajorBatch(t,e).map(function(t){return deepZip(t,r)})},t.prototype.concatenate=function(t,e){return new ChainedIterator(iteratorFromItems([this,t]),e)},t.prototype.take=function(t){return t<0||null==t?this:new TakeIterator(this,t)},t.prototype.skip=function(t){return t<0||null==t?this:new SkipIterator(this,t)},t.prototype.prefetch=function(t){return new PrefetchIterator(this,t)},t.prototype.shuffle=function(t,e){return new ShuffleIterator(this,t,e)},t.prototype.serial=function(){return new SerialIterator(this)},t}(),ArrayIterator=function(t){function e(e){var r=t.call(this)||this;return r.items=e,r.trav=0,r}return __extends(e,t),e.prototype.summary=function(){return"Array of "+this.items.length+" items"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],this.trav++,[2,{value:deepClone(t),done:!1}])})})},e}(LazyIterator),FunctionCallIterator=function(t){function e(e){var r=t.call(this)||this;return r.nextFn=e,r}return __extends(e,t),e.prototype.summary=function(){return"Function call"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){try{return[2,this.nextFn()]}catch(t){throw t.message="Error thrown while iterating through a dataset: "+t.message,t}return[2]})})},e}(LazyIterator),SerialIterator=function(t){function e(e){var r=t.call(this)||this;return r.upstream=e,r.lastRead=Promise.resolve({value:null,done:!1}),r}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return[2,this.upstream.next()]})})},e}(LazyIterator),SkipIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.maxCount=r,n.count=0,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return this.count++<this.maxCount?[4,this.upstream.next()]:[3,2];case 1:return(t=e.sent()).done?[2,t]:(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["dispose"])(t.value),[3,0]);case 2:return[2,this.upstream.next()]}})})},e}(LazyIterator),TakeIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.maxCount=r,n.count=0,n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Take"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},e}(LazyIterator),RowMajorBatchIterator=function(t){function e(e,r,n){void 0===n&&(n=!0);var i=t.call(this)||this;return i.upstream=e,i.batchSize=r,i.enableSmallLastBatch=n,i.lastRead=Promise.resolve({value:null,done:!1}),i}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var t,e;return __generator(this,function(r){switch(r.label){case 0:t=[],r.label=1;case 1:return t.length<this.batchSize?[4,this.upstream.next()]:[3,3];case 2:return(e=r.sent()).done?this.enableSmallLastBatch&&t.length>0?[2,{value:t,done:!1}]:[2,{value:null,done:!0}]:(t.push(e.value),[3,1]);case 3:return[2,{value:t,done:!1}]}})})},e}(LazyIterator),FilterIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.predicate=r,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:return(t=e.sent()).done||this.predicate(t.value)?[2,t]:(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["dispose"])(t.value),[3,0]);case 2:return[2]}})})},e}(LazyIterator),MapIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.transform=r,n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n,i,o,a;return __generator(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,{value:null,done:!0}];for(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].getTensorsInContainer(t.value),r=this.transform(t.value),n=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].getTensorsInContainer(r),i=0,o=e;i<o.length;i++)a=o[i],_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].isTensorInList(a,n)||a.dispose();return[2,{value:r,done:!1}]}})})},e}(LazyIterator),ErrorHandlingLazyIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.handler=r,n.count=0,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> handleErrors"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,e.sent()];case 3:return t=e.sent(),this.handler(t)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}})})},e}(LazyIterator),AsyncMapIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.transform=r,n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n,i,o,a;return __generator(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:return(t=s.sent()).done?[2,{value:null,done:!0}]:(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].getTensorsInContainer(t.value),[4,this.transform(t.value)]);case 2:for(r=s.sent(),n=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].getTensorsInContainer(r),i=0,o=e;i<o.length;i++)a=o[i],_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].isTensorInList(a,n)||a.dispose();return[2,{value:r,done:!1}]}})})},e}(LazyIterator),OneToManyIterator=function(t){function e(){var e=t.call(this)||this;return e.outputQueue=new GrowingRingBuffer,e.lastRead=Promise.resolve({value:null,done:!1}),e}return __extends(e,t),e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return 0!==this.outputQueue.length()?[3,2]:[4,this.pump()];case 1:return t.sent()?[3,0]:[2,{value:null,done:!0}];case 2:return[2,{value:this.outputQueue.shift(),done:!1}]}})})},e}(LazyIterator),FlatmapIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.transform=r,n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Flatmap"},e.prototype.pump=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n,i,o,a;return __generator(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,!1];for(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].getTensorsInContainer(t.value),r=this.transform(t.value),n=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].getTensorsInContainer(r),this.outputQueue.pushAll(r),i=0,o=e;i<o.length;i++)a=o[i],_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor_util"].isTensorInList(a,n)||a.dispose();return[2,!0]}})})},e}(OneToManyIterator),ChainedIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.baseErrorHandler=r,n.lastRead=null,n.iterator=null,n.moreIterators=e,n}return __extends(e,t),e.prototype.summary=function(){return"TODO: fill in upstream of chained summaries -> Chained"},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},e.prototype.readFromChain=function(t){return __awaiter(this,void 0,void 0,function(){var e,r;return __generator(this,function(n){switch(n.label){case 0:return[4,t];case 1:return n.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((e=n.sent()).done)return[2,{value:null,done:!0}];this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),n.label=3;case 3:return[4,this.iterator.next()];case 4:return(r=n.sent()).done?(this.iterator=null,[2,this.readFromChain(t)]):[2,r]}})})},e}(LazyIterator);!function(t){t[t.FAIL=0]="FAIL",t[t.SHORTEST=1]="SHORTEST",t[t.LONGEST=2]="LONGEST"}(ZipMismatchMode||(ZipMismatchMode={}));var ZipIterator=function(t){function e(e,r){void 0===r&&(r=ZipMismatchMode.FAIL);var n=t.call(this)||this;return n.iterators=e,n.mismatchMode=r,n.count=0,n.currentPromise=null,n}return __extends(e,t),e.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return __awaiter(this,void 0,void 0,function(){function e(t){return t instanceof LazyIterator?{value:t.next().then(function(t){return r++,t.done&&n++,t.value}),recurse:!1}:{value:null,recurse:!0}}var r,n,i;return __generator(this,function(o){switch(o.label){case 0:return[4,t];case 1:return o.sent(),r=0,n=0,[4,deepMapAndAwaitAll(this.iterators,e)];case 2:if(i=o.sent(),r===n)return[2,{value:null,done:!0}];if(n>0)switch(this.mismatchMode){case ZipMismatchMode.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case ZipMismatchMode.SHORTEST:return[2,{value:null,done:!0}];case ZipMismatchMode.LONGEST:}return this.count++,[2,{value:i,done:!1}]}})})},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return this.currentPromise=this.nextState(this.currentPromise),[2,this.currentPromise]})})},e}(LazyIterator),PrefetchIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.bufferSize=r,n.buffer=new RingBuffer(r),n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},e.prototype.refill=function(){for(;!this.buffer.isFull();){var t=this.upstream.next();this.buffer.push(t)}},e.prototype.next=function(){return this.refill(),this.buffer.shift()},e}(LazyIterator),ShuffleIterator=function(t){function e(e,r,n){var i=t.call(this,e,r)||this;return i.upstream=e,i.windowSize=r,i.upstreamExhausted=!1,i.random=seedrandom_1(n||_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].now().toString()),i.lastRead=Promise.resolve({value:null,done:!1}),i}return __extends(e,t),e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t=this;return __generator(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.randomInt=function(t){return Math.floor(this.random()*t)},e.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},e.prototype.serialNext=function(){return __awaiter(this,void 0,void 0,function(){var t,e;return __generator(this,function(r){switch(r.label){case 0:this.upstreamExhausted||this.refill(),r.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(t=this.chooseIndex(),[4,this.buffer.shuffleExcise(t)]);case 2:return(e=r.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,e]);case 3:return[2,{value:null,done:!0}]}})})},e}(PrefetchIterator),Dataset=function(){function t(){this.size=null}return t.prototype.batch=function(t,e){var r=this;void 0===e&&(e=!0);var n=this;return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t>0,function(){return"batchSize needs to be positive, but it is\n "+t}),datasetFromIteratorFn(function(){return __awaiter(r,void 0,void 0,function(){return __generator(this,function(r){switch(r.label){case 0:return[4,n.iterator()];case 1:return[2,r.sent().columnMajorBatch(t,e,deepBatchConcat)]}})})},this.size===1/0||null==this.size?this.size:e?Math.ceil(this.size/t):Math.floor(this.size/t))},t.prototype.concatenate=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){var e,n;return __generator(this,function(i){switch(i.label){case 0:return[4,r.iterator()];case 1:return n=(e=i.sent()).concatenate,[4,t.iterator()];case 2:return[2,n.apply(e,[i.sent()])]}})})},this.size===1/0||t.size===1/0?1/0:null!=this.size&&null!=t.size?this.size+t.size:null)},t.prototype.filter=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().filter(function(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return t(e)})})]}})})},this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}})})},t.prototype.forEach=function(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["deprecationWarn"])("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]})})},t.prototype.map=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().map(function(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return t(e)})})]}})})},this.size)},t.prototype.mapAsync=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().mapAsync(t)]}})})},this.size)},t.prototype.prefetch=function(t){var e=this;if(null==t)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().prefetch(t)]}})})},this.size)},t.prototype.repeat=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){var e=this;return __generator(this,function(n){return[2,iteratorFromConcatenated(iteratorFromFunction(function(){return __awaiter(e,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return t={},[4,r.iterator()];case 1:return[2,(t.value=e.sent(),t.done=!1,t)]}})})}).take(t))]})})},null!=this.size&&t>0?this.size*t:0===t?0:null!=this.size&&(void 0===t||t<0)?1/0:null)},t.prototype.skip=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().skip(t)]}})})},null!=this.size&&t>=0&&this.size>=t?this.size-t:null!=this.size&&(this.size<t||void 0===t||t<0)?0:null)},t.prototype.shuffle=function(t,e,r){var n=this;if(void 0===r&&(r=!0),null==t||t<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError("`Dataset.shuffle()` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for `tf.Tensor`s), consider setting bufferSize to the dataset size ("+this.size+" elements)");var i=this,o=seedrandom_1(e||_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].now().toString());return datasetFromIteratorFn(function(){return __awaiter(n,void 0,void 0,function(){var e;return __generator(this,function(n){switch(n.label){case 0:return e=o.int32(),r&&(e+=o.int32()),[4,i.iterator()];case 1:return[2,n.sent().shuffle(t,e.toString())]}})})},this.size)},t.prototype.take=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().take(t)]}})})},null!=this.size&&this.size>t?t:null!=this.size&&this.size<=t?this.size:null)},t.prototype.toArray=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArray()]}})})},t.prototype.toArrayForTest=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArrayForTest()]}})})},t.MAX_BUFFER_SIZE=1e4,t}();function datasetFromIteratorFn(t,e){return void 0===e&&(e=null),new(function(r){function n(){var t=null!==r&&r.apply(this,arguments)||this;return t.size=e,t}return __extends(n,r),n.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,t()]})})},n}(Dataset))}function array(t){var e=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(e){return[2,iteratorFromItems(t)]})})},t.length)}function zip(t){var e,r=this;if(!isIterable(t))throw new Error("The argument to zip() must be an object or array.");if(Array.isArray(t))for(var n=0;n<t.length;n++)e=null==e?t[n].size:Math.min(e,t[n].size);else if(t instanceof Object)for(var i in t)e=null==e?t[i].size:Math.min(e,t[i].size);return datasetFromIteratorFn(function(){return __awaiter(r,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:return[4,deepMapAndAwaitAll(t,function(t){if(t instanceof Dataset)return{value:t.iterator(),recurse:!1};if(isIterable(t))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})];case 1:return[2,iteratorFromZipped(e.sent(),ZipMismatchMode.SHORTEST)]}})})},e)}function deepBatchConcat(t){return null===t?null:canTensorify(t[0])?{value:batchConcat(t),recurse:!1}:{value:null,recurse:!0}}function batchConcat(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["stack"])(t):Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor"])(t)}var TextLineDataset=function(t){function e(e){var r=t.call(this)||this;return r.input=e,r}return __extends(e,t),e.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){var t,e;return __generator(this,function(r){switch(r.label){case 0:return[4,this.input.iterator()];case 1:return t=r.sent(),e=t.decodeUTF8(),[2,e.split("\n").map(function(t){return t.endsWith("\r")&&(t=t.slice(0,-1)),t})]}})})},e}(Dataset),CODE_QUOTE='"',STATE_OUT=Symbol("out"),STATE_FIELD=Symbol("field"),STATE_QUOTE=Symbol("quote"),STATE_QUOTE_AFTER_QUOTE=Symbol("quoteafterquote"),STATE_WITHIN_QUOTE_IN_QUOTE=Symbol("quoteinquote"),CSVDataset=function(t){function e(e,r){var n=t.call(this)||this;return n.input=e,n.hasHeader=!0,n.fullColumnNames=null,n.columnNamesValidated=!1,n.columnConfigs=null,n.configuredColumnsOnly=!1,n.delimiter=",",n.delimWhitespace=!1,n.base=new TextLineDataset(e),r||(r={}),n.hasHeader=!1!==r.hasHeader,n.fullColumnNames=r.columnNames,n.columnConfigs=r.columnConfigs,n.configuredColumnsOnly=r.configuredColumnsOnly,r.delimWhitespace?(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null==r.delimiter,function(){return"Delimiter should not be provided when delimWhitespace is true."}),n.delimWhitespace=!0,n.delimiter=" "):n.delimiter=r.delimiter?r.delimiter:",",n}return __extends(e,t),e.prototype.columnNames=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:t.sent(),t.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}})})},e.prototype.setColumnNames=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n,i,o,a=this;return __generator(this,function(s){switch(s.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(t=s.sent(),!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&t&&_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+a.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce(function(t,e){return t[e]=t[e]+1||1,t},{}),r=Object.keys(e).filter(function(t){return e[t]>1}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(0===r.length,function(){return"Duplicate column names found: "+r.toString()}),this.columnConfigs)for(n=0,i=Object.keys(this.columnConfigs);n<i.length;n++)if(o=i[n],-1===this.fullColumnNames.indexOf(o))throw new Error('The key "'+o+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");return this.columnNamesValidated=!0,[2]}})})},e.prototype.maybeReadHeaderLine=function(){return __awaiter(this,void 0,void 0,function(){var t,e;return __generator(this,function(r){switch(r.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return[4,r.sent().next()];case 2:if((t=r.sent()).done)throw new Error("No data was found for CSV parsing.");return e=t.value,[2,this.parseRow(e,!1)];case 3:return[2,null]}})})},e.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){var t,e=this;return __generator(this,function(r){switch(r.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:r.sent(),r.label=2;case 2:return[4,this.base.iterator()];case 3:return t=r.sent(),this.hasHeader&&(t=t.skip(1)),[2,t.map(function(t){return e.makeDataElement(t)})]}})})},e.prototype.makeDataElement=function(t){for(var e=this.parseRow(t),r={},n={},i=0;i<this.fullColumnNames.length;i++){var o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(!this.configuredColumnsOnly||a){var s=e[i],u=null;if(""===s)if(a&&void 0!==a.default)u=a.default;else{if(a&&(a.required||a.isLabel))throw new Error("Required column "+o+" is empty in this line: "+t);u=void 0}else{var c=Number(s);if(isNaN(c))u=a&&"bool"===a.dtype?this.getBoolean(s):s;else if(a&&a.dtype)switch(a.dtype){case"float32":u=c;break;case"int32":u=Math.floor(c);break;case"bool":u=this.getBoolean(s);break;default:u=c}else u=c}a&&a.isLabel?n[o]=u:r[o]=u}}return 0===Object.keys(n).length?r:{xs:r,ys:n}},e.prototype.getBoolean=function(t){return"1"===t||"true"===t.toLowerCase()?1:0},e.prototype.parseRow=function(t,e){void 0===e&&(e=!0);for(var r=[],n=0,i=t.length,o=STATE_OUT,a=0;a<i;a++)switch(o){case STATE_OUT:switch(t.charAt(a)){case CODE_QUOTE:n=a+1,o=STATE_QUOTE;break;case this.delimiter:if(n=a+1," "===this.delimiter&&this.delimWhitespace)break;r.push(""),o=STATE_OUT;break;default:o=STATE_FIELD,n=a}break;case STATE_FIELD:switch(t.charAt(a)){case this.delimiter:r.push(t.substring(n,a)),o=STATE_OUT,n=a+1}break;case STATE_QUOTE:switch(t.charAt(a)){case CODE_QUOTE:o=STATE_QUOTE_AFTER_QUOTE}break;case STATE_QUOTE_AFTER_QUOTE:switch(t.charAt(a)){case this.delimiter:r.push(t.substring(n,a-1)),o=STATE_OUT,n=a+1;break;case CODE_QUOTE:o=STATE_QUOTE;break;default:o=STATE_WITHIN_QUOTE_IN_QUOTE}break;case STATE_WITHIN_QUOTE_IN_QUOTE:switch(t.charAt(a)){case CODE_QUOTE:o=STATE_QUOTE}}if(o===STATE_QUOTE_AFTER_QUOTE?r.push(t.substring(n,i-1)):r.push(t.substring(n)),e&&r.length!==this.fullColumnNames.length)throw new Error("Invalid row in csv file. Should have "+this.fullColumnNames.length+" elements in a row, but got "+r);return r},e}(Dataset),MicrophoneIterator=function(t){function e(e){var r=t.call(this)||this;r.microphoneConfig=e,r.isClosed=!1,r.fftSize=e.fftSize||1024;var n=Math.log2(r.fftSize);if(r.fftSize<0||n<4||n>14||!Number.isInteger(n))throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got "+r.fftSize);if(r.numFrames=e.numFramesPerSpectrogram||43,r.sampleRateHz=e.sampleRateHz,r.columnTruncateLength=e.columnTruncateLength||r.fftSize,r.audioTrackConstraints=e.audioTrackConstraints,r.smoothingTimeConstant=e.smoothingTimeConstant||0,r.includeSpectrogram=!1!==e.includeSpectrogram,r.includeWaveform=!0===e.includeWaveform,!r.includeSpectrogram&&!r.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return r}return __extends(e,t),e.prototype.summary=function(){return"microphone"},e.create=function(t){return void 0===t&&(t={}),__awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(n){switch(n.label){case 0:if(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return[4,(r=new e(t)).start()];case 1:return n.sent(),[2,r]}})})},e.prototype.start=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n;return __generator(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=this,[4,navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})];case 1:return t.stream=i.sent(),[3,3];case 2:throw e=i.sent(),new Error("Error thrown while initializing video stream: "+e.message);case 3:if(!this.stream)throw new Error("Could not obtain audio from microphone.");if(r=window.AudioContext||window.webkitAudioContext,this.audioContext=new r,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: Expected: "+this.sampleRateHz+"; Actual: "+this.audioContext.sampleRate)}else this.sampleRateHz=this.audioContext.sampleRate;return n=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,n.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2]}})})},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n,i;return __generator(this,function(o){switch(o.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return r=o.sent(),this.includeSpectrogram&&(n=this.flattenQueue(r.freqDataQueue),t=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(i=this.flattenQueue(r.timeDataQueue),e=this.getTensorFromAudioDataArray(i,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:t,waveform:e},done:!1}]}})})},e.prototype.capture=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}})})},e.prototype.getAudioData=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n=this;return __generator(this,function(i){return t=[],e=[],r=0,[2,new Promise(function(i){var o=setInterval(function(){n.includeSpectrogram&&(n.analyser.getFloatFrequencyData(n.freqData),n.freqData[0]===-1/0&&i({freqDataQueue:t,timeDataQueue:e}),t.push(n.freqData.slice(0,n.columnTruncateLength))),n.includeWaveform&&(n.analyser.getFloatTimeDomainData(n.timeData),e.push(n.timeData.slice())),++r===n.numFrames&&(clearInterval(o),i({freqDataQueue:t,timeDataQueue:e}))},n.fftSize/n.sampleRateHz*1e3)})]})})},e.prototype.stop=function(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())},e.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},e.prototype.getSampleRate=function(){return this.sampleRateHz},e.prototype.flattenQueue=function(t){var e=t[0].length,r=new Float32Array(t.length*e);return t.forEach(function(t,n){return r.set(t,n*e)}),r},e.prototype.getTensorFromAudioDataArray=function(t,e){var r=new Float32Array(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(e));return r.set(t,r.length-t.length),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor"])(r,e)},e}(LazyIterator),WebcamIterator=function(t){function e(e,r){var n=t.call(this)||this;if(n.webcamVideoElement=e,n.webcamConfig=r,n.isClosed=!0,n.resize=!1,n.needToResize())if(n.resize=!0,n.cropSize=[n.webcamConfig.resizeHeight,n.webcamConfig.resizeWidth],n.cropBoxInd=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([0],"int32"),n.webcamConfig.centerCrop){var i=1*n.webcamConfig.resizeWidth/n.webcamVideoElement.width,o=1*n.webcamConfig.resizeHeight/n.webcamVideoElement.height,a=(1-i)/2,s=(1-o)/2,u=a+i,c=o+s;n.cropBox=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])([s,a,c,u],[1,4])}else n.cropBox=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])([0,0,1,1],[1,4]);return n}return __extends(e,t),e.prototype.summary=function(){return"webcam"},e.create=function(t,r){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(i){switch(i.label){case 0:if(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!r.resizeWidth||!r.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=r.resizeWidth,t.height=r.resizeHeight}return[4,(n=new e(t,r)).start()];case 1:return i.sent(),[2,n]}})})},e.prototype.start=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r=this;return __generator(this,function(n){switch(n.label){case 0:this.webcamConfig.facingMode&&_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,function(){return"Invalid webcam facing mode: "+r.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),n.label=1;case 1:return n.trys.push([1,3,,4]),t=this,[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:return t.stream=n.sent(),[3,4];case 3:throw(e=n.sent()).message="Error thrown while initializing video stream: "+e.message,e;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(t){r.webcamVideoElement.onloadedmetadata=function(){t()}})]}})})},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){if(this.isClosed)return[2,{value:null,done:!0}];try{t=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(this.webcamVideoElement)}catch(t){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(t))}if(!this.resize)return[2,{value:t,done:!1}];try{return[2,{value:this.cropAndResizeFrame(t),done:!1}]}catch(t){throw new Error("Error thrown cropping the video: "+t.message)}finally{t.dispose()}return[2]})})},e.prototype.needToResize=function(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)},e.prototype.cropAndResizeFrame=function(t){var e=this;return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r,n=t.toFloat().expandDims(0),i=(r=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].cropAndResize(n,e.cropBox,e.cropBoxInd,e.cropSize,"bilinear")).shape;return r.reshape(i.slice(1))})},e.prototype.capture=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}})})},e.prototype.stop=function(){this.stream.getTracks().forEach(function(t){return t.stop()});try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0},e.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},e}(LazyIterator),DataSource=function(){return function(){}}(),StringIterator=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.split=function(t){return new SplitIterator(this,t)},e}(LazyIterator),SplitIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.impl=new SplitIteratorImpl(e,r),n}return __extends(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return[2,this.impl.next()]})})},e}(StringIterator),SplitIteratorImpl=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.separator=r,n.carryover="",n}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},e.prototype.pump=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r,n,i;return __generator(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if((t=o.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],r=0,n=e.slice(0,-1);r<n.length;r++)i=n[r],this.outputQueue.push(i);return this.carryover=e[e.length-1],[2,!0]}})})},e}(OneToManyIterator),ByteChunkIterator=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends(e,t),e.prototype.decodeUTF8=function(){return new Utf8Iterator(this)},e}(LazyIterator),Utf8Iterator=function(t){function e(e){var r=t.call(this)||this;return r.upstream=e,r.impl=new Utf8IteratorImpl(e),r}return __extends(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return[2,this.impl.next()]})})},e}(StringIterator),Utf8IteratorImpl=function(t){function e(e){var r=t.call(this)||this;if(r.upstream=e,Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_BROWSER"))r.decoder=new TextDecoder("utf-8");else{var n=__webpack_require__(476).StringDecoder;r.decoder=new n("utf8")}return r}return __extends(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"},e.prototype.pump=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r;return __generator(this,function(n){switch(n.label){case 0:return[4,this.upstream.next()];case 1:return(t=n.sent()).done?[2,!1]:(e=t.value,r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_BROWSER")?this.decoder.decode(e,{stream:!0}):this.decoder.write(Buffer.from(e.buffer)),this.outputQueue.push(r),[2,!0])}})})},e}(OneToManyIterator),FileChunkIterator=function(t){function e(e,r){void 0===r&&(r={});var n=t.call(this)||this;return n.file=e,n.options=r,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(e instanceof Uint8Array||!!Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),n.offset=r.offset||0,n.chunkSize=r.chunkSize||1048576,n}return __extends(e,t),e.prototype.summary=function(){return"FileChunks "+this.file},e.prototype.next=function(){return __awaiter(this,void 0,void 0,function(){var t,e,r=this;return __generator(this,function(n){switch(n.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(t=new Promise(function(t,e){var n=r.offset+r.chunkSize;if(r.file instanceof Uint8Array)t(new Uint8Array(r.file.slice(r.offset,n)));else{var i=new FileReader;i.onload=function(r){var n=i.result;if(n instanceof ArrayBuffer&&(n=new Uint8Array(n)),!(n instanceof Uint8Array))return e(new TypeError("FileReader returned unknown type."));t(n)},i.onabort=function(t){return e(new Error("Aborted"))},i.onerror=function(t){return e(new Error(t.type))};var o=r.file.slice(r.offset,n);i.readAsArrayBuffer(o)}r.offset=n}),e={},[4,t]);case 1:return[2,(e.value=n.sent(),e.done=!1,e)]}})})},e}(ByteChunkIterator);function urlChunkIterator(t,e){return void 0===e&&(e={}),__awaiter(this,void 0,void 0,function(){var r,n,i,o,a;return __generator(this,function(s){switch(s.label){case 0:return"string"==typeof t?r=t:(r=t.url,n=getRequestInitFromRequest(t)),[4,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].fetch(r,n)];case 1:return(i=s.sent()).ok?(a=Uint8Array.bind,[4,i.arrayBuffer()]):[3,3];case 2:return o=new(a.apply(Uint8Array,[void 0,s.sent()])),[2,new FileChunkIterator(o,e)];case 3:throw new Error(i.statusText)}})})}var getRequestInitFromRequest=function(t){return{method:t.method,headers:t.headers,body:t.body,mode:t.mode,credentials:t.credentials,cache:t.cache,redirect:t.redirect,referrer:t.referrer,integrity:t.integrity}};function isLocalPath(t){return"string"==typeof t&&"file://"===t.substr(0,7)}var FileDataSource=function(t){function e(e,r){void 0===r&&(r={});var n=t.call(this)||this;return n.input=e,n.options=r,n}return __extends(e,t),e.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){return isLocalPath(this.input)&&Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("IS_NODE")&&(t=__webpack_require__(475),this.input=t.readFileSync(this.input.substr(7))),[2,new FileChunkIterator(this.input,this.options)]})})},e}(DataSource),URLDataSource=function(t){function e(e,r){void 0===r&&(r={});var n=t.call(this)||this;return n.url=e,n.fileOptions=r,n}return __extends(e,t),e.prototype.iterator=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return isLocalPath(this.url)?[2,new FileDataSource(this.url,this.fileOptions).iterator()]:[2,urlChunkIterator(this.url,this.fileOptions)]})})},e}(DataSource);function csv(t,e){return void 0===e&&(e={}),new CSVDataset(new URLDataSource(t),e)}function func(t){var e=this,r=iteratorFromFunction(t);return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){return __generator(this,function(t){return[2,r]})})})}function generator(t){var e=this;return datasetFromIteratorFn(function(){return __awaiter(e,void 0,void 0,function(){var e;return __generator(this,function(r){switch(r.label){case 0:return[4,t()];case 1:return e=r.sent(),[2,iteratorFromFunction(function(){return e.next()})]}})})})}function webcam(t,e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(r){return[2,WebcamIterator.create(t,e)]})})}function microphone(t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,MicrophoneIterator.create(t)]})})}var version="1.7.2";
//# sourceMappingURL=tf-data.esm.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53), __webpack_require__(86).Buffer))
/***/ }),
/* 138 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createFileSystem; });
function createFileSystem(fs) {
var requireFsError = '';
if (!fs) {
try {
fs = __webpack_require__(210);
}
catch (err) {
requireFsError = err.toString();
}
}
var readFile = fs
? function (filePath) {
return new Promise(function (res, rej) {
fs.readFile(filePath, function (err, buffer) {
return err ? rej(err) : res(buffer);
});
});
}
: function () {
throw new Error("readFile - failed to require fs in nodejs environment with error: " + requireFsError);
};
return {
readFile: readFile
};
}
//# sourceMappingURL=createFileSystem.js.map
/***/ }),
/* 139 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return json; });
/* harmony import */ var vega_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
function isBuffer(_) {
return (typeof Buffer === 'function' && Object(vega_util__WEBPACK_IMPORTED_MODULE_0__[/* isFunction */ "D"])(Buffer.isBuffer))
? Buffer.isBuffer(_) : false;
}
function json(data, format) {
const prop = (format && format.property) ? Object(vega_util__WEBPACK_IMPORTED_MODULE_0__[/* field */ "t"])(format.property) : vega_util__WEBPACK_IMPORTED_MODULE_0__[/* identity */ "x"];
return Object(vega_util__WEBPACK_IMPORTED_MODULE_0__[/* isObject */ "F"])(data) && !isBuffer(data)
? parseJSON(prop(data))
: prop(JSON.parse(data));
}
json.responseType = 'json';
function parseJSON(data, format) {
return (format && format.copy)
? JSON.parse(JSON.stringify(data))
: data;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(86).Buffer))
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Note: This regex matches even invalid JSON strings, but since were
// working on the output of `JSON.stringify` we know that only valid strings
// are present (unless the user supplied a weird `options.indent` but in
// that case we dont care since the output would be invalid anyway).
var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g;
module.exports = function stringify(passedObj, options) {
var indent, maxLength, replacer;
options = options || {};
indent = JSON.stringify(
[1],
undefined,
options.indent === undefined ? 2 : options.indent
).slice(2, -3);
maxLength =
indent === ""
? Infinity
: options.maxLength === undefined
? 80
: options.maxLength;
replacer = options.replacer;
return (function _stringify(obj, currentIndent, reserved) {
// prettier-ignore
var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value;
if (obj && typeof obj.toJSON === "function") {
obj = obj.toJSON();
}
string = JSON.stringify(obj, replacer);
if (string === undefined) {
return string;
}
length = maxLength - currentIndent.length - reserved;
if (string.length <= length) {
prettified = string.replace(stringOrChar, function(match, stringLiteral) {
return stringLiteral || match + " ";
});
if (prettified.length <= length) {
return prettified;
}
}
if (replacer != null) {
obj = JSON.parse(string);
replacer = undefined;
}
if (typeof obj === "object" && obj !== null) {
nextIndent = currentIndent + indent;
items = [];
index = 0;
if (Array.isArray(obj)) {
start = "[";
end = "]";
length = obj.length;
for (; index < length; index++) {
items.push(
_stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) ||
"null"
);
}
} else {
start = "{";
end = "}";
keys = Object.keys(obj);
length = keys.length;
for (; index < length; index++) {
key = keys[index];
keyPart = JSON.stringify(key) + ": ";
value = _stringify(
obj[key],
nextIndent,
keyPart.length + (index === length - 1 ? 0 : 1)
);
if (value !== undefined) {
items.push(keyPart + value);
}
}
}
if (items.length > 0) {
return [start, indent + items.join(",\n" + nextIndent), end].join(
"\n" + currentIndent
);
}
}
return string;
})(passedObj, "", 0);
};
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function isAbsoluteURL(str) {
var pattern = new RegExp('^(?:[a-z]+:)?//', 'i');
return !!pattern.test(str);
}
function getModelPath(absoluteOrRelativeUrl) {
var modelJsonPath = isAbsoluteURL(absoluteOrRelativeUrl) ? absoluteOrRelativeUrl : window.location.pathname + absoluteOrRelativeUrl;
return modelJsonPath;
}
exports.default = {
isAbsoluteURL: isAbsoluteURL,
getModelPath: getModelPath
};
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
Image and Video base class
*/
var Video = function () {
function Video(video, size) {
(0, _classCallCheck3.default)(this, Video);
this.videoElt = null;
this.size = size;
this.videoReady = false;
if (video instanceof HTMLVideoElement) {
this.videoElt = video;
} else if (video !== null && (typeof video === 'undefined' ? 'undefined' : (0, _typeof3.default)(video)) === 'object' && video.elt instanceof HTMLVideoElement) {
// Handle p5.js video element
this.videoElt = video.elt;
}
}
(0, _createClass3.default)(Video, [{
key: 'loadVideo',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this = this;
var stream;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
stream = void 0;
return _context.abrupt('return', new _promise2.default(function (resolve) {
_this.video = document.createElement('video');
var sUsrAg = navigator.userAgent;
if (sUsrAg.indexOf('Firefox') > -1) {
stream = _this.videoElt.mozCaptureStream();
} else {
stream = _this.videoElt.captureStream();
}
_this.video.srcObject = stream;
_this.video.width = _this.size;
_this.video.height = _this.size;
_this.video.autoplay = true;
_this.video.playsinline = true;
_this.video.muted = true;
var playPromise = _this.video.play();
if (playPromise !== undefined) {
playPromise.then(function () {
resolve(_this.video);
});
}
}));
case 2:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadVideo() {
return _ref.apply(this, arguments);
}
return loadVideo;
}()
}]);
return Video;
}();
exports.default = Video;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getTopKClassesFromTensor = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var getTopKClassesFromTensor = exports.getTopKClassesFromTensor = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(logits, topK, CLASSES) {
var values;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return logits.data();
case 2:
values = _context.sent;
return _context.abrupt("return", getTopKClassesFromArray(values, topK, CLASSES));
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
return function getTopKClassesFromTensor(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
exports.getTopKClassesFromArray = getTopKClassesFromArray;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
function getTopKClassesFromArray(values, topK, CLASSES) {
var valuesAndIndices = [];
for (var i = 0; i < values.length; i += 1) {
valuesAndIndices.push({
value: values[i],
index: i
});
}
valuesAndIndices.sort(function (a, b) {
return b.value - a.value;
});
var topkValues = new Float32Array(topK);
var topkIndices = new Int32Array(topK);
for (var _i = 0; _i < topK; _i += 1) {
topkValues[_i] = valuesAndIndices[_i].value;
topkIndices[_i] = valuesAndIndices[_i].index;
}
var topClassesAndProbs = [];
for (var _i2 = 0; _i2 < topkIndices.length; _i2 += 1) {
topClassesAndProbs.push({
className: CLASSES[topkIndices[_i2]],
probability: topkValues[_i2]
});
}
return topClassesAndProbs;
}
exports.default = { getTopKClassesFromArray: getTopKClassesFromArray, getTopKClassesFromTensor: getTopKClassesFromTensor };
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(26);
var core = __webpack_require__(18);
var LIBRARY = __webpack_require__(106);
var wksExt = __webpack_require__(147);
var defineProperty = __webpack_require__(39).f;
module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
var META = __webpack_require__(121)('meta');
var isObject = __webpack_require__(38);
var has = __webpack_require__(67);
var setDesc = __webpack_require__(39).f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !__webpack_require__(68)(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(25);
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
var hide = __webpack_require__(60);
module.exports = function (target, src, safe) {
for (var key in src) {
if (safe && target[key]) target[key] = src[key];
else hide(target, key, src[key]);
} return target;
};
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __webpack_require__(109);
function PromiseCapability(C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(116);
var ITERATOR = __webpack_require__(25)('iterator');
var Iterators = __webpack_require__(84);
module.exports = __webpack_require__(18).getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/* 151 */
/***/ (function(module, exports) {
module.exports = function (it, Constructor, name, forbiddenField) {
if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(106);
var $export = __webpack_require__(23);
var redefine = __webpack_require__(234);
var hide = __webpack_require__(60);
var Iterators = __webpack_require__(84);
var $iterCreate = __webpack_require__(423);
var setToStringTag = __webpack_require__(102);
var getPrototypeOf = __webpack_require__(232);
var ITERATOR = __webpack_require__(25)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/* 153 */
/***/ (function(module, exports) {
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const d3_format_1 = __webpack_require__(45);
const vega_embed_1 = __importDefault(__webpack_require__(81));
const dom_1 = __webpack_require__(59);
const math_1 = __webpack_require__(119);
const table_1 = __webpack_require__(118);
const defaultOpts = {
maxBins: 12,
fontSize: 11,
};
/**
* Renders a histogram of values
*
* ```js
* const data = Array(100).fill(0)
* .map(x => Math.random() * 100 - (Math.random() * 50))
*
* // Push some special values for the stats table.
* data.push(Infinity);
* data.push(NaN);
* data.push(0);
*
* const surface = { name: 'Histogram', tab: 'Charts' };
* tfvis.render.histogram(surface, data);
* ```
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function histogram(container, data, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const values = prepareData(data);
const options = Object.assign({}, defaultOpts, opts);
const embedOpts = {
actions: false,
mode: 'vega-lite',
defaultStyle: false,
};
const histogramContainer = dom_1.subSurface(container, 'histogram');
if (opts.stats !== false) {
const statsContainer = dom_1.subSurface(container, 'stats', {
prepend: true,
});
let stats;
if (opts.stats) {
stats = opts.stats;
}
else {
stats = math_1.arrayStats(values.map(x => x.value));
}
renderStats(stats, statsContainer, { fontSize: options.fontSize });
}
// Now that we have rendered stats we need to remove any NaNs and Infinities
// before rendering the histogram
const filtered = [];
for (let i = 0; i < values.length; i++) {
const val = values[i].value;
if (val != null && isFinite(val)) {
filtered.push(values[i]);
}
}
const histogramSpec = {
'width': options.width || dom_1.getDefaultWidth(histogramContainer),
'height': options.height || dom_1.getDefaultHeight(histogramContainer),
'padding': 0,
'autosize': {
'type': 'fit',
'contains': 'padding',
'resize': true,
},
'data': { 'values': filtered },
'mark': {
'type': 'bar',
'tooltip': true,
},
'config': {
'axis': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'text': { 'fontSize': options.fontSize },
'legend': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
}
},
'encoding': {
'x': {
'bin': { 'maxbins': options.maxBins },
'field': 'value',
'type': 'quantitative',
},
'y': {
'aggregate': 'count',
'type': 'quantitative',
},
'color': {
'value': options.color || '#001B44',
}
}
};
return vega_embed_1.default(histogramContainer, histogramSpec, embedOpts);
});
}
exports.histogram = histogram;
function renderStats(stats, container, opts) {
const format = d3_format_1.format(',.4~f');
const pctFormat = d3_format_1.format('.4~p');
const headers = [];
const vals = [];
if (stats.numVals != null) {
headers.push('Num Vals');
vals.push(format(stats.numVals));
}
if (stats.min != null) {
headers.push('Min');
vals.push(format(stats.min));
}
if (stats.max != null) {
headers.push('Max');
vals.push(format(stats.max));
}
if (stats.numZeros != null) {
headers.push('# Zeros');
let zeroPct = '';
if (stats.numVals) {
zeroPct = stats.numZeros > 0 ?
`(${pctFormat(stats.numZeros / stats.numVals)})` :
'';
}
vals.push(`${format(stats.numZeros)} ${zeroPct}`);
}
if (stats.numNans != null) {
headers.push('# NaNs');
let nanPct = '';
if (stats.numVals) {
nanPct = stats.numNans > 0 ?
`(${pctFormat(stats.numNans / stats.numVals)})` :
'';
}
vals.push(`${format(stats.numNans)} ${nanPct}`);
}
if (stats.numInfs != null) {
headers.push('# Infinity');
let infPct = '';
if (stats.numVals) {
infPct = stats.numInfs > 0 ?
`(${pctFormat(stats.numInfs / stats.numVals)})` :
'';
}
vals.push(`${format(stats.numInfs)} ${infPct}`);
}
table_1.table(container, { headers, values: [vals] }, opts);
}
/**
* Formats data to the internal format used by this chart.
*/
function prepareData(data) {
if (data.length == null) {
throw new Error('input data must be an array');
}
if (data.length === 0) {
return [];
}
else if (typeof data[0] === 'object') {
if (data[0].value == null) {
throw new Error('input data must have a value field');
}
else {
return data;
}
}
else {
const ret = Array(data.length);
for (let i = 0; i < data.length; i++) {
ret[i] = { value: data[i] };
}
return ret;
}
}
//# sourceMappingURL=histogram.js.map
/***/ }),
/* 155 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return h; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createElement", function() { return h; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cloneElement", function() { return cloneElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return Component; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rerender", function() { return rerender; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "options", function() { return options; });
/** Virtual DOM Node */
function VNode() {}
/** Global options
* @public
* @namespace options {Object}
*/
var options = {
/** If `true`, `prop` changes trigger synchronous component updates.
* @name syncComponentUpdates
* @type Boolean
* @default true
*/
//syncComponentUpdates: true,
/** Processes all created VNodes.
* @param {VNode} vnode A newly-created VNode to normalize/process
*/
//vnode(vnode) { }
/** Hook invoked after a component is mounted. */
// afterMount(component) { }
/** Hook invoked after the DOM is updated with a component's latest render. */
// afterUpdate(component) { }
/** Hook invoked immediately before a component is unmounted. */
// beforeUnmount(component) { }
};
var stack = [];
var EMPTY_CHILDREN = [];
/**
* JSX/hyperscript reviver.
* @see http://jasonformat.com/wtf-is-jsx
* Benchmarks: https://esbench.com/bench/57ee8f8e330ab09900a1a1a0
*
* Note: this is exported as both `h()` and `createElement()` for compatibility reasons.
*
* Creates a VNode (virtual DOM element). A tree of VNodes can be used as a lightweight representation
* of the structure of a DOM tree. This structure can be realized by recursively comparing it against
* the current _actual_ DOM structure, and applying only the differences.
*
* `h()`/`createElement()` accepts an element name, a list of attributes/props,
* and optionally children to append to the element.
*
* @example The following DOM tree
*
* `<div id="foo" name="bar">Hello!</div>`
*
* can be constructed using this function as:
*
* `h('div', { id: 'foo', name : 'bar' }, 'Hello!');`
*
* @param {string} nodeName An element name. Ex: `div`, `a`, `span`, etc.
* @param {Object} attributes Any attributes/props to set on the created element.
* @param rest Additional arguments are taken to be children to append. Can be infinitely nested Arrays.
*
* @public
*/
function h(nodeName, attributes) {
var children = EMPTY_CHILDREN,
lastSimple,
child,
simple,
i;
for (i = arguments.length; i-- > 2;) {
stack.push(arguments[i]);
}
if (attributes && attributes.children != null) {
if (!stack.length) stack.push(attributes.children);
delete attributes.children;
}
while (stack.length) {
if ((child = stack.pop()) && child.pop !== undefined) {
for (i = child.length; i--;) {
stack.push(child[i]);
}
} else {
if (typeof child === 'boolean') child = null;
if (simple = typeof nodeName !== 'function') {
if (child == null) child = '';else if (typeof child === 'number') child = String(child);else if (typeof child !== 'string') simple = false;
}
if (simple && lastSimple) {
children[children.length - 1] += child;
} else if (children === EMPTY_CHILDREN) {
children = [child];
} else {
children.push(child);
}
lastSimple = simple;
}
}
var p = new VNode();
p.nodeName = nodeName;
p.children = children;
p.attributes = attributes == null ? undefined : attributes;
p.key = attributes == null ? undefined : attributes.key;
// if a "vnode hook" is defined, pass every created VNode to it
if (options.vnode !== undefined) options.vnode(p);
return p;
}
/**
* Copy all properties from `props` onto `obj`.
* @param {Object} obj Object onto which properties should be copied.
* @param {Object} props Object from which to copy properties.
* @returns obj
* @private
*/
function extend(obj, props) {
for (var i in props) {
obj[i] = props[i];
}return obj;
}
/**
* Call a function asynchronously, as soon as possible. Makes
* use of HTML Promise to schedule the callback if available,
* otherwise falling back to `setTimeout` (mainly for IE<11).
*
* @param {Function} callback
*/
var defer = typeof Promise == 'function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
/**
* Clones the given VNode, optionally adding attributes/props and replacing its children.
* @param {VNode} vnode The virtual DOM element to clone
* @param {Object} props Attributes/props to add when cloning
* @param {VNode} rest Any additional arguments will be used as replacement children.
*/
function cloneElement(vnode, props) {
return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children);
}
// DOM properties that should NOT have "px" added when numeric
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
/** Managed queue of dirty components to be re-rendered */
var items = [];
function enqueueRender(component) {
if (!component._dirty && (component._dirty = true) && items.push(component) == 1) {
(options.debounceRendering || defer)(rerender);
}
}
function rerender() {
var p,
list = items;
items = [];
while (p = list.pop()) {
if (p._dirty) renderComponent(p);
}
}
/**
* Check if two nodes are equivalent.
*
* @param {Node} node DOM Node to compare
* @param {VNode} vnode Virtual DOM node to compare
* @param {boolean} [hydrating=false] If true, ignores component constructors when comparing.
* @private
*/
function isSameNodeType(node, vnode, hydrating) {
if (typeof vnode === 'string' || typeof vnode === 'number') {
return node.splitText !== undefined;
}
if (typeof vnode.nodeName === 'string') {
return !node._componentConstructor && isNamedNode(node, vnode.nodeName);
}
return hydrating || node._componentConstructor === vnode.nodeName;
}
/**
* Check if an Element has a given nodeName, case-insensitively.
*
* @param {Element} node A DOM Element to inspect the name of.
* @param {String} nodeName Unnormalized name to compare against.
*/
function isNamedNode(node, nodeName) {
return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}
/**
* Reconstruct Component-style `props` from a VNode.
* Ensures default/fallback values from `defaultProps`:
* Own-properties of `defaultProps` not present in `vnode.attributes` are added.
*
* @param {VNode} vnode
* @returns {Object} props
*/
function getNodeProps(vnode) {
var props = extend({}, vnode.attributes);
props.children = vnode.children;
var defaultProps = vnode.nodeName.defaultProps;
if (defaultProps !== undefined) {
for (var i in defaultProps) {
if (props[i] === undefined) {
props[i] = defaultProps[i];
}
}
}
return props;
}
/** Create an element with the given nodeName.
* @param {String} nodeName
* @param {Boolean} [isSvg=false] If `true`, creates an element within the SVG namespace.
* @returns {Element} node
*/
function createNode(nodeName, isSvg) {
var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
node.normalizedNodeName = nodeName;
return node;
}
/** Remove a child node from its parent if attached.
* @param {Element} node The node to remove
*/
function removeNode(node) {
var parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
/** Set a named attribute on the given Node, with special behavior for some names and event handlers.
* If `value` is `null`, the attribute/handler will be removed.
* @param {Element} node An element to mutate
* @param {string} name The name/key to set, such as an event or attribute name
* @param {any} old The last value that was set for this name/node pair
* @param {any} value An attribute value, such as a function to be used as an event handler
* @param {Boolean} isSvg Are we currently diffing inside an svg?
* @private
*/
function setAccessor(node, name, old, value, isSvg) {
if (name === 'className') name = 'class';
if (name === 'key') {
// ignore
} else if (name === 'ref') {
if (old) old(null);
if (value) value(node);
} else if (name === 'class' && !isSvg) {
node.className = value || '';
} else if (name === 'style') {
if (!value || typeof value === 'string' || typeof old === 'string') {
node.style.cssText = value || '';
}
if (value && typeof value === 'object') {
if (typeof old !== 'string') {
for (var i in old) {
if (!(i in value)) node.style[i] = '';
}
}
for (var i in value) {
node.style[i] = typeof value[i] === 'number' && IS_NON_DIMENSIONAL.test(i) === false ? value[i] + 'px' : value[i];
}
}
} else if (name === 'dangerouslySetInnerHTML') {
if (value) node.innerHTML = value.__html || '';
} else if (name[0] == 'o' && name[1] == 'n') {
var useCapture = name !== (name = name.replace(/Capture$/, ''));
name = name.toLowerCase().substring(2);
if (value) {
if (!old) node.addEventListener(name, eventProxy, useCapture);
} else {
node.removeEventListener(name, eventProxy, useCapture);
}
(node._listeners || (node._listeners = {}))[name] = value;
} else if (name !== 'list' && name !== 'type' && !isSvg && name in node) {
setProperty(node, name, value == null ? '' : value);
if (value == null || value === false) node.removeAttribute(name);
} else {
var ns = isSvg && name !== (name = name.replace(/^xlink:?/, ''));
if (value == null || value === false) {
if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase());else node.removeAttribute(name);
} else if (typeof value !== 'function') {
if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value);else node.setAttribute(name, value);
}
}
}
/** Attempt to set a DOM property to the given value.
* IE & FF throw for certain property-value combinations.
*/
function setProperty(node, name, value) {
try {
node[name] = value;
} catch (e) {}
}
/** Proxy an event to hooked event handlers
* @private
*/
function eventProxy(e) {
return this._listeners[e.type](options.event && options.event(e) || e);
}
/** Queue of components that have been mounted and are awaiting componentDidMount */
var mounts = [];
/** Diff recursion count, used to track the end of the diff cycle. */
var diffLevel = 0;
/** Global flag indicating if the diff is currently within an SVG */
var isSvgMode = false;
/** Global flag indicating if the diff is performing hydration */
var hydrating = false;
/** Invoke queued componentDidMount lifecycle methods */
function flushMounts() {
var c;
while (c = mounts.pop()) {
if (options.afterMount) options.afterMount(c);
if (c.componentDidMount) c.componentDidMount();
}
}
/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
* @param {Element} [dom=null] A DOM node to mutate into the shape of the `vnode`
* @param {VNode} vnode A VNode (with descendants forming a tree) representing the desired DOM structure
* @returns {Element} dom The created/mutated element
* @private
*/
function diff(dom, vnode, context, mountAll, parent, componentRoot) {
// diffLevel having been 0 here indicates initial entry into the diff (not a subdiff)
if (!diffLevel++) {
// when first starting the diff, check if we're diffing an SVG or within an SVG
isSvgMode = parent != null && parent.ownerSVGElement !== undefined;
// hydration is indicated by the existing element to be diffed not having a prop cache
hydrating = dom != null && !('__preactattr_' in dom);
}
var ret = idiff(dom, vnode, context, mountAll, componentRoot);
// append the element if its a new parent
if (parent && ret.parentNode !== parent) parent.appendChild(ret);
// diffLevel being reduced to 0 means we're exiting the diff
if (! --diffLevel) {
hydrating = false;
// invoke queued componentDidMount lifecycle methods
if (!componentRoot) flushMounts();
}
return ret;
}
/** Internals of `diff()`, separated to allow bypassing diffLevel / mount flushing. */
function idiff(dom, vnode, context, mountAll, componentRoot) {
var out = dom,
prevSvgMode = isSvgMode;
// empty values (null, undefined, booleans) render as empty Text nodes
if (vnode == null || typeof vnode === 'boolean') vnode = '';
// Fast case: Strings & Numbers create/update Text nodes.
if (typeof vnode === 'string' || typeof vnode === 'number') {
// update if it's already a Text node:
if (dom && dom.splitText !== undefined && dom.parentNode && (!dom._component || componentRoot)) {
/* istanbul ignore if */ /* Browser quirk that can't be covered: https://github.com/developit/preact/commit/fd4f21f5c45dfd75151bd27b4c217d8003aa5eb9 */
if (dom.nodeValue != vnode) {
dom.nodeValue = vnode;
}
} else {
// it wasn't a Text node: replace it with one and recycle the old Element
out = document.createTextNode(vnode);
if (dom) {
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, true);
}
}
out['__preactattr_'] = true;
return out;
}
// If the VNode represents a Component, perform a component diff:
var vnodeName = vnode.nodeName;
if (typeof vnodeName === 'function') {
return buildComponentFromVNode(dom, vnode, context, mountAll);
}
// Tracks entering and exiting SVG namespace when descending through the tree.
isSvgMode = vnodeName === 'svg' ? true : vnodeName === 'foreignObject' ? false : isSvgMode;
// If there's no existing element or it's the wrong type, create a new one:
vnodeName = String(vnodeName);
if (!dom || !isNamedNode(dom, vnodeName)) {
out = createNode(vnodeName, isSvgMode);
if (dom) {
// move children into the replacement node
while (dom.firstChild) {
out.appendChild(dom.firstChild);
} // if the previous Element was mounted into the DOM, replace it inline
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
// recycle the old element (skips non-Element node types)
recollectNodeTree(dom, true);
}
}
var fc = out.firstChild,
props = out['__preactattr_'],
vchildren = vnode.children;
if (props == null) {
props = out['__preactattr_'] = {};
for (var a = out.attributes, i = a.length; i--;) {
props[a[i].name] = a[i].value;
}
}
// Optimization: fast-path for elements containing a single TextNode:
if (!hydrating && vchildren && vchildren.length === 1 && typeof vchildren[0] === 'string' && fc != null && fc.splitText !== undefined && fc.nextSibling == null) {
if (fc.nodeValue != vchildren[0]) {
fc.nodeValue = vchildren[0];
}
}
// otherwise, if there are existing or new children, diff them:
else if (vchildren && vchildren.length || fc != null) {
innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML != null);
}
// Apply attributes/props from VNode to the DOM Element:
diffAttributes(out, vnode.attributes, props);
// restore previous SVG mode: (in case we're exiting an SVG namespace)
isSvgMode = prevSvgMode;
return out;
}
/** Apply child and attribute changes between a VNode and a DOM Node to the DOM.
* @param {Element} dom Element whose children should be compared & mutated
* @param {Array} vchildren Array of VNodes to compare to `dom.childNodes`
* @param {Object} context Implicitly descendant context object (from most recent `getChildContext()`)
* @param {Boolean} mountAll
* @param {Boolean} isHydrating If `true`, consumes externally created elements similar to hydration
*/
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
var originalChildren = dom.childNodes,
children = [],
keyed = {},
keyedLen = 0,
min = 0,
len = originalChildren.length,
childrenLen = 0,
vlen = vchildren ? vchildren.length : 0,
j,
c,
f,
vchild,
child;
// Build up a map of keyed children and an Array of unkeyed children:
if (len !== 0) {
for (var i = 0; i < len; i++) {
var _child = originalChildren[i],
props = _child['__preactattr_'],
key = vlen && props ? _child._component ? _child._component.__key : props.key : null;
if (key != null) {
keyedLen++;
keyed[key] = _child;
} else if (props || (_child.splitText !== undefined ? isHydrating ? _child.nodeValue.trim() : true : isHydrating)) {
children[childrenLen++] = _child;
}
}
}
if (vlen !== 0) {
for (var i = 0; i < vlen; i++) {
vchild = vchildren[i];
child = null;
// attempt to find a node based on key matching
var key = vchild.key;
if (key != null) {
if (keyedLen && keyed[key] !== undefined) {
child = keyed[key];
keyed[key] = undefined;
keyedLen--;
}
}
// attempt to pluck a node of the same type from the existing children
else if (!child && min < childrenLen) {
for (j = min; j < childrenLen; j++) {
if (children[j] !== undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
child = c;
children[j] = undefined;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
}
}
// morph the matched/found/created DOM child to match vchild (deep)
child = idiff(child, vchild, context, mountAll);
f = originalChildren[i];
if (child && child !== dom && child !== f) {
if (f == null) {
dom.appendChild(child);
} else if (child === f.nextSibling) {
removeNode(f);
} else {
dom.insertBefore(child, f);
}
}
}
}
// remove unused keyed children:
if (keyedLen) {
for (var i in keyed) {
if (keyed[i] !== undefined) recollectNodeTree(keyed[i], false);
}
}
// remove orphaned unkeyed children:
while (min <= childrenLen) {
if ((child = children[childrenLen--]) !== undefined) recollectNodeTree(child, false);
}
}
/** Recursively recycle (or just unmount) a node and its descendants.
* @param {Node} node DOM node to start unmount/removal from
* @param {Boolean} [unmountOnly=false] If `true`, only triggers unmount lifecycle, skips removal
*/
function recollectNodeTree(node, unmountOnly) {
var component = node._component;
if (component) {
// if node is owned by a Component, unmount that component (ends up recursing back here)
unmountComponent(component);
} else {
// If the node's VNode had a ref function, invoke it with null here.
// (this is part of the React spec, and smart for unsetting references)
if (node['__preactattr_'] != null && node['__preactattr_'].ref) node['__preactattr_'].ref(null);
if (unmountOnly === false || node['__preactattr_'] == null) {
removeNode(node);
}
removeChildren(node);
}
}
/** Recollect/unmount all children.
* - we use .lastChild here because it causes less reflow than .firstChild
* - it's also cheaper than accessing the .childNodes Live NodeList
*/
function removeChildren(node) {
node = node.lastChild;
while (node) {
var next = node.previousSibling;
recollectNodeTree(node, true);
node = next;
}
}
/** Apply differences in attributes from a VNode to the given DOM Element.
* @param {Element} dom Element with attributes to diff `attrs` against
* @param {Object} attrs The desired end-state key-value attribute pairs
* @param {Object} old Current/previous attributes (from previous VNode or element's prop cache)
*/
function diffAttributes(dom, attrs, old) {
var name;
// remove attributes no longer present on the vnode by setting them to undefined
for (name in old) {
if (!(attrs && attrs[name] != null) && old[name] != null) {
setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
}
}
// add new & update changed attributes
for (name in attrs) {
if (name !== 'children' && name !== 'innerHTML' && (!(name in old) || attrs[name] !== (name === 'value' || name === 'checked' ? dom[name] : old[name]))) {
setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
}
}
}
/** Retains a pool of Components for re-use, keyed on component name.
* Note: since component names are not unique or even necessarily available, these are primarily a form of sharding.
* @private
*/
var components = {};
/** Reclaim a component for later re-use by the recycler. */
function collectComponent(component) {
var name = component.constructor.name;
(components[name] || (components[name] = [])).push(component);
}
/** Create a component. Normalizes differences between PFC's and classful Components. */
function createComponent(Ctor, props, context) {
var list = components[Ctor.name],
inst;
if (Ctor.prototype && Ctor.prototype.render) {
inst = new Ctor(props, context);
Component.call(inst, props, context);
} else {
inst = new Component(props, context);
inst.constructor = Ctor;
inst.render = doRender;
}
if (list) {
for (var i = list.length; i--;) {
if (list[i].constructor === Ctor) {
inst.nextBase = list[i].nextBase;
list.splice(i, 1);
break;
}
}
}
return inst;
}
/** The `.render()` method for a PFC backing instance. */
function doRender(props, state, context) {
return this.constructor(props, context);
}
/** Set a component's `props` (generally derived from JSX attributes).
* @param {Object} props
* @param {Object} [opts]
* @param {boolean} [opts.renderSync=false] If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
* @param {boolean} [opts.render=true] If `false`, no render will be triggered.
*/
function setComponentProps(component, props, opts, context, mountAll) {
if (component._disable) return;
component._disable = true;
if (component.__ref = props.ref) delete props.ref;
if (component.__key = props.key) delete props.key;
if (!component.base || mountAll) {
if (component.componentWillMount) component.componentWillMount();
} else if (component.componentWillReceiveProps) {
component.componentWillReceiveProps(props, context);
}
if (context && context !== component.context) {
if (!component.prevContext) component.prevContext = component.context;
component.context = context;
}
if (!component.prevProps) component.prevProps = component.props;
component.props = props;
component._disable = false;
if (opts !== 0) {
if (opts === 1 || options.syncComponentUpdates !== false || !component.base) {
renderComponent(component, 1, mountAll);
} else {
enqueueRender(component);
}
}
if (component.__ref) component.__ref(component);
}
/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
* @param {Component} component
* @param {Object} [opts]
* @param {boolean} [opts.build=false] If `true`, component will build and store a DOM node if not already associated with one.
* @private
*/
function renderComponent(component, opts, mountAll, isChild) {
if (component._disable) return;
var props = component.props,
state = component.state,
context = component.context,
previousProps = component.prevProps || props,
previousState = component.prevState || state,
previousContext = component.prevContext || context,
isUpdate = component.base,
nextBase = component.nextBase,
initialBase = isUpdate || nextBase,
initialChildComponent = component._component,
skip = false,
rendered,
inst,
cbase;
// if updating
if (isUpdate) {
component.props = previousProps;
component.state = previousState;
component.context = previousContext;
if (opts !== 2 && component.shouldComponentUpdate && component.shouldComponentUpdate(props, state, context) === false) {
skip = true;
} else if (component.componentWillUpdate) {
component.componentWillUpdate(props, state, context);
}
component.props = props;
component.state = state;
component.context = context;
}
component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
component._dirty = false;
if (!skip) {
rendered = component.render(props, state, context);
// context to pass to the child, can be updated via (grand-)parent component
if (component.getChildContext) {
context = extend(extend({}, context), component.getChildContext());
}
var childComponent = rendered && rendered.nodeName,
toUnmount,
base;
if (typeof childComponent === 'function') {
// set up high order component link
var childProps = getNodeProps(rendered);
inst = initialChildComponent;
if (inst && inst.constructor === childComponent && childProps.key == inst.__key) {
setComponentProps(inst, childProps, 1, context, false);
} else {
toUnmount = inst;
component._component = inst = createComponent(childComponent, childProps, context);
inst.nextBase = inst.nextBase || nextBase;
inst._parentComponent = component;
setComponentProps(inst, childProps, 0, context, false);
renderComponent(inst, 1, mountAll, true);
}
base = inst.base;
} else {
cbase = initialBase;
// destroy high order component link
toUnmount = initialChildComponent;
if (toUnmount) {
cbase = component._component = null;
}
if (initialBase || opts === 1) {
if (cbase) cbase._component = null;
base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, true);
}
}
if (initialBase && base !== initialBase && inst !== initialChildComponent) {
var baseParent = initialBase.parentNode;
if (baseParent && base !== baseParent) {
baseParent.replaceChild(base, initialBase);
if (!toUnmount) {
initialBase._component = null;
recollectNodeTree(initialBase, false);
}
}
}
if (toUnmount) {
unmountComponent(toUnmount);
}
component.base = base;
if (base && !isChild) {
var componentRef = component,
t = component;
while (t = t._parentComponent) {
(componentRef = t).base = base;
}
base._component = componentRef;
base._componentConstructor = componentRef.constructor;
}
}
if (!isUpdate || mountAll) {
mounts.unshift(component);
} else if (!skip) {
// Ensure that pending componentDidMount() hooks of child components
// are called before the componentDidUpdate() hook in the parent.
// Note: disabled as it causes duplicate hooks, see https://github.com/developit/preact/issues/750
// flushMounts();
if (component.componentDidUpdate) {
component.componentDidUpdate(previousProps, previousState, previousContext);
}
if (options.afterUpdate) options.afterUpdate(component);
}
if (component._renderCallbacks != null) {
while (component._renderCallbacks.length) {
component._renderCallbacks.pop().call(component);
}
}
if (!diffLevel && !isChild) flushMounts();
}
/** Apply the Component referenced by a VNode to the DOM.
* @param {Element} dom The DOM node to mutate
* @param {VNode} vnode A Component-referencing VNode
* @returns {Element} dom The created/mutated element
* @private
*/
function buildComponentFromVNode(dom, vnode, context, mountAll) {
var c = dom && dom._component,
originalComponent = c,
oldDom = dom,
isDirectOwner = c && dom._componentConstructor === vnode.nodeName,
isOwner = isDirectOwner,
props = getNodeProps(vnode);
while (c && !isOwner && (c = c._parentComponent)) {
isOwner = c.constructor === vnode.nodeName;
}
if (c && isOwner && (!mountAll || c._component)) {
setComponentProps(c, props, 3, context, mountAll);
dom = c.base;
} else {
if (originalComponent && !isDirectOwner) {
unmountComponent(originalComponent);
dom = oldDom = null;
}
c = createComponent(vnode.nodeName, props, context);
if (dom && !c.nextBase) {
c.nextBase = dom;
// passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L229:
oldDom = null;
}
setComponentProps(c, props, 1, context, mountAll);
dom = c.base;
if (oldDom && dom !== oldDom) {
oldDom._component = null;
recollectNodeTree(oldDom, false);
}
}
return dom;
}
/** Remove a component from the DOM and recycle it.
* @param {Component} component The Component instance to unmount
* @private
*/
function unmountComponent(component) {
if (options.beforeUnmount) options.beforeUnmount(component);
var base = component.base;
component._disable = true;
if (component.componentWillUnmount) component.componentWillUnmount();
component.base = null;
// recursively tear down & recollect high-order component children:
var inner = component._component;
if (inner) {
unmountComponent(inner);
} else if (base) {
if (base['__preactattr_'] && base['__preactattr_'].ref) base['__preactattr_'].ref(null);
component.nextBase = base;
removeNode(base);
collectComponent(component);
removeChildren(base);
}
if (component.__ref) component.__ref(null);
}
/** Base Component class.
* Provides `setState()` and `forceUpdate()`, which trigger rendering.
* @public
*
* @example
* class MyFoo extends Component {
* render(props, state) {
* return <div />;
* }
* }
*/
function Component(props, context) {
this._dirty = true;
/** @public
* @type {object}
*/
this.context = context;
/** @public
* @type {object}
*/
this.props = props;
/** @public
* @type {object}
*/
this.state = this.state || {};
}
extend(Component.prototype, {
/** Returns a `boolean` indicating if the component should re-render when receiving the given `props` and `state`.
* @param {object} nextProps
* @param {object} nextState
* @param {object} nextContext
* @returns {Boolean} should the component re-render
* @name shouldComponentUpdate
* @function
*/
/** Update component state by copying properties from `state` to `this.state`.
* @param {object} state A hash of state properties to update with new values
* @param {function} callback A function to be called once component state is updated
*/
setState: function setState(state, callback) {
var s = this.state;
if (!this.prevState) this.prevState = extend({}, s);
extend(s, typeof state === 'function' ? state(s, this.props) : state);
if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback);
enqueueRender(this);
},
/** Immediately perform a synchronous re-render of the component.
* @param {function} callback A function to be called after component is re-rendered.
* @private
*/
forceUpdate: function forceUpdate(callback) {
if (callback) (this._renderCallbacks = this._renderCallbacks || []).push(callback);
renderComponent(this, 2);
},
/** Accepts `props` and `state`, and returns a new Virtual DOM tree to build.
* Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).
* @param {object} props Props (eg: JSX attributes) received from parent element/component
* @param {object} state The component's current state
* @param {object} context Context object (if a parent component has provided context)
* @returns VNode
*/
render: function render() {}
});
/** Render JSX into a `parent` Element.
* @param {VNode} vnode A (JSX) VNode to render
* @param {Element} parent DOM element to render into
* @param {Element} [merge] Attempt to re-use an existing DOM tree rooted at `merge`
* @public
*
* @example
* // render a div into <body>:
* render(<div id="hello">hello!</div>, document.body);
*
* @example
* // render a "Thing" component into #foo:
* const Thing = ({ name }) => <span>{ name }</span>;
* render(<Thing name="one" />, document.querySelector('#foo'));
*/
function render(vnode, parent, merge) {
return diff(merge, vnode, {}, false, parent, false);
}
var preact = {
h: h,
createElement: h,
cloneElement: cloneElement,
Component: Component,
render: render,
rerender: rerender,
options: options
};
/* harmony default export */ __webpack_exports__["default"] = (preact);
//# sourceMappingURL=preact.esm.js.map
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ }),
/* 157 */
/***/ (function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ }),
/* 158 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__(18);
var global = __webpack_require__(26);
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: __webpack_require__(106) ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(159)('keys');
var uid = __webpack_require__(121);
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 161 */
/***/ (function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ }),
/* 162 */
/***/ (function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(107);
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(38);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(38);
var document = __webpack_require__(26).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(11);
var DESCRIPTORS = __webpack_require__(19);
var LIBRARY = __webpack_require__(63);
var $typed = __webpack_require__(126);
var hide = __webpack_require__(31);
var redefineAll = __webpack_require__(70);
var fails = __webpack_require__(12);
var anInstance = __webpack_require__(72);
var toInteger = __webpack_require__(41);
var toLength = __webpack_require__(17);
var toIndex = __webpack_require__(254);
var gOPN = __webpack_require__(74).f;
var dP = __webpack_require__(21).f;
var arrayFill = __webpack_require__(173);
var setToStringTag = __webpack_require__(94);
var ARRAY_BUFFER = 'ArrayBuffer';
var DATA_VIEW = 'DataView';
var PROTOTYPE = 'prototype';
var WRONG_LENGTH = 'Wrong length!';
var WRONG_INDEX = 'Wrong index!';
var $ArrayBuffer = global[ARRAY_BUFFER];
var $DataView = global[DATA_VIEW];
var Math = global.Math;
var RangeError = global.RangeError;
// eslint-disable-next-line no-shadow-restricted-names
var Infinity = global.Infinity;
var BaseBuffer = $ArrayBuffer;
var abs = Math.abs;
var pow = Math.pow;
var floor = Math.floor;
var log = Math.log;
var LN2 = Math.LN2;
var BUFFER = 'buffer';
var BYTE_LENGTH = 'byteLength';
var BYTE_OFFSET = 'byteOffset';
var $BUFFER = DESCRIPTORS ? '_b' : BUFFER;
var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH;
var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
function packIEEE754(value, mLen, nBytes) {
var buffer = new Array(nBytes);
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0;
var i = 0;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
var e, m, c;
value = abs(value);
// eslint-disable-next-line no-self-compare
if (value != value || value === Infinity) {
// eslint-disable-next-line no-self-compare
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if (value * (c = pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
}
function unpackIEEE754(buffer, mLen, nBytes) {
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = eLen - 7;
var i = nBytes - 1;
var s = buffer[i--];
var e = s & 127;
var m;
s >>= 7;
for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
}
function unpackI32(bytes) {
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
}
function packI8(it) {
return [it & 0xff];
}
function packI16(it) {
return [it & 0xff, it >> 8 & 0xff];
}
function packI32(it) {
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
}
function packF64(it) {
return packIEEE754(it, 52, 8);
}
function packF32(it) {
return packIEEE754(it, 23, 4);
}
function addGetter(C, key, internal) {
dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } });
}
function get(view, bytes, index, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
}
function set(view, bytes, index, conversion, value, isLittleEndian) {
var numIndex = +index;
var intIndex = toIndex(numIndex);
if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b;
var start = intIndex + view[$OFFSET];
var pack = conversion(+value);
for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
}
if (!$typed.ABV) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer, ARRAY_BUFFER);
var byteLength = toIndex(length);
this._b = arrayFill.call(new Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength) {
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH];
var offset = toInteger(byteOffset);
if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if (DESCRIPTORS) {
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset) {
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset) {
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /* , littleEndian */) {
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /* , littleEndian */) {
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /* , littleEndian */) {
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value) {
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /* , littleEndian */) {
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if (!fails(function () {
$ArrayBuffer(1);
}) || !fails(function () {
new $ArrayBuffer(-1); // eslint-disable-line no-new
}) || fails(function () {
new $ArrayBuffer(); // eslint-disable-line no-new
new $ArrayBuffer(1.5); // eslint-disable-line no-new
new $ArrayBuffer(NaN); // eslint-disable-line no-new
return $ArrayBuffer.name != ARRAY_BUFFER;
})) {
$ArrayBuffer = function ArrayBuffer(length) {
anInstance(this, $ArrayBuffer);
return new BaseBuffer(toIndex(length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) {
if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]);
}
if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2));
var $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value) {
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = __webpack_require__(27);
function PromiseCapability(C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var macrotask = __webpack_require__(169).set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __webpack_require__(42)(process) == 'process';
module.exports = function () {
var head, last, notify;
var flush = function () {
var parent, fn;
if (isNode && (parent = process.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (e) {
if (head) notify();
else last = undefined;
throw e;
}
} last = undefined;
if (parent) parent.enter();
};
// Node.js
if (isNode) {
notify = function () {
process.nextTick(flush);
};
// browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
} else if (Observer && !(global.navigator && global.navigator.standalone)) {
var toggle = true;
var node = document.createTextNode('');
new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (Promise && Promise.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
var promise = Promise.resolve(undefined);
notify = function () {
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
};
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(43);
var invoke = __webpack_require__(274);
var html = __webpack_require__(188);
var cel = __webpack_require__(192);
var global = __webpack_require__(11);
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
setTask = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (__webpack_require__(42)(process) == 'process') {
defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if (MessageChannel) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in cel('script')) {
defer = function (id) {
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var at = __webpack_require__(133)(true);
// `AdvanceStringIndex` abstract operation
// https://tc39.github.io/ecma262/#sec-advancestringindex
module.exports = function (S, index, unicode) {
return index + (unicode ? at(S, index).length : 1);
};
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var regexpFlags = __webpack_require__(111);
var nativeExec = RegExp.prototype.exec;
// This always refers to the native implementation, because the
// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
// which loads this file before patching the method.
var nativeReplace = String.prototype.replace;
var patchedExec = nativeExec;
var LAST_INDEX = 'lastIndex';
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/,
re2 = /b*/g;
nativeExec.call(re1, 'a');
nativeExec.call(re2, 'a');
return re1[LAST_INDEX] !== 0 || re2[LAST_INDEX] !== 0;
})();
// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
if (PATCH) {
patchedExec = function exec(str) {
var re = this;
var lastIndex, reCopy, match, i;
if (NPCG_INCLUDED) {
reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
}
if (UPDATES_LAST_INDEX_WRONG) lastIndex = re[LAST_INDEX];
match = nativeExec.call(re, str);
if (UPDATES_LAST_INDEX_WRONG && match) {
re[LAST_INDEX] = re.global ? match.index + match[0].length : lastIndex;
}
if (NPCG_INCLUDED && match && match.length > 1) {
// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
// eslint-disable-next-line no-loop-func
nativeReplace.call(match[0], reCopy, function () {
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) match[i] = undefined;
}
});
}
return match;
};
}
module.exports = patchedExec;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__(61);
var step = __webpack_require__(264);
var Iterators = __webpack_require__(91);
var toIObject = __webpack_require__(35);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(181)(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var toObject = __webpack_require__(22);
var toAbsoluteIndex = __webpack_require__(76);
var toLength = __webpack_require__(17);
module.exports = function fill(value /* , start = 0, end = @length */) {
var O = toObject(this);
var length = toLength(O.length);
var aLen = arguments.length;
var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length);
var end = aLen > 2 ? arguments[2] : undefined;
var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
while (endPos > index) O[index++] = value;
return O;
};
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(600);
module.exports = function (original, length) {
return new (speciesConstructor(original))(length);
};
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(93);
var ITERATOR = __webpack_require__(16)('iterator');
var Iterators = __webpack_require__(91);
module.exports = __webpack_require__(44).getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__(21);
var createDesc = __webpack_require__(79);
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(91);
var ITERATOR = __webpack_require__(16)('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(16)('match');
module.exports = function (KEY) {
var re = /./;
try {
'/./'[KEY](re);
} catch (e) {
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch (f) { /* empty */ }
} return true;
};
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(132);
var defined = __webpack_require__(51);
module.exports = function (that, searchString, NAME) {
if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var create = __webpack_require__(75);
var descriptor = __webpack_require__(79);
var setToStringTag = __webpack_require__(94);
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(31)(IteratorPrototype, __webpack_require__(16)('iterator'), function () { return this; });
module.exports = function (Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(63);
var $export = __webpack_require__(5);
var redefine = __webpack_require__(30);
var hide = __webpack_require__(31);
var Iterators = __webpack_require__(91);
var $iterCreate = __webpack_require__(180);
var setToStringTag = __webpack_require__(94);
var getPrototypeOf = __webpack_require__(33);
var ITERATOR = __webpack_require__(16)('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ }),
/* 182 */
/***/ (function(module, exports) {
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x) {
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
/***/ }),
/* 183 */
/***/ (function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var toInteger = __webpack_require__(41);
var defined = __webpack_require__(51);
module.exports = function repeat(count) {
var str = String(defined(this));
var res = '';
var n = toInteger(count);
if (n < 0 || n == Infinity) throw RangeError("Count can't be negative");
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str;
return res;
};
/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
var setPrototypeOf = __webpack_require__(187).set;
module.exports = function (that, target, C) {
var S = target.constructor;
var P;
if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) {
setPrototypeOf(that, P);
} return that;
};
/***/ }),
/* 186 */
/***/ (function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(13);
var anObject = __webpack_require__(6);
var check = function (O, proto) {
anObject(O);
if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = __webpack_require__(43)(Function.call, __webpack_require__(34).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__(11).document;
module.exports = document && document.documentElement;
/***/ }),
/* 189 */
/***/ (function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
var shared = __webpack_require__(114)('keys');
var uid = __webpack_require__(78);
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var core = __webpack_require__(44);
var LIBRARY = __webpack_require__(63);
var wksExt = __webpack_require__(281);
var defineProperty = __webpack_require__(21).f;
module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
var document = __webpack_require__(11).document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
/***/ }),
/* 193 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isNodejs; });
function isNodejs() {
return typeof global === 'object'
&& "function" === 'function'
&& typeof module !== 'undefined'
// issues with gatsby.js: module.exports is undefined
// && !!module.exports
&& typeof process !== 'undefined' && !!process.version;
}
//# sourceMappingURL=isNodejs.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53), __webpack_require__(87)))
/***/ }),
/* 194 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createNodejsEnv; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _createFileSystem__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(138);
function createNodejsEnv() {
var Canvas = global['Canvas'] || global['HTMLCanvasElement'];
var Image = global['Image'] || global['HTMLImageElement'];
var createCanvasElement = function () {
if (Canvas) {
return new Canvas();
}
throw new Error('createCanvasElement - missing Canvas implementation for nodejs environment');
};
var createImageElement = function () {
if (Image) {
return new Image();
}
throw new Error('createImageElement - missing Image implementation for nodejs environment');
};
var fetch = global['fetch'] || function () {
throw new Error('fetch - missing fetch implementation for nodejs environment');
};
var fileSystem = Object(_createFileSystem__WEBPACK_IMPORTED_MODULE_1__[/* createFileSystem */ "a"])();
return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[/* __assign */ "a"])({ Canvas: Canvas || /** @class */ (function () {
function Canvas() {
}
return Canvas;
}()), CanvasRenderingContext2D: global['CanvasRenderingContext2D'] || /** @class */ (function () {
function class_1() {
}
return class_1;
}()), Image: Image || /** @class */ (function () {
function Image() {
}
return Image;
}()), ImageData: global['ImageData'] || /** @class */ (function () {
function class_2() {
}
return class_2;
}()), Video: global['HTMLVideoElement'] || /** @class */ (function () {
function class_3() {
}
return class_3;
}()), createCanvasElement: createCanvasElement,
createImageElement: createImageElement,
fetch: fetch }, fileSystem);
}
//# sourceMappingURL=createNodejsEnv.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53)))
/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Parse a vega schema url into library and version.
*/
function default_1(url) {
var regex = /\/schema\/([\w-]+)\/([\w\.\-]+)\.json$/g;
var _a = regex.exec(url).slice(1, 3), library = _a[0], version = _a[1];
return { library: library, version: version };
}
exports.default = default_1;
//# sourceMappingURL=index.js.map
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {exports = module.exports = SemVer
var debug
/* istanbul ignore next */
if (typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)) {
debug = function () {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift('SEMVER')
console.log.apply(console, args)
}
} else {
debug = function () {}
}
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
exports.SEMVER_SPEC_VERSION = '2.0.0'
var MAX_LENGTH = 256
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
var MAX_SAFE_COMPONENT_LENGTH = 16
// The actual regexps go on exports.re
var re = exports.re = []
var src = exports.src = []
var t = exports.tokens = {}
var R = 0
function tok (n) {
t[n] = R++
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
tok('NUMERICIDENTIFIER')
src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*'
tok('NUMERICIDENTIFIERLOOSE')
src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
tok('NONNUMERICIDENTIFIER')
src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'
// ## Main Version
// Three dot-separated numeric identifiers.
tok('MAINVERSION')
src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIER] + ')'
tok('MAINVERSIONLOOSE')
src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
'(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
tok('PRERELEASEIDENTIFIER')
src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
'|' + src[t.NONNUMERICIDENTIFIER] + ')'
tok('PRERELEASEIDENTIFIERLOOSE')
src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
'|' + src[t.NONNUMERICIDENTIFIER] + ')'
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
tok('PRERELEASE')
src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
'(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))'
tok('PRERELEASELOOSE')
src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
'(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
tok('BUILDIDENTIFIER')
src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
tok('BUILD')
src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
'(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
tok('FULL')
tok('FULLPLAIN')
src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
src[t.PRERELEASE] + '?' +
src[t.BUILD] + '?'
src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
tok('LOOSEPLAIN')
src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] +
src[t.PRERELEASELOOSE] + '?' +
src[t.BUILD] + '?'
tok('LOOSE')
src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$'
tok('GTLT')
src[t.GTLT] = '((?:<|>)?=?)'
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
tok('XRANGEIDENTIFIERLOOSE')
src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'
tok('XRANGEIDENTIFIER')
src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*'
tok('XRANGEPLAIN')
src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
'(?:' + src[t.PRERELEASE] + ')?' +
src[t.BUILD] + '?' +
')?)?'
tok('XRANGEPLAINLOOSE')
src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
'(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
'(?:' + src[t.PRERELEASELOOSE] + ')?' +
src[t.BUILD] + '?' +
')?)?'
tok('XRANGE')
src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$'
tok('XRANGELOOSE')
src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
tok('COERCE')
src[t.COERCE] = '(^|[^\\d])' +
'(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
'(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
'(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
'(?:$|[^\\d])'
tok('COERCERTL')
re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g')
// Tilde ranges.
// Meaning is "reasonably at or greater than"
tok('LONETILDE')
src[t.LONETILDE] = '(?:~>?)'
tok('TILDETRIM')
src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+'
re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g')
var tildeTrimReplace = '$1~'
tok('TILDE')
src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'
tok('TILDELOOSE')
src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'
// Caret ranges.
// Meaning is "at least and backwards compatible with"
tok('LONECARET')
src[t.LONECARET] = '(?:\\^)'
tok('CARETTRIM')
src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+'
re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g')
var caretTrimReplace = '$1^'
tok('CARET')
src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$'
tok('CARETLOOSE')
src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'
// A simple gt/lt/eq thing, or just "" to indicate "any version"
tok('COMPARATORLOOSE')
src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$'
tok('COMPARATOR')
src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$'
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
tok('COMPARATORTRIM')
src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] +
'\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'
// this one has to use the /g flag
re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g')
var comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
tok('HYPHENRANGE')
src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' +
'\\s+-\\s+' +
'(' + src[t.XRANGEPLAIN] + ')' +
'\\s*$'
tok('HYPHENRANGELOOSE')
src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
'\\s+-\\s+' +
'(' + src[t.XRANGEPLAINLOOSE] + ')' +
'\\s*$'
// Star ranges basically just allow anything at all.
tok('STAR')
src[t.STAR] = '(<|>)?=?\\s*\\*'
// Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
for (var i = 0; i < R; i++) {
debug(i, src[i])
if (!re[i]) {
re[i] = new RegExp(src[i])
}
}
exports.parse = parse
function parse (version, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (version instanceof SemVer) {
return version
}
if (typeof version !== 'string') {
return null
}
if (version.length > MAX_LENGTH) {
return null
}
var r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
try {
return new SemVer(version, options)
} catch (er) {
return null
}
}
exports.valid = valid
function valid (version, options) {
var v = parse(version, options)
return v ? v.version : null
}
exports.clean = clean
function clean (version, options) {
var s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
exports.SemVer = SemVer
function SemVer (version, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (version instanceof SemVer) {
if (version.loose === options.loose) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError('Invalid Version: ' + version)
}
if (version.length > MAX_LENGTH) {
throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
}
if (!(this instanceof SemVer)) {
return new SemVer(version, options)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError('Invalid Version: ' + version)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map(function (id) {
if (/^[0-9]+$/.test(id)) {
var num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
SemVer.prototype.format = function () {
this.version = this.major + '.' + this.minor + '.' + this.patch
if (this.prerelease.length) {
this.version += '-' + this.prerelease.join('.')
}
return this.version
}
SemVer.prototype.toString = function () {
return this.version
}
SemVer.prototype.compare = function (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return this.compareMain(other) || this.comparePre(other)
}
SemVer.prototype.compareMain = function (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
}
SemVer.prototype.comparePre = function (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
var i = 0
do {
var a = this.prerelease[i]
var b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
SemVer.prototype.compareBuild = function (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
var i = 0
do {
var a = this.build[i]
var b = other.build[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
SemVer.prototype.inc = function (release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier)
this.inc('pre', identifier)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier)
}
this.inc('pre', identifier)
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0]
} else {
var i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
this.prerelease.push(0)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (this.prerelease[0] === identifier) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0]
}
} else {
this.prerelease = [identifier, 0]
}
}
break
default:
throw new Error('invalid increment argument: ' + release)
}
this.format()
this.raw = this.version
return this
}
exports.inc = inc
function inc (version, release, loose, identifier) {
if (typeof (loose) === 'string') {
identifier = loose
loose = undefined
}
try {
return new SemVer(version, loose).inc(release, identifier).version
} catch (er) {
return null
}
}
exports.diff = diff
function diff (version1, version2) {
if (eq(version1, version2)) {
return null
} else {
var v1 = parse(version1)
var v2 = parse(version2)
var prefix = ''
if (v1.prerelease.length || v2.prerelease.length) {
prefix = 'pre'
var defaultResult = 'prerelease'
}
for (var key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key
}
}
}
return defaultResult // may be undefined
}
}
exports.compareIdentifiers = compareIdentifiers
var numeric = /^[0-9]+$/
function compareIdentifiers (a, b) {
var anum = numeric.test(a)
var bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
exports.rcompareIdentifiers = rcompareIdentifiers
function rcompareIdentifiers (a, b) {
return compareIdentifiers(b, a)
}
exports.major = major
function major (a, loose) {
return new SemVer(a, loose).major
}
exports.minor = minor
function minor (a, loose) {
return new SemVer(a, loose).minor
}
exports.patch = patch
function patch (a, loose) {
return new SemVer(a, loose).patch
}
exports.compare = compare
function compare (a, b, loose) {
return new SemVer(a, loose).compare(new SemVer(b, loose))
}
exports.compareLoose = compareLoose
function compareLoose (a, b) {
return compare(a, b, true)
}
exports.compareBuild = compareBuild
function compareBuild (a, b, loose) {
var versionA = new SemVer(a, loose)
var versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
exports.rcompare = rcompare
function rcompare (a, b, loose) {
return compare(b, a, loose)
}
exports.sort = sort
function sort (list, loose) {
return list.sort(function (a, b) {
return exports.compareBuild(a, b, loose)
})
}
exports.rsort = rsort
function rsort (list, loose) {
return list.sort(function (a, b) {
return exports.compareBuild(b, a, loose)
})
}
exports.gt = gt
function gt (a, b, loose) {
return compare(a, b, loose) > 0
}
exports.lt = lt
function lt (a, b, loose) {
return compare(a, b, loose) < 0
}
exports.eq = eq
function eq (a, b, loose) {
return compare(a, b, loose) === 0
}
exports.neq = neq
function neq (a, b, loose) {
return compare(a, b, loose) !== 0
}
exports.gte = gte
function gte (a, b, loose) {
return compare(a, b, loose) >= 0
}
exports.lte = lte
function lte (a, b, loose) {
return compare(a, b, loose) <= 0
}
exports.cmp = cmp
function cmp (a, op, b, loose) {
switch (op) {
case '===':
if (typeof a === 'object')
a = a.version
if (typeof b === 'object')
b = b.version
return a === b
case '!==':
if (typeof a === 'object')
a = a.version
if (typeof b === 'object')
b = b.version
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError('Invalid operator: ' + op)
}
}
exports.Comparator = Comparator
function Comparator (comp, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
if (!(this instanceof Comparator)) {
return new Comparator(comp, options)
}
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
var ANY = {}
Comparator.prototype.parse = function (comp) {
var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
var m = comp.match(r)
if (!m) {
throw new TypeError('Invalid comparator: ' + comp)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
Comparator.prototype.toString = function () {
return this.value
}
Comparator.prototype.test = function (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
Comparator.prototype.intersects = function (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
var rangeTmp
if (this.operator === '') {
if (this.value === '') {
return true
}
rangeTmp = new Range(comp.value, options)
return satisfies(this.value, rangeTmp, options)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
rangeTmp = new Range(this.value, options)
return satisfies(comp.semver, rangeTmp, options)
}
var sameDirectionIncreasing =
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '>=' || comp.operator === '>')
var sameDirectionDecreasing =
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '<=' || comp.operator === '<')
var sameSemVer = this.semver.version === comp.semver.version
var differentDirectionsInclusive =
(this.operator === '>=' || this.operator === '<=') &&
(comp.operator === '>=' || comp.operator === '<=')
var oppositeDirectionsLessThan =
cmp(this.semver, '<', comp.semver, options) &&
((this.operator === '>=' || this.operator === '>') &&
(comp.operator === '<=' || comp.operator === '<'))
var oppositeDirectionsGreaterThan =
cmp(this.semver, '>', comp.semver, options) &&
((this.operator === '<=' || this.operator === '<') &&
(comp.operator === '>=' || comp.operator === '>'))
return sameDirectionIncreasing || sameDirectionDecreasing ||
(sameSemVer && differentDirectionsInclusive) ||
oppositeDirectionsLessThan || oppositeDirectionsGreaterThan
}
exports.Range = Range
function Range (range, options) {
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
}
}
if (range instanceof Range) {
if (range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
return new Range(range.value, options)
}
if (!(this instanceof Range)) {
return new Range(range, options)
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First, split based on boolean or ||
this.raw = range
this.set = range.split(/\s*\|\|\s*/).map(function (range) {
return this.parseRange(range.trim())
}, this).filter(function (c) {
// throw out any that are not relevant for whatever reason
return c.length
})
if (!this.set.length) {
throw new TypeError('Invalid SemVer Range: ' + range)
}
this.format()
}
Range.prototype.format = function () {
this.range = this.set.map(function (comps) {
return comps.join(' ').trim()
}).join('||').trim()
return this.range
}
Range.prototype.toString = function () {
return this.range
}
Range.prototype.parseRange = function (range) {
var loose = this.options.loose
range = range.trim()
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace)
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range, re[t.COMPARATORTRIM])
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
// At this point, the range is completely trimmed and
// ready to be split into comparators.
var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
var set = range.split(' ').map(function (comp) {
return parseComparator(comp, this.options)
}, this).join(' ').split(/\s+/)
if (this.options.loose) {
// in loose mode, throw out any that are not valid comparators
set = set.filter(function (comp) {
return !!comp.match(compRe)
})
}
set = set.map(function (comp) {
return new Comparator(comp, this.options)
}, this)
return set
}
Range.prototype.intersects = function (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some(function (thisComparators) {
return (
isSatisfiable(thisComparators, options) &&
range.set.some(function (rangeComparators) {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every(function (thisComparator) {
return rangeComparators.every(function (rangeComparator) {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// take a set of comparators and determine whether there
// exists a version which can satisfy it
function isSatisfiable (comparators, options) {
var result = true
var remainingComparators = comparators.slice()
var testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every(function (otherComparator) {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// Mostly just for testing and legacy API reasons
exports.toComparators = toComparators
function toComparators (range, options) {
return new Range(range, options).set.map(function (comp) {
return comp.map(function (c) {
return c.value
}).join(' ').trim().split(' ')
})
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
function parseComparator (comp, options) {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
function isX (id) {
return !id || id.toLowerCase() === 'x' || id === '*'
}
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
function replaceTildes (comp, options) {
return comp.trim().split(/\s+/).map(function (comp) {
return replaceTilde(comp, options)
}).join(' ')
}
function replaceTilde (comp, options) {
var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, function (_, M, m, p, pr) {
debug('tilde', comp, _, M, m, p, pr)
var ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
} else if (pr) {
debug('replaceTilde pr', pr)
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
' <' + M + '.' + (+m + 1) + '.0'
} else {
// ~1.2.3 == >=1.2.3 <1.3.0
ret = '>=' + M + '.' + m + '.' + p +
' <' + M + '.' + (+m + 1) + '.0'
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
// ^1.2.3 --> >=1.2.3 <2.0.0
// ^1.2.0 --> >=1.2.0 <2.0.0
function replaceCarets (comp, options) {
return comp.trim().split(/\s+/).map(function (comp) {
return replaceCaret(comp, options)
}).join(' ')
}
function replaceCaret (comp, options) {
debug('caret', comp, options)
var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
return comp.replace(r, function (_, M, m, p, pr) {
debug('caret', comp, _, M, m, p, pr)
var ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
} else if (isX(p)) {
if (M === '0') {
ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
} else {
ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
' <' + M + '.' + m + '.' + (+p + 1)
} else {
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
' <' + M + '.' + (+m + 1) + '.0'
}
} else {
ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
' <' + (+M + 1) + '.0.0'
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = '>=' + M + '.' + m + '.' + p +
' <' + M + '.' + m + '.' + (+p + 1)
} else {
ret = '>=' + M + '.' + m + '.' + p +
' <' + M + '.' + (+m + 1) + '.0'
}
} else {
ret = '>=' + M + '.' + m + '.' + p +
' <' + (+M + 1) + '.0.0'
}
}
debug('caret return', ret)
return ret
})
}
function replaceXRanges (comp, options) {
debug('replaceXRanges', comp, options)
return comp.split(/\s+/).map(function (comp) {
return replaceXRange(comp, options)
}).join(' ')
}
function replaceXRange (comp, options) {
comp = comp.trim()
var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
var xM = isX(M)
var xm = xM || isX(m)
var xp = xm || isX(p)
var anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
// >1.2.3 => >= 1.2.4
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
ret = gtlt + M + '.' + m + '.' + p + pr
} else if (xm) {
ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr
} else if (xp) {
ret = '>=' + M + '.' + m + '.0' + pr +
' <' + M + '.' + (+m + 1) + '.0' + pr
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
function replaceStars (comp, options) {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[t.STAR], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0
function hyphenReplace ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = '>=' + fM + '.0.0'
} else if (isX(fp)) {
from = '>=' + fM + '.' + fm + '.0'
} else {
from = '>=' + from
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = '<' + (+tM + 1) + '.0.0'
} else if (isX(tp)) {
to = '<' + tM + '.' + (+tm + 1) + '.0'
} else if (tpr) {
to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr
} else {
to = '<=' + to
}
return (from + ' ' + to).trim()
}
// if ANY of the sets match ALL of its comparators, then pass
Range.prototype.test = function (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (var i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
function testSet (set, version, options) {
for (var i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
var allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}
exports.satisfies = satisfies
function satisfies (version, range, options) {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
exports.maxSatisfying = maxSatisfying
function maxSatisfying (versions, range, options) {
var max = null
var maxSV = null
try {
var rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach(function (v) {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
exports.minSatisfying = minSatisfying
function minSatisfying (versions, range, options) {
var min = null
var minSV = null
try {
var rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach(function (v) {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v
minSV = new SemVer(min, options)
}
}
})
return min
}
exports.minVersion = minVersion
function minVersion (range, loose) {
range = new Range(range, loose)
var minver = new SemVer('0.0.0')
if (range.test(minver)) {
return minver
}
minver = new SemVer('0.0.0-0')
if (range.test(minver)) {
return minver
}
minver = null
for (var i = 0; i < range.set.length; ++i) {
var comparators = range.set[i]
comparators.forEach(function (comparator) {
// Clone to avoid manipulating the comparator's semver object.
var compver = new SemVer(comparator.semver.version)
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++
} else {
compver.prerelease.push(0)
}
compver.raw = compver.format()
/* fallthrough */
case '':
case '>=':
if (!minver || gt(minver, compver)) {
minver = compver
}
break
case '<':
case '<=':
/* Ignore maximum versions */
break
/* istanbul ignore next */
default:
throw new Error('Unexpected operation: ' + comparator.operator)
}
})
}
if (minver && range.test(minver)) {
return minver
}
return null
}
exports.validRange = validRange
function validRange (range, options) {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, options).range || '*'
} catch (er) {
return null
}
}
// Determine if version is less than all the versions possible in the range
exports.ltr = ltr
function ltr (version, range, options) {
return outside(version, range, '<', options)
}
// Determine if version is greater than all the versions possible in the range.
exports.gtr = gtr
function gtr (version, range, options) {
return outside(version, range, '>', options)
}
exports.outside = outside
function outside (version, range, hilo, options) {
version = new SemVer(version, options)
range = new Range(range, options)
var gtfn, ltefn, ltfn, comp, ecomp
switch (hilo) {
case '>':
gtfn = gt
ltefn = lte
ltfn = lt
comp = '>'
ecomp = '>='
break
case '<':
gtfn = lt
ltefn = gte
ltfn = gt
comp = '<'
ecomp = '<='
break
default:
throw new TypeError('Must provide a hilo val of "<" or ">"')
}
// If it satisifes the range it is not outside
if (satisfies(version, range, options)) {
return false
}
// From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (var i = 0; i < range.set.length; ++i) {
var comparators = range.set[i]
var high = null
var low = null
comparators.forEach(function (comparator) {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0')
}
high = high || comparator
low = low || comparator
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator
}
})
// If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false
}
// If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) &&
ltefn(version, low.semver)) {
return false
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false
}
}
return true
}
exports.prerelease = prerelease
function prerelease (version, options) {
var parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
exports.intersects = intersects
function intersects (r1, r2, options) {
r1 = new Range(r1, options)
r2 = new Range(r2, options)
return r1.intersects(r2)
}
exports.coerce = coerce
function coerce (version, options) {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
var match = null
if (!options.rtl) {
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
var next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null) {
return null
}
return parse(match[2] +
'.' + (match[3] || '0') +
'.' + (match[4] || '0'), options)
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(87)))
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _extends2 = __webpack_require__(90);
var _extends3 = _interopRequireDefault(_extends2);
var _toConsumableArray2 = __webpack_require__(82);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NeuralNetworkUtils = function () {
function NeuralNetworkUtils(options) {
(0, _classCallCheck3.default)(this, NeuralNetworkUtils);
this.options = options || {};
}
/**
* normalizeValue
* @param {*} value
* @param {*} min
* @param {*} max
*/
// eslint-disable-next-line class-methods-use-this
(0, _createClass3.default)(NeuralNetworkUtils, [{
key: 'normalizeValue',
value: function normalizeValue(value, min, max) {
return (value - min) / (max - min);
}
/**
* unNormalizeValue
* @param {*} value
* @param {*} min
* @param {*} max
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'unnormalizeValue',
value: function unnormalizeValue(value, min, max) {
return value * (max - min) + min;
}
/**
* getMin
* @param {*} _array
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'getMin',
value: function getMin(_array) {
// return Math.min(..._array)
return _array.reduce(function (a, b) {
return Math.min(a, b);
});
}
/**
* getMax
* @param {*} _array
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'getMax',
value: function getMax(_array) {
return _array.reduce(function (a, b) {
return Math.max(a, b);
});
// return Math.max(..._array)
}
/**
* checks whether or not a string is a json
* @param {*} str
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'isJsonOrString',
value: function isJsonOrString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
/**
* zipArrays
* @param {*} arr1
* @param {*} arr2
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'zipArrays',
value: function zipArrays(arr1, arr2) {
if (arr1.length !== arr2.length) {
console.error('arrays do not have the same length');
return [];
}
var output = [].concat((0, _toConsumableArray3.default)(new Array(arr1.length).fill(null))).map(function (item, idx) {
return (0, _extends3.default)({}, arr1[idx], arr2[idx]);
});
return output;
}
/**
* createLabelsFromArrayValues
* @param {*} incoming
* @param {*} prefix
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'createLabelsFromArrayValues',
value: function createLabelsFromArrayValues(incoming, prefix) {
var labels = void 0;
if (Array.isArray(incoming)) {
labels = incoming.map(function (v, idx) {
return prefix + '_' + idx;
});
}
return labels;
}
/**
* takes an array and turns it into a json object
* where the labels are the keys and the array values
* are the object values
* @param {*} incoming
* @param {*} labels
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'formatDataAsObject',
value: function formatDataAsObject(incoming, labels) {
var result = {};
if (Array.isArray(incoming)) {
incoming.forEach(function (item, idx) {
var label = labels[idx];
result[label] = item;
});
return result;
} else if ((typeof incoming === 'undefined' ? 'undefined' : (0, _typeof3.default)(incoming)) === 'object') {
result = incoming;
return result;
}
throw new Error('input provided is not supported or does not match your output label specifications');
}
/**
* returns a datatype of the value as string
* @param {*} val
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'getDataType',
value: function getDataType(val) {
var dtype = typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val);
if (dtype === 'object') {
if (Array.isArray(val)) {
dtype = 'array';
}
}
return dtype;
}
}]);
return NeuralNetworkUtils;
}();
var neuralNetworkUtils = function neuralNetworkUtils() {
var instance = new NeuralNetworkUtils();
return instance;
};
exports.default = neuralNetworkUtils();
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.randomSample = exports.randomGaussian = exports.randomInt = exports.randomFloat = undefined;
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Random
// Returns a random number between min (inclusive) and max (exclusive)
var randomFloat = function randomFloat() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return Math.random() * (max - min) + min;
};
// Returns a random integer between min (inclusive) and max (inclusive)
var randomInt = function randomInt() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return Math.floor(Math.random() * (max - min + 1)) + min;
};
// Random Number following a normal dist.
// Taken from https://github.com/processing/p5.js/blob/master/src/math/random.js#L168
var randomGaussian = function randomGaussian() {
var mean = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var sd = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var y1 = void 0;
var y2 = void 0;
var x1 = void 0;
var x2 = void 0;
var w = void 0;
var previous = void 0;
if (previous) {
y1 = y2;
previous = false;
} else {
do {
x1 = randomFloat(0, 2) - 1;
x2 = randomFloat(0, 2) - 1;
w = x1 * x1 + x2 * x2;
} while (w >= 1);
w = Math.sqrt(-2 * Math.log(w) / w);
y1 = x1 * w;
y2 = x2 * w;
previous = true;
}
return y1 * sd + mean;
};
// Returns a random sample (either with or without replacement) of size k from an array
var randomSample = function randomSample(arr, k) {
var withReplacement = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var sample = void 0;
if (withReplacement === true) {
// sample with replacement
sample = (0, _from2.default)({ length: k }, function () {
return arr[Math.floor(Math.random() * arr.length)];
});
} else {
// sample without replacement
if (k > arr.length) {
throw new RangeError('Sample size must be less than or equal to array length when sampling without replacement.');
}
sample = arr.map(function (a) {
return [a, Math.random()];
}).sort(function (a, b) {
return a[1] < b[1] ? -1 : 1;
}).slice(0, k).map(function (a) {
return a[0];
});
};
return sample;
};
exports.randomFloat = randomFloat;
exports.randomInt = randomInt;
exports.randomGaussian = randomGaussian;
exports.randomSample = randomSample;
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _defineProperty = __webpack_require__(222);
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (obj, key, value) {
if (key in obj) {
(0, _defineProperty2.default)(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(309), __esModule: true };
/***/ }),
/* 201 */
/***/ (function(module) {
module.exports = {"name":"ml5","version":"0.5.0","description":"A friendly machine learning library for the web.","main":"dist/ml5.min.js","directories":{"examples":"examples","dist":"dist"},"scripts":{"commit":"git-cz","prebuild":"rimraf dist","develop":"npm-run-all --parallel start examples:serve examples:watch","start":"webpack-dev-server --config webpack.dev.babel.js","lint":"eslint . --ext .js; exit 0","lint:nibble":"npx eslint-nibble --ext .js .","manual-test":"webpack-dev-server --open --config webpack.test.babel.js","build":"webpack --config webpack.prod.babel.js --config-name ml5","test":"./node_modules/karma/bin/karma start karma.conf.js","test:single":"./node_modules/karma/bin/karma start karma.conf.js --single-run","test-travis":"./scripts/test-travis.sh","serve:docs":"docsify serve docs","update:readme":"node ./scripts/updateReadme.js","update:docs":"node ./scripts/updateDocVersions.js $oldversion","publish:npm":"npm run build && npm publish","contributors:add":"all-contributors add","contributors:generate":"all-contributors generate","examples:serve":"live-server ./examples --port=8081 --mount=/:./examples --wait=250","examples:update-json":"node scripts/update-examples-json.js","examples:watch":"onchange -f 'addDir unlinkDir' './examples' -- npm run examples:update-json","preexamples:build":"rimraf dist_examples","examples:build":"npm run examples:update-json && webpack --config webpack.prod.babel.js --config-name examples"},"repository":{"type":"git","url":"git+https://github.com/ml5js/ml5-library.git"},"keywords":["machine learning"],"author":"NYU ITP <cvalenzuela@nyu.edu> (https://github.com/ml5js)","license":"MIT","bugs":{"url":"https://github.com/ml5js/ml5-library/issues"},"homepage":"https://github.com/ml5js/ml5-library#readme","devDependencies":{"all-contributors-cli":"^6.10.0","babel-cli":"6.26.0","babel-core":"6.26.0","babel-loader":"7.1.4","babel-plugin-transform-object-rest-spread":"^6.26.0","babel-plugin-transform-runtime":"^6.23.0","babel-polyfill":"6.26.0","babel-preset-env":"1.6.1","babel-register":"6.26.0","commitizen":"4.0.3","copy-webpack-plugin":"^5.1.1","cz-conventional-changelog":"2.1.0","docsify-cli":"^4.3.0","dotenv":"^8.2.0","eslint":"4.18.2","eslint-config-airbnb-base":"12.1.0","eslint-config-prettier":"^4.1.0","eslint-loader":"2.0.0","eslint-nibble":"^5.1.0","eslint-plugin-import":"2.9.0","extract-text-webpack-plugin":"4.0.0-beta.0","ghooks":"2.0.2","html-webpack-plugin":"^3.0.7","jasmine-core":"3.1.0","karma":"2.0.0","karma-browserstack-launcher":"^1.5.1","karma-chrome-launcher":"2.2.0","karma-jasmine":"1.1.1","karma-mocha-reporter":"^2.2.5","karma-safari-launcher":"1.0.0","karma-webpack":"3.0.0","live-server":"^1.2.1","npm-run-all":"^4.1.5","q":"^1.5.1","recursive-readdir":"^2.2.2","regenerator-runtime":"0.11.1","request-promise":"^4.2.5","rimraf":"2.6.2","semantic-release":"^15.13.26","uglifyjs-webpack-plugin":"^1.2.5","webpack":"4.1.1","webpack-cli":"2.0.10","webpack-dev-server":"3.10.3","webpack-merge":"^4.1.2"},"config":{"commitizen":{"path":"node_modules/cz-conventional-changelog"}},"files":["dist","README.md"],"babel":{"presets":[["env"]],"plugins":["transform-runtime","transform-object-rest-spread"]},"peerDependencies":{"@tensorflow/tfjs-core":"^1.2.9","@tensorflow/tfjs-converter":"^1.2.9"},"dependencies":{"@magenta/sketch":"0.2.0","@tensorflow-models/body-pix":"1.1.2","@tensorflow-models/coco-ssd":"^2.0.0","@tensorflow-models/facemesh":"0.0.3","@tensorflow-models/handpose":"0.0.3","@tensorflow-models/knn-classifier":"1.2.1","@tensorflow-models/mobilenet":"2.0.3","@tensorflow-models/posenet":"^2.2.1","@tensorflow-models/speech-commands":"0.3.9","@tensorflow-models/universal-sentence-encoder":"^1.2.2","@tensorflow/tfjs":"^1.7.0","@tensorflow/tfjs-vis":"^1.1.0","axios":"^0.19.2","events":"^3.0.0","face-api.js":"~0.22.2","onchange":"^6.1.0"}};
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(38);
module.exports = function (it, TYPE) {
if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!');
return it;
};
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(332), __esModule: true };
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MANIFEST_FILE = 'manifest.json'; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var CheckpointLoader = function () {
function CheckpointLoader(urlPath) {
(0, _classCallCheck3.default)(this, CheckpointLoader);
this.urlPath = urlPath;
if (this.urlPath.charAt(this.urlPath.length - 1) !== '/') {
this.urlPath += '/';
}
}
(0, _createClass3.default)(CheckpointLoader, [{
key: 'loadManifest',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this = this;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', new _promise2.default(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', _this.urlPath + MANIFEST_FILE);
xhr.onload = function () {
_this.checkpointManifest = JSON.parse(xhr.responseText);
resolve();
};
xhr.onerror = function (error) {
reject();
throw new Error(MANIFEST_FILE + ' not found at ' + _this.urlPath + '. ' + error);
};
xhr.send();
}));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadManifest() {
return _ref.apply(this, arguments);
}
return loadManifest;
}()
}, {
key: 'getCheckpointManifest',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(this.checkpointManifest == null)) {
_context2.next = 3;
break;
}
_context2.next = 3;
return this.loadManifest();
case 3:
return _context2.abrupt('return', this.checkpointManifest);
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function getCheckpointManifest() {
return _ref2.apply(this, arguments);
}
return getCheckpointManifest;
}()
}, {
key: 'getAllVariables',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() {
var _this2 = this;
var variableNames, variablePromises;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(this.variables != null)) {
_context3.next = 2;
break;
}
return _context3.abrupt('return', _promise2.default.resolve(this.variables));
case 2:
_context3.next = 4;
return this.getCheckpointManifest();
case 4:
variableNames = (0, _keys2.default)(this.checkpointManifest);
variablePromises = variableNames.map(function (v) {
return _this2.getVariable(v);
});
return _context3.abrupt('return', _promise2.default.all(variablePromises).then(function (variables) {
_this2.variables = {};
for (var i = 0; i < variables.length; i += 1) {
_this2.variables[variableNames[i]] = variables[i];
}
return _this2.variables;
}));
case 7:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function getAllVariables() {
return _ref3.apply(this, arguments);
}
return getAllVariables;
}()
}, {
key: 'getVariable',
value: function getVariable(varName) {
var _this3 = this;
if (!(varName in this.checkpointManifest)) {
throw new Error('Cannot load non-existent variable ' + varName);
}
var variableRequestPromiseMethod = function variableRequestPromiseMethod(resolve) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
var fname = _this3.checkpointManifest[varName].filename;
xhr.open('GET', _this3.urlPath + fname);
xhr.onload = function () {
if (xhr.status === 404) {
throw new Error('Not found variable ' + varName);
}
var values = new Float32Array(xhr.response);
var tensor = tf.tensor(values, _this3.checkpointManifest[varName].shape);
resolve(tensor);
};
xhr.onerror = function (error) {
throw new Error('Could not fetch variable ' + varName + ': ' + error);
};
xhr.send();
};
if (this.checkpointManifest == null) {
return new _promise2.default(function (resolve) {
_this3.loadManifest().then(function () {
new _promise2.default(variableRequestPromiseMethod).then(resolve);
});
});
}
return new _promise2.default(variableRequestPromiseMethod);
}
}]);
return CheckpointLoader;
}();
exports.default = CheckpointLoader;
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CocoSsd = exports.CocoSsdBase = undefined;
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _cocoSsd = __webpack_require__(347);
var cocoSsd = _interopRequireWildcard(_cocoSsd);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _imageUtilities = __webpack_require__(46);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
COCO-SSD Object detection
Wraps the coco-ssd model in tfjs to be used in ml5
*/
var DEFAULTS = {
base: "lite_mobilenet_v2",
modelUrl: undefined
};
var CocoSsdBase = exports.CocoSsdBase = function () {
/**
* Create CocoSsd model. Works on video and images.
* @param {function} constructorCallback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise
* that will be resolved once the model has loaded.
*/
function CocoSsdBase(video, options, constructorCallback) {
(0, _classCallCheck3.default)(this, CocoSsdBase);
this.video = video || null;
this.modelReady = false;
this.isPredicting = false;
this.config = {
base: options.base || DEFAULTS.base,
modelUrl: options.modelUrl || DEFAULTS.modelUrl
};
this.callback = constructorCallback;
this.ready = (0, _callcallback2.default)(this.loadModel(), this.callback);
}
/**
* load model
*/
(0, _createClass3.default)(CocoSsdBase, [{
key: "loadModel",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return cocoSsd.load(this.config);
case 2:
this.model = _context.sent;
this.modelReady = true;
return _context.abrupt("return", this);
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* @typedef {Object} ObjectDetectorPrediction
* @property {number} x - top left x coordinate of the prediction box in pixels.
* @property {number} y - top left y coordinate of the prediction box in pixels.
* @property {number} width - width of the prediction box in pixels.
* @property {number} height - height of the prediction box in pixels.
* @property {string} label - the label given.
* @property {number} confidence - the confidence score (0 to 1).
* @property {ObjectDetectorPredictionNormalized} normalized - a normalized object of the predicition
*/
/**
* @typedef {Object} ObjectDetectorPredictionNormalized
* @property {number} x - top left x coordinate of the prediction box (0 to 1).
* @property {number} y - top left y coordinate of the prediction box (0 to 1).
* @property {number} width - width of the prediction box (0 to 1).
* @property {number} height - height of the prediction box (0 to 1).
*/
/**
* Detect objects that are in video, returns bounding box, label, and confidence scores
* @param {HTMLVideoElement|HTMLImageElement|HTMLCanvasElement|ImageData} subject - Subject of the detection.
* @returns {ObjectDetectorPrediction}
*/
}, {
key: "detectInternal",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(imgToPredict) {
var predictions, formattedPredictions;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
this.isPredicting = true;
_context2.next = 3;
return this.model.detect(imgToPredict);
case 3:
predictions = _context2.sent;
formattedPredictions = predictions.map(function (prediction) {
return {
label: prediction.class,
confidence: prediction.score,
x: prediction.bbox[0],
y: prediction.bbox[1],
width: prediction.bbox[2],
height: prediction.bbox[3],
normalized: {
x: prediction.bbox[0] / imgToPredict.width,
y: prediction.bbox[1] / imgToPredict.height,
width: prediction.bbox[2] / imgToPredict.width,
height: prediction.bbox[3] / imgToPredict.height
}
};
});
this.isPredicting = false;
return _context2.abrupt("return", formattedPredictions);
case 7:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function detectInternal(_x) {
return _ref2.apply(this, arguments);
}
return detectInternal;
}()
/**
* Detect objects that are in video, returns bounding box, label, and confidence scores
* @param {HTMLVideoElement|HTMLImageElement|HTMLCanvasElement|ImageData} subject - Subject of the detection.
* @param {function} callback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise
* that will be resolved once the prediction is done.
* @returns {ObjectDetectorPrediction}
*/
}, {
key: "detect",
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(inputOrCallback, cb) {
var imgToPredict, callback;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.ready;
case 2:
_context3.next = 4;
return tf.nextFrame();
case 4:
imgToPredict = void 0;
callback = cb;
if (!(0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback)) {
_context3.next = 10;
break;
}
imgToPredict = inputOrCallback;
_context3.next = 24;
break;
case 10:
if (!((typeof inputOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(inputOrCallback)) === "object" && (0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback.elt))) {
_context3.next = 14;
break;
}
imgToPredict = inputOrCallback.elt; // Handle p5.js image and video.
_context3.next = 24;
break;
case 14:
if (!((typeof inputOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(inputOrCallback)) === "object" && (0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback.canvas))) {
_context3.next = 18;
break;
}
imgToPredict = inputOrCallback.canvas; // Handle p5.js image and video.
_context3.next = 24;
break;
case 18:
if (!(typeof inputOrCallback === "function")) {
_context3.next = 23;
break;
}
imgToPredict = this.video;
callback = inputOrCallback;
_context3.next = 24;
break;
case 23:
throw new Error("Detection subject not supported");
case 24:
return _context3.abrupt("return", (0, _callcallback2.default)(this.detectInternal(imgToPredict), callback));
case 25:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function detect(_x2, _x3) {
return _ref3.apply(this, arguments);
}
return detect;
}()
}]);
return CocoSsdBase;
}();
var CocoSsd = exports.CocoSsd = function CocoSsd(videoOr, optionsOr, cb) {
var video = null;
var options = {};
var callback = cb;
if (videoOr instanceof HTMLVideoElement) {
video = videoOr;
} else if ((typeof videoOr === "undefined" ? "undefined" : (0, _typeof3.default)(videoOr)) === "object" && videoOr.elt instanceof HTMLVideoElement) {
video = videoOr.elt; // Handle p5.js image
} else if (typeof videoOr === "function") {
callback = videoOr;
} else if ((typeof videoOr === "undefined" ? "undefined" : (0, _typeof3.default)(videoOr)) === "object") {
options = videoOr;
}
if ((typeof optionsOr === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOr)) === "object") {
options = optionsOr;
} else if (typeof optionsOr === "function") {
callback = optionsOr;
}
return new CocoSsdBase(video, options, callback);
};
// export default CocoSsd;
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.YOLO = exports.YOLOBase = undefined;
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _getPrototypeOf = __webpack_require__(98);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(97);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(96);
var _inherits3 = _interopRequireDefault(_inherits2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _Video2 = __webpack_require__(143);
var _Video3 = _interopRequireDefault(_Video2);
var _imageUtilities = __webpack_require__(46);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _COCO_CLASSES = __webpack_require__(349);
var _COCO_CLASSES2 = _interopRequireDefault(_COCO_CLASSES);
var _modelLoader = __webpack_require__(142);
var _modelLoader2 = _interopRequireDefault(_modelLoader);
var _postprocess = __webpack_require__(348);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
modelUrl: 'https://raw.githubusercontent.com/ml5js/ml5-data-and-training/master/models/YOLO/model.json',
filterBoxesThreshold: 0.01,
IOUThreshold: 0.4,
classProbThreshold: 0.4
};
// Size of the video
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint max-len: ["error", { "code": 180 }] */
/*
YOLO Object detection
Heavily derived from https://github.com/ModelDepot/tfjs-yolo-tiny (ModelDepot: modeldepot.io)
*/
var imageSize = 416;
var YOLOBase = exports.YOLOBase = function (_Video) {
(0, _inherits3.default)(YOLOBase, _Video);
/**
* @deprecated Please use ObjectDetector class instead
*/
/**
* @typedef {Object} options
* @property {number} filterBoxesThreshold - default 0.01
* @property {number} IOUThreshold - default 0.4
* @property {number} classProbThreshold - default 0.4
*/
/**
* Create YOLO model. Works on video and images.
* @param {HTMLVideoElement|HTMLImageElement|HTMLCanvasElement|ImageData} video - Optional. The video to be used for object detection and classification.
* @param {Object} options - Optional. A set of options.
* @param {function} callback - Optional. A callback function that is called once the model has loaded.
*/
function YOLOBase(video, options, callback) {
(0, _classCallCheck3.default)(this, YOLOBase);
var _this = (0, _possibleConstructorReturn3.default)(this, (YOLOBase.__proto__ || (0, _getPrototypeOf2.default)(YOLOBase)).call(this, video, imageSize));
_this.modelUrl = options.modelUrl || DEFAULTS.modelUrl;
_this.filterBoxesThreshold = options.filterBoxesThreshold || DEFAULTS.filterBoxesThreshold;
_this.IOUThreshold = options.IOUThreshold || DEFAULTS.IOUThreshold;
_this.classProbThreshold = options.classProbThreshold || DEFAULTS.classProbThreshold;
_this.modelReady = false;
_this.isPredicting = false;
_this.callback = callback;
_this.ready = (0, _callcallback2.default)(_this.loadModel(), _this.callback);
if (!options.disableDeprecationNotice) {
console.warn("WARNING! Function YOLO has been deprecated, please use the new ObjectDetector function instead");
}
return _this;
}
(0, _createClass3.default)(YOLOBase, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var modelPath;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(this.videoElt && !this.video)) {
_context.next = 4;
break;
}
_context.next = 3;
return this.loadVideo();
case 3:
this.video = _context.sent;
case 4:
if (!(_modelLoader2.default.isAbsoluteURL(this.modelUrl) === true)) {
_context.next = 10;
break;
}
_context.next = 7;
return tf.loadLayersModel(this.modelUrl);
case 7:
this.model = _context.sent;
_context.next = 15;
break;
case 10:
modelPath = _modelLoader2.default.getModelPath(this.modelUrl);
this.modelUrl = modelPath + '/model.json';
_context.next = 14;
return tf.loadLayersModel(this.modelUrl);
case 14:
this.model = _context.sent;
case 15:
this.modelReady = true;
return _context.abrupt('return', this);
case 17:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Detect objects that are in video, returns bounding box, label, and confidence scores
* @param {HTMLVideoElement|HTMLImageElement|HTMLCanvasElement|ImageData} subject - Subject of the detection.
* @param {function} callback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise
* that will be resolved once the prediction is done.
* @returns {ObjectDetectorPrediction}
*/
}, {
key: 'detect',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputOrCallback, cb) {
var imgToPredict, callback;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.ready;
case 2:
imgToPredict = void 0;
callback = cb;
if (!(0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback)) {
_context2.next = 8;
break;
}
imgToPredict = inputOrCallback;
_context2.next = 22;
break;
case 8:
if (!((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === "object" && (0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback.elt))) {
_context2.next = 12;
break;
}
imgToPredict = inputOrCallback.elt; // Handle p5.js image and video.
_context2.next = 22;
break;
case 12:
if (!((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === "object" && (0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback.canvas))) {
_context2.next = 16;
break;
}
imgToPredict = inputOrCallback.canvas; // Handle p5.js image and video.
_context2.next = 22;
break;
case 16:
if (!(typeof inputOrCallback === "function")) {
_context2.next = 21;
break;
}
imgToPredict = this.video;
callback = inputOrCallback;
_context2.next = 22;
break;
case 21:
throw new Error('Detection subject not supported');
case 22:
return _context2.abrupt('return', (0, _callcallback2.default)(this.detectInternal(imgToPredict), callback));
case 23:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function detect(_x, _x2) {
return _ref2.apply(this, arguments);
}
return detect;
}()
/**
* @typedef {Object} ObjectDetectorPrediction
* @property {number} x - top left x coordinate of the prediction box in pixels.
* @property {number} y - top left y coordinate of the prediction box in pixels.
* @property {number} width - width of the prediction box in pixels.
* @property {number} height - height of the prediction box in pixels.
* @property {string} label - the label given.
* @property {number} confidence - the confidence score (0 to 1).
* @property {ObjectDetectorPredictionNormalized} normalized - a normalized object of the predicition
*/
/**
* @typedef {Object} ObjectDetectorPredictionNormalized
* @property {number} x - top left x coordinate of the prediction box (0 to 1).
* @property {number} y - top left y coordinate of the prediction box (0 to 1).
* @property {number} width - width of the prediction box (0 to 1).
* @property {number} height - height of the prediction box (0 to 1).
*/
/**
* Detect objects that are in video, returns bounding box, label, and confidence scores
* @param {HTMLVideoElement|HTMLImageElement|HTMLCanvasElement|ImageData} subject - Subject of the detection.
* @returns {ObjectDetectorPrediction}
*/
}, {
key: 'detectInternal',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(imgToPredict) {
var _this2 = this;
var ANCHORS, _tf$tidy, _tf$tidy2, allBoxes, boxConfidence, boxClassProbs, _ref4, _ref5, boxes, scores, classes;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.ready;
case 2:
_context3.next = 4;
return tf.nextFrame();
case 4:
ANCHORS = tf.tensor2d([[0.57273, 0.677385], [1.87446, 2.06253], [3.33843, 5.47434], [7.88282, 3.52778], [9.77052, 9.16828]]);
this.isPredicting = true;
_tf$tidy = tf.tidy(function () {
var input = (0, _imageUtilities.imgToTensor)(imgToPredict, [imageSize, imageSize]);
var activation = _this2.model.predict(input);
var _head = (0, _postprocess.head)(activation, ANCHORS, 80),
_head2 = (0, _slicedToArray3.default)(_head, 4),
boxXY = _head2[0],
boxWH = _head2[1],
bConfidence = _head2[2],
bClassProbs = _head2[3];
var aBoxes = (0, _postprocess.boxesToCorners)(boxXY, boxWH);
return [aBoxes, bConfidence, bClassProbs];
}), _tf$tidy2 = (0, _slicedToArray3.default)(_tf$tidy, 3), allBoxes = _tf$tidy2[0], boxConfidence = _tf$tidy2[1], boxClassProbs = _tf$tidy2[2];
_context3.next = 9;
return (0, _postprocess.filterBoxes)(allBoxes, boxConfidence, boxClassProbs, this.filterBoxesThreshold);
case 9:
_ref4 = _context3.sent;
_ref5 = (0, _slicedToArray3.default)(_ref4, 3);
boxes = _ref5[0];
scores = _ref5[1];
classes = _ref5[2];
allBoxes.dispose();
boxConfidence.dispose();
boxClassProbs.dispose();
// If all boxes have been filtered out
if (!(boxes == null)) {
_context3.next = 19;
break;
}
return _context3.abrupt('return', []);
case 19:
return _context3.abrupt('return', tf.tidy(function () {
var width = tf.scalar(imageSize);
var height = tf.scalar(imageSize);
var imageDims = tf.stack([height, width, height, width]).reshape([1, 4]);
var boxesModified = tf.mul(boxes, imageDims);
var preKeepBoxesArr = boxesModified.dataSync();
var scoresArr = scores.dataSync();
var _nonMaxSuppression = (0, _postprocess.nonMaxSuppression)(preKeepBoxesArr, scoresArr, _this2.IOUThreshold),
_nonMaxSuppression2 = (0, _slicedToArray3.default)(_nonMaxSuppression, 3),
keepIndx = _nonMaxSuppression2[0],
boxesArr = _nonMaxSuppression2[1],
keepScores = _nonMaxSuppression2[2];
var classesIndxArr = classes.gather(tf.tensor1d(keepIndx, 'int32')).dataSync();
var results = [];
classesIndxArr.forEach(function (classIndx, i) {
var classProb = keepScores[i];
if (classProb < _this2.classProbThreshold) {
return;
}
var className = _COCO_CLASSES2.default[classIndx];
var _boxesArr$i = (0, _slicedToArray3.default)(boxesArr[i], 4),
y = _boxesArr$i[0],
x = _boxesArr$i[1],
h = _boxesArr$i[2],
w = _boxesArr$i[3];
y = Math.max(0, y);
x = Math.max(0, x);
h = Math.min(imageSize, h) - y;
w = Math.min(imageSize, w) - x;
var resultObj = {
label: className,
confidence: classProb,
x: x,
y: y,
width: w,
height: h,
normalized: {
x: x / imageSize,
y: y / imageSize,
width: w / imageSize,
height: h / imageSize
}
};
results.push(resultObj);
});
_this2.isPredicting = false;
width.dispose();
height.dispose();
imageDims.dispose();
boxesModified.dispose();
boxes.dispose();
scores.dispose();
classes.dispose();
ANCHORS.dispose();
return results;
}));
case 20:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function detectInternal(_x3) {
return _ref3.apply(this, arguments);
}
return detectInternal;
}()
}]);
return YOLOBase;
}(_Video3.default);
var YOLO = exports.YOLO = function YOLO(videoOr, optionsOr, cb) {
var video = null;
var options = {};
var callback = cb;
if (videoOr instanceof HTMLVideoElement) {
video = videoOr;
} else if ((typeof videoOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOr)) === 'object' && videoOr.elt instanceof HTMLVideoElement) {
video = videoOr.elt; // Handle p5.js image
} else if (typeof videoOr === 'function') {
callback = videoOr;
} else if ((typeof videoOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOr)) === 'object') {
options = videoOr;
}
if ((typeof optionsOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOr)) === 'object') {
options = optionsOr;
} else if (typeof optionsOr === 'function') {
callback = optionsOr;
}
return new YOLOBase(video, options, callback);
};
// export default YOLO;
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(32);
var getKeys = __webpack_require__(88);
var toIObject = __webpack_require__(66);
var isEnum = __webpack_require__(105).f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!DESCRIPTORS || isEnum.call(O, key)) {
result.push(isEntries ? [key, O[key]] : O[key]);
}
}
return result;
};
};
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(360), __esModule: true };
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(23);
var core = __webpack_require__(18);
var fails = __webpack_require__(68);
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
/***/ }),
/* 210 */
/***/ (function(module, exports) {
/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var defaultToConfig2Keys = [
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath'
];
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
}
});
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys);
var otherKeys = Object
.keys(config2)
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config;
};
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var enhanceError = __webpack_require__(391);
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
var settle = __webpack_require__(392);
var buildURL = __webpack_require__(217);
var buildFullPath = __webpack_require__(390);
var parseHeaders = __webpack_require__(387);
var isURLSameOrigin = __webpack_require__(386);
var createError = __webpack_require__(213);
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(385);
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
if (config.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
var utils = __webpack_require__(28);
var normalizeHeaderName = __webpack_require__(393);
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(214);
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(214);
}
return adapter;
}
var defaults = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults.headers = {
common: {
'Accept': 'application/json, text/plain, */*'
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(87)))
/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(105);
var createDesc = __webpack_require__(108);
var toIObject = __webpack_require__(66);
var toPrimitive = __webpack_require__(164);
var has = __webpack_require__(67);
var IE8_DOM_DEFINE = __webpack_require__(246);
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(32) ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(245);
var hiddenKeys = __webpack_require__(158).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(107);
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(413), __esModule: true };
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(25)('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(26);
var core = __webpack_require__(18);
var dP = __webpack_require__(39);
var DESCRIPTORS = __webpack_require__(32);
var SPECIES = __webpack_require__(25)('species');
module.exports = function (KEY) {
var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(48);
var isObject = __webpack_require__(38);
var newPromiseCapability = __webpack_require__(149);
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
/***/ }),
/* 226 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return { e: false, v: exec() };
} catch (e) {
return { e: true, v: e };
}
};
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(56);
var invoke = __webpack_require__(418);
var html = __webpack_require__(233);
var cel = __webpack_require__(165);
var global = __webpack_require__(26);
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
setTask = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (__webpack_require__(107)(process) == 'process') {
defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if (MessageChannel) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in cel('script')) {
defer = function (id) {
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(48);
var aFunction = __webpack_require__(109);
var SPECIES = __webpack_require__(25)('species');
module.exports = function (O, D) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(84);
var ITERATOR = __webpack_require__(25)('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(48);
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/* 231 */
/***/ (function(module, exports) {
module.exports = function (done, value) {
return { value: value, done: !!done };
};
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(67);
var toObject = __webpack_require__(65);
var IE_PROTO = __webpack_require__(160)('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
var document = __webpack_require__(26).document;
module.exports = document && document.documentElement;
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(60);
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const vega_embed_1 = __importDefault(__webpack_require__(81));
const dom_1 = __webpack_require__(59);
const utils_1 = __webpack_require__(120);
const render_utils_1 = __webpack_require__(37);
/**
* Renders a line chart
*
* ```js
* const series1 = Array(100).fill(0)
* .map(y => Math.random() * 100 - (Math.random() * 50))
* .map((y, x) => ({ x, y, }));
*
* const series2 = Array(100).fill(0)
* .map(y => Math.random() * 100 - (Math.random() * 150))
* .map((y, x) => ({ x, y, }));
*
* const series = ['First', 'Second'];
* const data = { values: [series1, series2], series }
*
* const surface = { name: 'Line chart', tab: 'Charts' };
* tfvis.render.linechart(surface, data);
* ```
*
* ```js
* const series1 = Array(100).fill(0)
* .map(y => Math.random() * 100 + 50)
* .map((y, x) => ({ x, y, }));
*
* const data = { values: [series1] }
*
* // Render to visor
* const surface = { name: 'Zoomed Line Chart', tab: 'Charts' };
* tfvis.render.linechart(surface, data, { zoomToFit: true });
* ```
*
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function linechart(container, data, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
// Nest data if necessary before further processing
const _data = Array.isArray(data.values[0]) ? data.values :
[data.values];
const numValues = _data[0].length;
// Create series names if none were passed in.
const _series = data.series ? data.series : _data.map((_, i) => `Series ${i + 1}`);
utils_1.assert(_series.length === _data.length, 'Must have an equal number of series labels as there are data series');
if (opts.seriesColors != null) {
utils_1.assert(opts.seriesColors.length === _data.length, 'Must have an equal number of series colors as there are data series');
}
const vlChartValues = [];
for (let valueIdx = 0; valueIdx < numValues; valueIdx++) {
const v = {
x: valueIdx,
};
_series.forEach((seriesName, seriesIdx) => {
const seriesValue = _data[seriesIdx][valueIdx].y;
v[seriesName] = seriesValue;
v[`${seriesName}-name`] = seriesName;
});
vlChartValues.push(v);
}
const options = Object.assign({}, defaultOpts, opts);
const yScale = () => {
if (options.zoomToFit) {
return { 'zero': false };
}
else if (options.yAxisDomain != null) {
return { 'domain': options.yAxisDomain };
}
return undefined;
};
const sharedEncoding = {
x: {
field: 'x',
type: options.xType,
title: options.xLabel,
},
tooltip: [
{ field: 'x', type: 'quantitative' },
..._series.map(seriesName => {
return {
field: seriesName,
type: 'quantitative',
};
}),
]
};
const lineLayers = _series.map((seriesName) => {
return {
// data will be defined at the chart level.
'data': undefined,
'mark': { 'type': 'line', 'clip': true },
'encoding': {
// Note: the encoding for 'x' is shared
// Add a y encoding for this series
'y': {
'field': seriesName,
'type': options.yType,
'title': options.yLabel,
'scale': yScale(),
},
'color': {
'field': `${seriesName}-name`,
'type': 'nominal',
'legend': { 'values': _series, title: null },
'scale': {
'range': options.seriesColors,
}
},
}
};
});
const tooltipLayer = {
'mark': 'rule',
'selection': {
'hover': {
'type': 'single',
'on': 'mouseover',
'nearest': true,
clear: 'mouseout',
}
},
'encoding': {
'color': {
'value': 'grey',
'condition': {
'selection': { 'not': 'hover' },
'value': 'transparent',
}
}
}
};
const drawArea = render_utils_1.getDrawArea(container);
const spec = {
'width': options.width || dom_1.getDefaultWidth(drawArea),
'height': options.height || dom_1.getDefaultHeight(drawArea),
'padding': 0,
'autosize': {
'type': 'fit',
'contains': 'padding',
'resize': true,
},
'config': {
'axis': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'text': { 'fontSize': options.fontSize },
'legend': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
}
},
'data': { 'values': vlChartValues },
'encoding': sharedEncoding,
'layer': [
...lineLayers,
tooltipLayer,
],
};
const embedOpts = {
actions: false,
mode: 'vega-lite',
defaultStyle: false,
};
yield vega_embed_1.default(drawArea, spec, embedOpts);
return Promise.resolve();
});
}
exports.linechart = linechart;
const defaultOpts = {
xLabel: 'x',
yLabel: 'y',
xType: 'quantitative',
yType: 'quantitative',
zoomToFit: false,
fontSize: 11,
};
//# sourceMappingURL=linechart.js.map
/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
const visor_1 = __webpack_require__(439);
let visorSingleton;
const DEFAULT_TAB = 'Visor';
const VISOR_CONTAINER_ID = 'tfjs-visor-container';
/**
* The primary interface to the visor is the visor() function.
*
* This returns a singleton instance of the Visor class. The
* singleton object will be replaced if the visor is removed from the DOM for
* some reason.
*
* ```js
* // Show the visor
* tfvis.visor();
* ```
*
*/
/** @doc {heading: 'Visor & Surfaces'} */
function visor() {
if (typeof document === 'undefined') {
throw new Error('No document defined. This library needs a browser/dom to work');
}
if (document.getElementById(VISOR_CONTAINER_ID) && visorSingleton != null) {
return visorSingleton;
}
// Create the container
let visorEl = document.getElementById(VISOR_CONTAINER_ID);
if (visorEl == null) {
visorEl = document.createElement('div');
visorEl.id = VISOR_CONTAINER_ID;
document.body.appendChild(visorEl);
}
let renderRoot;
function renderVisor(domNode, surfaceList) {
let visorInstance = null;
renderRoot = visor_1.VisorComponent.render(domNode, renderRoot, {
ref: (r) => visorInstance = r,
surfaceList: Array.from(surfaceList.values()),
});
// Side effect of VisorComponent.render() is to assign visorInstance
return visorInstance;
}
// TODO: consider changing this type. Possibly lift into top level state
// object
const surfaceList = new Map();
const visorComponentInstance = renderVisor(visorEl, surfaceList);
visorSingleton =
new Visor(visorComponentInstance, visorEl, surfaceList, renderVisor);
return visorSingleton;
}
exports.visor = visor;
/**
* An instance of the visor. An instance of this class is created using the
* `visor()` function.
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
class Visor {
constructor(visorComponent, visorEl, surfaceList, renderVisor) {
this.visorComponent = visorComponent;
this.el = visorEl;
this.surfaceList = surfaceList;
this.renderVisor = renderVisor;
}
/**
* Creates a surface on the visor
*
* Most methods in tfjs-vis that take a surface also take a SurfaceInfo
* so you rarely need to call this method unless you want to make a custom
* plot.
*
* ```js
* // Create a surface on a tab
* tfvis.visor().surface({name: 'My Surface', tab: 'My Tab'});
* ```
*
* ```js
* // Create a surface and specify its height
* tfvis.visor().surface({name: 'Custom Height', tab: 'My Tab', styles: {
* height: 500
* }})
* ```
*
* @param options
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
surface(options) {
const { name } = options;
const tab = options.tab == null ? DEFAULT_TAB : options.tab;
if (name == null ||
// tslint:disable-next-line
!(typeof name === 'string' || name instanceof String)) {
throw new Error(
// tslint:disable-next-line
'You must pass a config object with a \'name\' property to create or retrieve a surface');
}
const finalOptions = Object.assign({}, options, { tab });
const key = `${name}-${tab}`;
if (!this.surfaceList.has(key)) {
this.surfaceList.set(key, finalOptions);
}
this.renderVisor(this.el, this.surfaceList);
return this.visorComponent.getSurface(name, tab);
}
/**
* Returns a boolean indicating if the visor is in 'fullscreen' mode
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
isFullscreen() {
return this.visorComponent.isFullscreen();
}
/**
* Returns a boolean indicating if the visor is open
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
isOpen() {
return this.visorComponent.isOpen();
}
/**
* Closes the visor.
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
close() {
return this.visorComponent.close();
}
/**
* Opens the visor.
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
open() {
return this.visorComponent.open();
}
/**
* Toggles the visor (closed vs open).
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
toggle() {
return this.visorComponent.toggle();
}
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
toggleFullScreen() {
return this.visorComponent.toggleFullScreen();
}
/**
* Binds the ~ (tilde) key to toggle the visor.
*
* This is called by default when the visor is initially created.
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
bindKeys() {
return this.visorComponent.bindKeys();
}
/**
* Unbinds the keyboard control to toggle the visor.
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
unbindKeys() {
return this.visorComponent.unbindKeys();
}
/**
* Sets the active tab for the visor.
*/
/** @doc {heading: 'Visor & Surfaces', subheading: 'Visor Methods'} */
setActiveTab(tabName) {
const tabs = this.visorComponent.state.tabs;
if (!tabs.has(tabName)) {
throw new Error(`Tab '${tabName}' does not exist`);
}
this.visorComponent.setState({ activeTab: tabName });
}
}
exports.Visor = Visor;
//# sourceMappingURL=visor.js.map
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isSurfaceInfo(drawable) {
if (drawable.name != null) {
return true;
}
return false;
}
exports.isSurfaceInfo = isSurfaceInfo;
function isSurface(drawable) {
if (drawable.drawArea instanceof HTMLElement) {
return true;
}
return false;
}
exports.isSurface = isSurface;
//# sourceMappingURL=types.js.map
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = capitalizeString;
function capitalizeString(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
module.exports = exports["default"];
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var emptyFunction = __webpack_require__(462);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (false) { var printWarning; }
module.exports = warning;
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.processStyleName = undefined;
exports.createMarkupForStyles = createMarkupForStyles;
var _camelizeStyleName = __webpack_require__(466);
var _camelizeStyleName2 = _interopRequireDefault(_camelizeStyleName);
var _dangerousStyleValue = __webpack_require__(464);
var _dangerousStyleValue2 = _interopRequireDefault(_dangerousStyleValue);
var _hyphenateStyleName = __webpack_require__(461);
var _hyphenateStyleName2 = _interopRequireDefault(_hyphenateStyleName);
var _memoizeStringOnly = __webpack_require__(459);
var _memoizeStringOnly2 = _interopRequireDefault(_memoizeStringOnly);
var _warning = __webpack_require__(239);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var processStyleName = exports.processStyleName = (0, _memoizeStringOnly2.default)(_hyphenateStyleName2.default); /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSPropertyOperations
*/
if (false) { var warnValidStyle, checkRenderMessage, warnStyleValueIsNaN, warnStyleValueWithSemicolon, warnBadVendoredStyleName, warnHyphenatedStyleName, warnedForNaNValue, warnedStyleValues, warnedStyleNames, badStyleValueWithSemicolonPattern, badVendoredStyleNamePattern; }
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @param {ReactDOMComponent} component
* @return {?string}
*/
function createMarkupForStyles(styles, component) {
var serialized = '';
for (var styleName in styles) {
var isCustomProp = styleName.indexOf('--') === 0;
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if (styleName === 'label') {
continue;
}
var styleValue = styles[styleName];
if (false) {}
if (styleValue != null) {
if (isCustomProp) {
serialized += styleName + ':' + styleValue + ';';
} else {
serialized += processStyleName(styleName) + ':';
serialized += (0, _dangerousStyleValue2.default)(styleName, styleValue, component) + ';';
}
}
}
return serialized || null;
}
/***/ }),
/* 241 */
/***/ (function(module) {
module.exports = {"a":"5.4.0"};
/***/ }),
/* 242 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return band; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "point", function() { return point; });
/* harmony import */ var d3_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
/* harmony import */ var _init_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(null);
/* harmony import */ var _ordinal_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(null);
function band() {
var scale = Object(_ordinal_js__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])().unknown(undefined),
domain = scale.domain,
ordinalRange = scale.range,
r0 = 0,
r1 = 1,
step,
bandwidth,
round = false,
paddingInner = 0,
paddingOuter = 0,
align = 0.5;
delete scale.unknown;
function rescale() {
var n = domain().length,
reverse = r1 < r0,
start = reverse ? r1 : r0,
stop = reverse ? r0 : r1;
step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
if (round) step = Math.floor(step);
start += (stop - start - step * (n - paddingInner)) * align;
bandwidth = step * (1 - paddingInner);
if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);
var values = Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(n).map(function(i) { return start + step * i; });
return ordinalRange(reverse ? values.reverse() : values);
}
scale.domain = function(_) {
return arguments.length ? (domain(_), rescale()) : domain();
};
scale.range = function(_) {
return arguments.length ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
};
scale.rangeRound = function(_) {
return [r0, r1] = _, r0 = +r0, r1 = +r1, round = true, rescale();
};
scale.bandwidth = function() {
return bandwidth;
};
scale.step = function() {
return step;
};
scale.round = function(_) {
return arguments.length ? (round = !!_, rescale()) : round;
};
scale.padding = function(_) {
return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
};
scale.paddingInner = function(_) {
return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
};
scale.paddingOuter = function(_) {
return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
};
scale.align = function(_) {
return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
};
scale.copy = function() {
return band(domain(), [r0, r1])
.round(round)
.paddingInner(paddingInner)
.paddingOuter(paddingOuter)
.align(align);
};
return _init_js__WEBPACK_IMPORTED_MODULE_1__[/* initRange */ "a"].apply(rescale(), arguments);
}
function pointish(scale) {
var copy = scale.copy;
scale.padding = scale.paddingOuter;
delete scale.paddingInner;
delete scale.paddingOuter;
scale.copy = function() {
return pointish(copy());
};
return scale;
}
function point() {
return pointish(band.apply(null, arguments).paddingInner(1));
}
/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
const barchart_1 = __webpack_require__(474);
const confusion_matrix_1 = __webpack_require__(436);
const heatmap_1 = __webpack_require__(435);
const histogram_1 = __webpack_require__(154);
const linechart_1 = __webpack_require__(235);
const scatterplot_1 = __webpack_require__(434);
const table_1 = __webpack_require__(118);
const history_1 = __webpack_require__(433);
const model_1 = __webpack_require__(432);
const quality_1 = __webpack_require__(431);
const tensor_1 = __webpack_require__(430);
const math_1 = __webpack_require__(119);
const version_1 = __webpack_require__(429);
exports.version_vis = version_1.version;
const render = {
barchart: barchart_1.barchart,
table: table_1.table,
histogram: histogram_1.histogram,
linechart: linechart_1.linechart,
scatterplot: scatterplot_1.scatterplot,
confusionMatrix: confusion_matrix_1.confusionMatrix,
heatmap: heatmap_1.heatmap,
};
exports.render = render;
const metrics = {
accuracy: math_1.accuracy,
perClassAccuracy: math_1.perClassAccuracy,
confusionMatrix: math_1.confusionMatrix,
};
exports.metrics = metrics;
const show = {
history: history_1.history,
fitCallbacks: history_1.fitCallbacks,
perClassAccuracy: quality_1.showPerClassAccuracy,
valuesDistribution: tensor_1.valuesDistribution,
layer: model_1.layer,
modelSummary: model_1.modelSummary,
};
exports.show = show;
var visor_1 = __webpack_require__(236);
exports.visor = visor_1.visor;
__export(__webpack_require__(237));
//# sourceMappingURL=index.js.map
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(481);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53)))
/***/ }),
/* 245 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(67);
var toIObject = __webpack_require__(66);
var arrayIndexOf = __webpack_require__(486)(false);
var IE_PROTO = __webpack_require__(160)('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 246 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(32) && !__webpack_require__(68)(function () {
return Object.defineProperty(__webpack_require__(165)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 247 */
/***/ (function(module, exports) {
// https://rwaldron.github.io/proposal-math-extensions/
module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) {
if (
arguments.length === 0
// eslint-disable-next-line no-self-compare
|| x != x
// eslint-disable-next-line no-self-compare
|| inLow != inLow
// eslint-disable-next-line no-self-compare
|| inHigh != inHigh
// eslint-disable-next-line no-self-compare
|| outLow != outLow
// eslint-disable-next-line no-self-compare
|| outHigh != outHigh
) return NaN;
if (x === Infinity || x === -Infinity) return x;
return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow;
};
/***/ }),
/* 248 */
/***/ (function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(71);
module.exports = function (iter, ITERATOR) {
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __webpack_require__(93);
var from = __webpack_require__(248);
module.exports = function (NAME) {
return function toJSON() {
if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
/***/ }),
/* 250 */
/***/ (function(module, exports, __webpack_require__) {
var DESCRIPTORS = __webpack_require__(19);
var getKeys = __webpack_require__(77);
var toIObject = __webpack_require__(35);
var isEnum = __webpack_require__(112).f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!DESCRIPTORS || isEnum.call(O, key)) {
result.push(isEntries ? [key, O[key]] : O[key]);
}
}
return result;
};
};
/***/ }),
/* 251 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(17);
var repeat = __webpack_require__(184);
var defined = __webpack_require__(51);
module.exports = function (that, maxLength, fillString, left) {
var S = String(defined(that));
var stringLength = S.length;
var fillStr = fillString === undefined ? ' ' : String(fillString);
var intMaxLength = toLength(maxLength);
if (intMaxLength <= stringLength || fillStr == '') return S;
var fillLen = intMaxLength - stringLength;
var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
var isArray = __webpack_require__(134);
var isObject = __webpack_require__(13);
var toLength = __webpack_require__(17);
var ctx = __webpack_require__(43);
var IS_CONCAT_SPREADABLE = __webpack_require__(16)('isConcatSpreadable');
function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) {
var targetIndex = start;
var sourceIndex = 0;
var mapFn = mapper ? ctx(mapper, thisArg, 3) : false;
var element, spreadable;
while (sourceIndex < sourceLen) {
if (sourceIndex in source) {
element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
spreadable = false;
if (isObject(element)) {
spreadable = element[IS_CONCAT_SPREADABLE];
spreadable = spreadable !== undefined ? !!spreadable : isArray(element);
}
if (spreadable && depth > 0) {
targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
} else {
if (targetIndex >= 0x1fffffffffffff) throw TypeError();
target[targetIndex] = element;
}
targetIndex++;
}
sourceIndex++;
}
return targetIndex;
}
module.exports = flattenIntoArray;
/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(74);
var gOPS = __webpack_require__(135);
var anObject = __webpack_require__(6);
var Reflect = __webpack_require__(11).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) {
var keys = gOPN.f(anObject(it));
var getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ }),
/* 254 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/ecma262/#sec-toindex
var toInteger = __webpack_require__(41);
var toLength = __webpack_require__(17);
module.exports = function (it) {
if (it === undefined) return 0;
var number = toInteger(it);
var length = toLength(number);
if (number !== length) throw RangeError('Wrong length!');
return length;
};
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var redefineAll = __webpack_require__(70);
var getWeak = __webpack_require__(62).getWeak;
var anObject = __webpack_require__(6);
var isObject = __webpack_require__(13);
var anInstance = __webpack_require__(72);
var forOf = __webpack_require__(71);
var createArrayMethod = __webpack_require__(49);
var $has = __webpack_require__(36);
var validate = __webpack_require__(69);
var arrayFind = createArrayMethod(5);
var arrayFindIndex = createArrayMethod(6);
var id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function (that) {
return that._l || (that._l = new UncaughtFrozenStore());
};
var UncaughtFrozenStore = function () {
this.a = [];
};
var findUncaughtFrozen = function (store, key) {
return arrayFind(store.a, function (it) {
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function (key) {
var entry = findUncaughtFrozen(this, key);
if (entry) return entry[1];
},
has: function (key) {
return !!findUncaughtFrozen(this, key);
},
set: function (key, value) {
var entry = findUncaughtFrozen(this, key);
if (entry) entry[1] = value;
else this.a.push([key, value]);
},
'delete': function (key) {
var index = arrayFindIndex(this.a, function (it) {
return it[0] === key;
});
if (~index) this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function (key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key) {
if (!isObject(key)) return false;
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function (that, key, value) {
var data = getWeak(anObject(key), true);
if (data === true) uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(11);
var each = __webpack_require__(49)(0);
var redefine = __webpack_require__(30);
var meta = __webpack_require__(62);
var assign = __webpack_require__(277);
var weak = __webpack_require__(255);
var isObject = __webpack_require__(13);
var validate = __webpack_require__(69);
var NATIVE_WEAK_MAP = __webpack_require__(69);
var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global;
var WEAK_MAP = 'WeakMap';
var getWeak = meta.getWeak;
var isExtensible = Object.isExtensible;
var uncaughtFrozenStore = weak.ufstore;
var InternalMap;
var wrapper = function (get) {
return function WeakMap() {
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key) {
if (isObject(key)) {
var data = getWeak(key);
if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value) {
return weak.def(validate(this, WEAK_MAP), key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(127)(WEAK_MAP, wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if (NATIVE_WEAK_MAP && IS_IE11) {
InternalMap = weak.getConstructor(wrapper, WEAK_MAP);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function (key) {
var proto = $WeakMap.prototype;
var method = proto[key];
redefine(proto, key, function (a, b) {
// store frozen objects on internal weakmap shim
if (isObject(a) && !isExtensible(a)) {
if (!this._f) this._f = new InternalMap();
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var strong = __webpack_require__(258);
var validate = __webpack_require__(69);
var SET = 'Set';
// 23.2 Set Objects
module.exports = __webpack_require__(127)(SET, function (get) {
return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value) {
return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var dP = __webpack_require__(21).f;
var create = __webpack_require__(75);
var redefineAll = __webpack_require__(70);
var ctx = __webpack_require__(43);
var anInstance = __webpack_require__(72);
var forOf = __webpack_require__(71);
var $iterDefine = __webpack_require__(181);
var step = __webpack_require__(264);
var setSpecies = __webpack_require__(73);
var DESCRIPTORS = __webpack_require__(19);
var fastKey = __webpack_require__(62).fastKey;
var validate = __webpack_require__(69);
var SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function (that, key) {
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return that._i[index];
// frozen object case
for (entry = that._f; entry; entry = entry.n) {
if (entry.k == key) return entry;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear() {
for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
entry.r = true;
if (entry.p) entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function (key) {
var that = validate(this, NAME);
var entry = getEntry(that, key);
if (entry) {
var next = entry.n;
var prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if (prev) prev.n = next;
if (next) next.p = prev;
if (that._f == entry) that._f = next;
if (that._l == entry) that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /* , that = undefined */) {
validate(this, NAME);
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
var entry;
while (entry = entry ? entry.n : this._f) {
f(entry.v, entry.k, this);
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key) {
return !!getEntry(validate(this, NAME), key);
}
});
if (DESCRIPTORS) dP(C.prototype, 'size', {
get: function () {
return validate(this, NAME)[SIZE];
}
});
return C;
},
def: function (that, key, value) {
var entry = getEntry(that, key);
var prev, index;
// change existing entry
if (entry) {
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if (!that._f) that._f = entry;
if (prev) prev.n = entry;
that[SIZE]++;
// add to index
if (index !== 'F') that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function (C, NAME, IS_MAP) {
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function (iterated, kind) {
this._t = validate(iterated, NAME); // target
this._k = kind; // kind
this._l = undefined; // previous
}, function () {
var that = this;
var kind = that._k;
var entry = that._l;
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
// get next entry
if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if (kind == 'keys') return step(0, entry.k);
if (kind == 'values') return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var strong = __webpack_require__(258);
var validate = __webpack_require__(69);
var MAP = 'Map';
// 23.1 Map Objects
module.exports = __webpack_require__(127)(MAP, function (get) {
return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key) {
var entry = strong.getEntry(validate(this, MAP), key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value) {
return strong.def(validate(this, MAP), key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(6);
var isObject = __webpack_require__(13);
var newPromiseCapability = __webpack_require__(167);
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
/***/ }),
/* 261 */
/***/ (function(module, exports) {
module.exports = function (exec) {
try {
return { e: false, v: exec() };
} catch (e) {
return { e: true, v: e };
}
};
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if (__webpack_require__(19) && /./g.flags != 'g') __webpack_require__(21).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(111)
});
/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var regexpExec = __webpack_require__(171);
__webpack_require__(5)({
target: 'RegExp',
proto: true,
forced: regexpExec !== /./.exec
}, {
exec: regexpExec
});
/***/ }),
/* 264 */
/***/ (function(module, exports) {
module.exports = function (done, value) {
return { value: value, done: !!done };
};
/***/ }),
/* 265 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var toObject = __webpack_require__(22);
var toAbsoluteIndex = __webpack_require__(76);
var toLength = __webpack_require__(17);
module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {
var O = toObject(this);
var len = toLength(O.length);
var to = toAbsoluteIndex(target, len);
var from = toAbsoluteIndex(start, len);
var end = arguments.length > 2 ? arguments[2] : undefined;
var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);
var inc = 1;
if (from < to && to < from + count) {
inc = -1;
from += count - 1;
to += count - 1;
}
while (count-- > 0) {
if (from in O) O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(27);
var toObject = __webpack_require__(22);
var IObject = __webpack_require__(113);
var toLength = __webpack_require__(17);
module.exports = function (that, callbackfn, aLen, memo, isRight) {
aFunction(callbackfn);
var O = toObject(that);
var self = IObject(O);
var length = toLength(O.length);
var index = isRight ? length - 1 : 0;
var i = isRight ? -1 : 1;
if (aLen < 2) for (;;) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (isRight ? index < 0 : length <= index) {
throw TypeError('Reduce of empty array with no initial value');
}
}
for (;isRight ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(6);
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var sign = __webpack_require__(183);
var pow = Math.pow;
var EPSILON = pow(2, -52);
var EPSILON32 = pow(2, -23);
var MAX32 = pow(2, 127) * (2 - EPSILON32);
var MIN32 = pow(2, -126);
var roundTiesToEven = function (n) {
return n + 1 / EPSILON - 1 / EPSILON;
};
module.exports = Math.fround || function fround(x) {
var $abs = Math.abs(x);
var $sign = sign(x);
var a, result;
if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
// eslint-disable-next-line no-self-compare
if (result > MAX32 || result != result) return $sign * Infinity;
return $sign * result;
};
/***/ }),
/* 269 */
/***/ (function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x) {
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(13);
var floor = Math.floor;
module.exports = function isInteger(it) {
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
var cof = __webpack_require__(42);
module.exports = function (it, msg) {
if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg);
return +it;
};
/***/ }),
/* 272 */
/***/ (function(module, exports, __webpack_require__) {
var $parseFloat = __webpack_require__(11).parseFloat;
var $trim = __webpack_require__(92).trim;
module.exports = 1 / $parseFloat(__webpack_require__(186) + '-0') !== -Infinity ? function parseFloat(str) {
var string = $trim(String(str), 3);
var result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
var $parseInt = __webpack_require__(11).parseInt;
var $trim = __webpack_require__(92).trim;
var ws = __webpack_require__(186);
var hex = /^[-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) {
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
/***/ }),
/* 274 */
/***/ (function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
var un = that === undefined;
switch (args.length) {
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var aFunction = __webpack_require__(27);
var isObject = __webpack_require__(13);
var invoke = __webpack_require__(274);
var arraySlice = [].slice;
var factories = {};
var construct = function (F, len, args) {
if (!(len in factories)) {
for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']';
// eslint-disable-next-line no-new-func
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /* , ...args */) {
var fn = aFunction(this);
var partArgs = arraySlice.call(arguments, 1);
var bound = function (/* args... */) {
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if (isObject(fn.prototype)) bound.prototype = fn.prototype;
return bound;
};
/***/ }),
/* 276 */
/***/ (function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var DESCRIPTORS = __webpack_require__(19);
var getKeys = __webpack_require__(77);
var gOPS = __webpack_require__(135);
var pIE = __webpack_require__(112);
var toObject = __webpack_require__(22);
var IObject = __webpack_require__(113);
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(12)(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
}
} return T;
} : $assign;
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(35);
var gOPN = __webpack_require__(74).f;
var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(21);
var anObject = __webpack_require__(6);
var getKeys = __webpack_require__(77);
module.exports = __webpack_require__(19) ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
var has = __webpack_require__(36);
var toIObject = __webpack_require__(35);
var arrayIndexOf = __webpack_require__(136)(false);
var IE_PROTO = __webpack_require__(190)('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(16);
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(19) && !__webpack_require__(12)(function () {
return Object.defineProperty(__webpack_require__(192)('div'), 'a', { get: function () { return 7; } }).a != 7;
});
/***/ }),
/* 283 */
/***/ (function(module) {
module.exports = {"name":"vega-tooltip","version":"0.19.1","description":"A tooltip plugin for Vega-Lite and Vega visualizations.","main":"build/vega-tooltip.js","module":"build/src/index.js","unpkg":"build/vega-tooltip.min.js","jsdelivr":"build/vega-tooltip.min.js","typings":"build/src/index.d.ts","repository":{"type":"git","url":"https://github.com/vega/vega-tooltip.git"},"keywords":["vega-lite","vega","tooltip"],"author":{"name":"UW Interactive Data Lab","url":"https://idl.cs.washington.edu"},"collaborators":["Dominik Moritz","Sira Horradarn","Zening Qu","Kanit Wongsuphasawat","Yuri Astrakhan","Jeffrey Heer"],"license":"BSD-3-Clause","bugs":{"url":"https://github.com/vega/vega-tooltip/issues"},"homepage":"https://github.com/vega/vega-tooltip#readme","scripts":{"prepare":"beemo create-config --silent","tsc:src":"tsc -b tsconfig.src.json","build":"yarn tsc:src && rollup -c","clean":"rm -rf build examples/data && rm -f src/style.ts","copy:data":"rsync -r node_modules/vega-datasets/data/* examples/data","copy:build":"rsync -r build/* examples/build","deploy:gh":"yarn build && yarn copy:build && gh-pages -d examples && yarn clean","prettierbase":"beemo prettier 'examples/*.{html,scss,css}'","eslintbase":"beemo eslint '{src,test,types}/**/*.ts'","format":"yarn eslintbase --fix && yarn prettierbase --write","lint":"yarn eslintbase && yarn prettierbase --check","postbuild":"terser build/vega-tooltip.js -c -m -o build/vega-tooltip.min.js","prebuild":"mkdir -p build && yarn copy:data && ./build-style.sh","prepublishOnly":"yarn clean && yarn build","preversion":"yarn lint","start":"yarn build && concurrently --kill-others -n Server,Typescript,Rollup 'browser-sync start -s -f build examples --serveStatic examples' 'yarn tsc:src -w' 'rollup -c -w'","pretest":"./build-style.sh","test":"jest"},"devDependencies":{"@types/jest":"^24.0.18","browser-sync":"^2.26.7","concurrently":"^4.1.2","gh-pages":"^2.1.1","jest":"^24.9.0","node-sass":"^4.12.0","path":"^0.12.7","rollup":"^1.20.3","rollup-plugin-commonjs":"^10.1.0","rollup-plugin-json":"^4.0.0","rollup-plugin-node-resolve":"^5.2.0","terser":"^4.2.1","ts-jest":"^24.0.2","typescript":"^3.6.2","vega-datasets":"^1.25.0","vega-lite-dev-config":"^0.2.5","vega-typings":"^0.8.1"},"dependencies":{"vega-util":"^1.11.1"},"beemo":{"module":"vega-lite-dev-config","drivers":["prettier","eslint"]},"jest":{"testURL":"http://localhost/","transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testPathIgnorePatterns":["node_modules","<rootDir>/build","src"]}};
/***/ }),
/* 284 */
/***/ (function(module) {
module.exports = {"name":"vega-themes","version":"2.8.3","description":"Themes for stylized Vega and Vega-Lite visualizations.","keywords":["vega","vega-lite","themes","style"],"license":"BSD-3-Clause","author":{"name":"UW Interactive Data Lab","url":"https://idl.cs.washington.edu"},"contributors":[{"name":"Emily Gu","url":"https://github.com/emilygu"},{"name":"Arvind Satyanarayan","url":"http://arvindsatya.com"},{"name":"Jeffrey Heer","url":"https://idl.cs.washington.edu"},{"name":"Dominik Moritz","url":"https://www.domoritz.de"}],"main":"build/vega-themes.js","module":"build/src/index.js","unpkg":"build/vega-themes.min.js","jsdelivr":"build/vega-themes.min.js","typings":"build/src/index.d.ts","repository":{"type":"git","url":"https://github.com/vega/vega-themes.git"},"scripts":{"prepare":"beemo create-config --silent","clean":"rm -rf build examples/build","prettierbase":"beemo prettier 'examples/*.{html,scss,css}'","eslintbase":"beemo eslint 'src/**/*.ts'","format":"yarn eslintbase --fix && yarn prettierbase --write","lint":"yarn eslintbase && yarn prettierbase --check","prebuild":"mkdir -p build","build":"tsc && rollup -c","postbuild":"terser build/vega-themes.js -cm > build/vega-themes.min.js","deploy:gh":"yarn build && mkdir -p examples/build && rsync -r build/* examples/build && gh-pages -d examples","prepublishOnly":"yarn clean && yarn build","preversion":"yarn lint","serve":"browser-sync start -s -f build examples --serveStatic examples","start":"yarn build && concurrently --kill-others -n Server,Typescript,Rollup 'yarn serve' 'tsc -w' 'rollup -c -w'"},"devDependencies":{"@rollup/plugin-json":"^4.0.2","browser-sync":"^2.26.7","concurrently":"^5.1.0","gh-pages":"^2.2.0","rollup":"^2.1.0","terser":"^4.6.7","typescript":"^3.8.3","vega":"^5.10.0","vega-lite":"^4.8.1","vega-lite-dev-config":"^0.5.0"},"peerDependencies":{"vega":"*","vega-lite":"*"},"beemo":{"module":"vega-lite-dev-config","drivers":["prettier","eslint"]}};
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// do not edit .js files directly - edit src/index.jst
module.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {var clone = (function() {
'use strict';
function _instanceof(obj, type) {
return type != null && obj instanceof type;
}
var nativeMap;
try {
nativeMap = Map;
} catch(_) {
// maybe a reference error because no `Map`. Give it a dummy value that no
// value will ever be an instanceof.
nativeMap = function() {};
}
var nativeSet;
try {
nativeSet = Set;
} catch(_) {
nativeSet = function() {};
}
var nativePromise;
try {
nativePromise = Promise;
} catch(_) {
nativePromise = function() {};
}
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
* @param `includeNonEnumerable` - set to true if the non-enumerable properties
* should be cloned as well. Non-enumerable properties on the prototype
* chain will be ignored. (optional - false by default)
*/
function clone(parent, circular, depth, prototype, includeNonEnumerable) {
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
includeNonEnumerable = circular.includeNonEnumerable;
circular = circular.circular;
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (_instanceof(parent, nativeMap)) {
child = new nativeMap();
} else if (_instanceof(parent, nativeSet)) {
child = new nativeSet();
} else if (_instanceof(parent, nativePromise)) {
child = new nativePromise(function (resolve, reject) {
parent.then(function(value) {
resolve(_clone(value, depth - 1));
}, function(err) {
reject(_clone(err, depth - 1));
});
});
} else if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
if (Buffer.allocUnsafe) {
// Node.js >= 4.5.0
child = Buffer.allocUnsafe(parent.length);
} else {
// Older Node.js versions
child = new Buffer(parent.length);
}
parent.copy(child);
return child;
} else if (_instanceof(parent, Error)) {
child = Object.create(parent);
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
if (_instanceof(parent, nativeMap)) {
parent.forEach(function(value, key) {
var keyChild = _clone(key, depth - 1);
var valueChild = _clone(value, depth - 1);
child.set(keyChild, valueChild);
});
}
if (_instanceof(parent, nativeSet)) {
parent.forEach(function(value) {
var entryChild = _clone(value, depth - 1);
child.add(entryChild);
});
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(parent);
for (var i = 0; i < symbols.length; i++) {
// Don't need to worry about cloning a symbol because it is a primitive,
// like a number or string.
var symbol = symbols[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
continue;
}
child[symbol] = _clone(parent[symbol], depth - 1);
if (!descriptor.enumerable) {
Object.defineProperty(child, symbol, {
enumerable: false
});
}
}
}
if (includeNonEnumerable) {
var allPropertyNames = Object.getOwnPropertyNames(parent);
for (var i = 0; i < allPropertyNames.length; i++) {
var propertyName = allPropertyNames[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
if (descriptor && descriptor.enumerable) {
continue;
}
child[propertyName] = _clone(parent[propertyName], depth - 1);
Object.defineProperty(child, propertyName, {
enumerable: false
});
}
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
}
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
}
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
}
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(86).Buffer))
/***/ }),
/* 287 */
/***/ (function(module) {
module.exports = {"name":"vega-lite","author":"Dominik Moritz, Kanit \"Ham\" Wongsuphasawat, Arvind Satyanarayan, Jeffrey Heer","version":"4.0.2","collaborators":["Kanit Wongsuphasawat (http://kanitw.yellowpigz.com)","Dominik Moritz (https://www.domoritz.de)","Arvind Satyanarayan (https://arvindsatya.com)","Jeffrey Heer (https://jheer.org)"],"homepage":"https://vega.github.io/vega-lite/","description":"Vega-Lite is a concise high-level language for interactive visualization.","main":"build/vega-lite.js","unpkg":"build/vega-lite.min.js","jsdelivr":"build/vega-lite.min.js","module":"build/src/index","types":"build/src/index.d.ts","bin":{"vl2png":"./bin/vl2png","vl2svg":"./bin/vl2svg","vl2vg":"./bin/vl2vg"},"directories":{"test":"test"},"scripts":{"build":"yarn build:only","build:only":"yarn tsc:src && rollup -c","postbuild":"terser build/vega-lite.js -cm --source-map content=build/vega-lite.js.map,filename=build/vega-lite.min.js.map -o build/vega-lite.min.js && yarn schema","prebuild:examples":"yarn build:only","build:examples":"yarn data && TZ=America/Los_Angeles scripts/build-examples.sh","prebuild:examples-full":"yarn build:only","build:examples-full":"TZ=America/Los_Angeles scripts/build-examples.sh 1","build:example":"TZ=America/Los_Angeles scripts/build-example.sh","build:toc":"yarn build:jekyll && scripts/generate-toc","build:site":"yarn tsc:site && rollup -c site/rollup.config.js","build:jekyll":"pushd site && bundle exec jekyll build -q && popd","build:versions":"scripts/update-version.sh","clean":"find build ! -name 'vega-lite-schema.json' -type f -delete && rm -rf site/data/* && rm -f examples/compiled/*.png && find site/examples ! -name 'index.md' ! -name 'data' -type f -delete","predeploy:site":"yarn presite","deploy:site":"gh-pages -d site","data":"rsync -r node_modules/vega-datasets/data/* site/data","schema":"mkdir -p build && ts-json-schema-generator -c -f tsconfig.json -p src/index.ts -t TopLevelSpec -k deprecated > build/vega-lite-schema.json && yarn renameschema && cp build/vega-lite-schema.json site/_data/","renameschema":"scripts/rename-schema.sh","presite":"yarn data && yarn schema && yarn build:site && yarn build:versions && scripts/create-example-pages.sh","site":"pushd site && bundle exec jekyll serve -I -l && popd","tsc:src":"tsc -b src/tsconfig.src.json","tsc:site":"tsc -b site/tsconfig.site.json","prettierbase":"prettier '**/*.{md,css,yml}'","eslintbase":"eslint --ext .ts .","format":"yarn eslintbase --fix && yarn prettierbase --write","lint":"yarn eslintbase && yarn prettierbase --check","test":"jest test/ && yarn lint && yarn schema && jest examples/ && yarn test:runtime","test:inspect":"node --inspect-brk ./node_modules/.bin/jest --runInBand test","test:runtime":"TZ=America/Los_Angeles jest test-runtime/","test:runtime:generate":"yarn build:only && rm -Rf test-runtime/resources && VL_GENERATE_TESTS=true yarn test:runtime","watch:build":"yarn build:only && concurrently --kill-others -n Typescript,Rollup 'yarn tsc:src -w' 'rollup -c -w'","watch:site":"concurrently --kill-others -n Typescript,Rollup 'yarn tsc:site -w' 'rollup -c site/rollup.config.js -w'","watch:test":"jest --watch"},"repository":{"type":"git","url":"https://github.com/vega/vega-lite.git"},"license":"BSD-3-Clause","bugs":{"url":"https://github.com/vega/vega-lite/issues"},"devDependencies":{"@commitlint/cli":"^8.2.0","@commitlint/config-conventional":"^8.2.0","@types/chai":"^4.2.6","@types/d3":"^5.7.2","@types/highlight.js":"^9.12.3","@types/jest":"^24.0.23","@types/jest-environment-puppeteer":"^4.3.1","@types/mkdirp":"^0.5.2","@types/puppeteer":"^2.0.0","@typescript-eslint/eslint-plugin":"^2.10.0","@typescript-eslint/parser":"^2.10.0","ajv":"^6.10.2","chai":"^4.2.0","cheerio":"^1.0.0-rc.2","codecov":"^3.6.1","concurrently":"^5.0.0","d3":"^5.14.2","eslint":"^6.7.2","eslint-config-prettier":"^6.7.0","eslint-plugin-prettier":"^3.1.1","gh-pages":"^2.1.1","highlight.js":"^9.16.2","http-server":"^0.12.0","husky":"^3.1.0","jest":"^24.9.0","jest-puppeteer":"^4.3.0","lint-staged":"^9.5.0","mkdirp":"^0.5.1","prettier":"^1.19.1","puppeteer":"^2.0.0","rollup":"^1.27.8","rollup-plugin-commonjs":"^10.1.0","rollup-plugin-json":"^4.0.0","rollup-plugin-node-resolve":"^5.2.0","rollup-plugin-sourcemaps":"^0.4.2","rollup-plugin-terser":"^5.1.2","svg2png-many":"^0.0.7","terser":"^4.4.2","ts-jest":"^24.2.0","ts-json-schema-generator":"^0.57.0","typescript":"~3.7.3","vega-cli":"^5.9.0","vega-datasets":"^1.28.0","vega-embed":"^6.2.0","vega-tooltip":"^0.19.1","yaml-front-matter":"^4.0.0"},"dependencies":{"@types/clone":"~0.1.30","@types/fast-json-stable-stringify":"^2.0.0","array-flat-polyfill":"^1.0.1","clone":"~2.1.2","fast-deep-equal":"~3.1.1","fast-json-stable-stringify":"~2.0.0","json-stringify-pretty-compact":"~2.0.0","tslib":"~1.10.0","vega-event-selector":"~2.0.2","vega-expression":"~2.6.3","vega-typings":"~0.12.0","vega-util":"~1.12.1","yargs":"~15.0.2"},"peerDependencies":{"vega":"^5.9.0"},"husky":{"hooks":{"pre-commit":"lint-staged","commit-msg":"commitlint -E HUSKY_GIT_PARAMS"}},"lint-staged":{"*.ts":["eslint --fix","git add"],"*.{md,css,yml}":["prettier --write","git add"]},"jest":{"preset":"jest-puppeteer","transform":{"^.+\\.tsx?$":"ts-jest"},"testRegex":"(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$","moduleFileExtensions":["ts","tsx","js","jsx","json","node"],"testPathIgnorePatterns":["<rootDir>/node_modules","<rootDir>/build","<rootDir>/_site","<rootDir>/src"],"coverageDirectory":"./coverage/","collectCoverage":false}};
/***/ }),
/* 288 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isoSpecifier", function() { return isoSpecifier; });
/* harmony import */ var _defaultLocale_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ";
function formatIsoNative(date) {
return date.toISOString();
}
var formatIso = Date.prototype.toISOString
? formatIsoNative
: Object(_defaultLocale_js__WEBPACK_IMPORTED_MODULE_0__[/* utcFormat */ "b"])(isoSpecifier);
/* harmony default export */ __webpack_exports__["default"] = (formatIso);
/***/ }),
/* 289 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";
/* harmony default export */ var namespaces = ({
svg: "http://www.w3.org/2000/svg",
xhtml: xhtml,
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/namespace.js
/* harmony default export */ var namespace = (function(name) {
var prefix = name += "", i = prefix.indexOf(":");
if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/creator.js
function creator_creatorInherit(name) {
return function() {
var document = this.ownerDocument,
uri = this.namespaceURI;
return uri === xhtml && document.documentElement.namespaceURI === xhtml
? document.createElement(name)
: document.createElementNS(uri, name);
};
}
function creator_creatorFixed(fullname) {
return function() {
return this.ownerDocument.createElementNS(fullname.space, fullname.local);
};
}
/* harmony default export */ var creator = (function(name) {
var fullname = namespace(name);
return (fullname.local
? creator_creatorFixed
: creator_creatorInherit)(fullname);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selector.js
function none() {}
/* harmony default export */ var src_selector = (function(selector) {
return selector == null ? none : function() {
return this.querySelector(selector);
};
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/select.js
/* harmony default export */ var selection_select = (function(select) {
if (typeof select !== "function") select = src_selector(select);
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {
if ("__data__" in node) subnode.__data__ = node.__data__;
subgroup[i] = subnode;
}
}
}
return new selection_Selection(subgroups, this._parents);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selectorAll.js
function empty() {
return [];
}
/* harmony default export */ var selectorAll = (function(selector) {
return selector == null ? empty : function() {
return this.querySelectorAll(selector);
};
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/selectAll.js
/* harmony default export */ var selectAll = (function(select) {
if (typeof select !== "function") select = selectorAll(select);
for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {
if (node = group[i]) {
subgroups.push(select.call(node, node.__data__, i, group));
parents.push(node);
}
}
}
return new selection_Selection(subgroups, parents);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/matcher.js
var matcher = function(selector) {
return function() {
return this.matches(selector);
};
};
if (typeof document !== "undefined") {
var matcher_element = document.documentElement;
if (!matcher_element.matches) {
var vendorMatches = matcher_element.webkitMatchesSelector
|| matcher_element.msMatchesSelector
|| matcher_element.mozMatchesSelector
|| matcher_element.oMatchesSelector;
matcher = function(selector) {
return function() {
return vendorMatches.call(this, selector);
};
};
}
}
/* harmony default export */ var src_matcher = (matcher);
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/filter.js
/* harmony default export */ var filter = (function(match) {
if (typeof match !== "function") match = src_matcher(match);
for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
if ((node = group[i]) && match.call(node, node.__data__, i, group)) {
subgroup.push(node);
}
}
}
return new selection_Selection(subgroups, this._parents);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/sparse.js
/* harmony default export */ var sparse = (function(update) {
return new Array(update.length);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/enter.js
/* harmony default export */ var selection_enter = (function() {
return new selection_Selection(this._enter || this._groups.map(sparse), this._parents);
});
function enter_EnterNode(parent, datum) {
this.ownerDocument = parent.ownerDocument;
this.namespaceURI = parent.namespaceURI;
this._next = null;
this._parent = parent;
this.__data__ = datum;
}
enter_EnterNode.prototype = {
constructor: enter_EnterNode,
appendChild: function(child) { return this._parent.insertBefore(child, this._next); },
insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },
querySelector: function(selector) { return this._parent.querySelector(selector); },
querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }
};
// CONCATENATED MODULE: ./node_modules/d3-selection/src/constant.js
/* harmony default export */ var constant = (function(x) {
return function() {
return x;
};
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/data.js
var data_keyPrefix = "$"; // Protect against keys like “__proto__”.
function data_bindIndex(parent, group, enter, update, exit, data) {
var i = 0,
node,
groupLength = group.length,
dataLength = data.length;
// Put any non-null nodes that fit into update.
// Put any null nodes into enter.
// Put any remaining data into enter.
for (; i < dataLength; ++i) {
if (node = group[i]) {
node.__data__ = data[i];
update[i] = node;
} else {
enter[i] = new enter_EnterNode(parent, data[i]);
}
}
// Put any non-null nodes that dont fit into exit.
for (; i < groupLength; ++i) {
if (node = group[i]) {
exit[i] = node;
}
}
}
function data_bindKey(parent, group, enter, update, exit, data, key) {
var i,
node,
nodeByKeyValue = {},
groupLength = group.length,
dataLength = data.length,
keyValues = new Array(groupLength),
keyValue;
// Compute the key for each node.
// If multiple nodes have the same key, the duplicates are added to exit.
for (i = 0; i < groupLength; ++i) {
if (node = group[i]) {
keyValues[i] = keyValue = data_keyPrefix + key.call(node, node.__data__, i, group);
if (keyValue in nodeByKeyValue) {
exit[i] = node;
} else {
nodeByKeyValue[keyValue] = node;
}
}
}
// Compute the key for each datum.
// If there a node associated with this key, join and add it to update.
// If there is not (or the key is a duplicate), add it to enter.
for (i = 0; i < dataLength; ++i) {
keyValue = data_keyPrefix + key.call(parent, data[i], i, data);
if (node = nodeByKeyValue[keyValue]) {
update[i] = node;
node.__data__ = data[i];
nodeByKeyValue[keyValue] = null;
} else {
enter[i] = new enter_EnterNode(parent, data[i]);
}
}
// Add any remaining nodes that were not bound to data to exit.
for (i = 0; i < groupLength; ++i) {
if ((node = group[i]) && (nodeByKeyValue[keyValues[i]] === node)) {
exit[i] = node;
}
}
}
/* harmony default export */ var selection_data = (function(value, key) {
if (!value) {
data = new Array(this.size()), j = -1;
this.each(function(d) { data[++j] = d; });
return data;
}
var bind = key ? data_bindKey : data_bindIndex,
parents = this._parents,
groups = this._groups;
if (typeof value !== "function") value = constant(value);
for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
var parent = parents[j],
group = groups[j],
groupLength = group.length,
data = value.call(parent, parent && parent.__data__, j, parents),
dataLength = data.length,
enterGroup = enter[j] = new Array(dataLength),
updateGroup = update[j] = new Array(dataLength),
exitGroup = exit[j] = new Array(groupLength);
bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
// Now connect the enter nodes to their following update node, such that
// appendChild can insert the materialized enter node before this node,
// rather than at the end of the parent node.
for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
if (previous = enterGroup[i0]) {
if (i0 >= i1) i1 = i0 + 1;
while (!(next = updateGroup[i1]) && ++i1 < dataLength);
previous._next = next || null;
}
}
}
update = new selection_Selection(update, parents);
update._enter = enter;
update._exit = exit;
return update;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/exit.js
/* harmony default export */ var selection_exit = (function() {
return new selection_Selection(this._exit || this._groups.map(sparse), this._parents);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/merge.js
/* harmony default export */ var selection_merge = (function(selection) {
for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group0[i] || group1[i]) {
merge[i] = node;
}
}
}
for (; j < m0; ++j) {
merges[j] = groups0[j];
}
return new selection_Selection(merges, this._parents);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/order.js
/* harmony default export */ var order = (function() {
for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {
for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {
if (node = group[i]) {
if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
next = node;
}
}
}
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/sort.js
/* harmony default export */ var sort = (function(compare) {
if (!compare) compare = sort_ascending;
function compareNode(a, b) {
return a && b ? compare(a.__data__, b.__data__) : !a - !b;
}
for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
if (node = group[i]) {
sortgroup[i] = node;
}
}
sortgroup.sort(compareNode);
}
return new selection_Selection(sortgroups, this._parents).order();
});
function sort_ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/call.js
/* harmony default export */ var call = (function() {
var callback = arguments[0];
arguments[0] = this;
callback.apply(null, arguments);
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/nodes.js
/* harmony default export */ var nodes = (function() {
var nodes = new Array(this.size()), i = -1;
this.each(function() { nodes[++i] = this; });
return nodes;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/node.js
/* harmony default export */ var selection_node = (function() {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {
var node = group[i];
if (node) return node;
}
}
return null;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/size.js
/* harmony default export */ var size = (function() {
var size = 0;
this.each(function() { ++size; });
return size;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/empty.js
/* harmony default export */ var selection_empty = (function() {
return !this.node();
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/each.js
/* harmony default export */ var each = (function(callback) {
for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {
if (node = group[i]) callback.call(node, node.__data__, i, group);
}
}
return this;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/attr.js
function attr_attrRemove(name) {
return function() {
this.removeAttribute(name);
};
}
function attr_attrRemoveNS(fullname) {
return function() {
this.removeAttributeNS(fullname.space, fullname.local);
};
}
function attr_attrConstant(name, value) {
return function() {
this.setAttribute(name, value);
};
}
function attr_attrConstantNS(fullname, value) {
return function() {
this.setAttributeNS(fullname.space, fullname.local, value);
};
}
function attr_attrFunction(name, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) this.removeAttribute(name);
else this.setAttribute(name, v);
};
}
function attr_attrFunctionNS(fullname, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
else this.setAttributeNS(fullname.space, fullname.local, v);
};
}
/* harmony default export */ var attr = (function(name, value) {
var fullname = namespace(name);
if (arguments.length < 2) {
var node = this.node();
return fullname.local
? node.getAttributeNS(fullname.space, fullname.local)
: node.getAttribute(fullname);
}
return this.each((value == null
? (fullname.local ? attr_attrRemoveNS : attr_attrRemove) : (typeof value === "function"
? (fullname.local ? attr_attrFunctionNS : attr_attrFunction)
: (fullname.local ? attr_attrConstantNS : attr_attrConstant)))(fullname, value));
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/window.js
/* harmony default export */ var src_window = (function(node) {
return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node
|| (node.document && node) // node is a Window
|| node.defaultView; // node is a Document
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/style.js
function style_styleRemove(name) {
return function() {
this.style.removeProperty(name);
};
}
function style_styleConstant(name, value, priority) {
return function() {
this.style.setProperty(name, value, priority);
};
}
function style_styleFunction(name, value, priority) {
return function() {
var v = value.apply(this, arguments);
if (v == null) this.style.removeProperty(name);
else this.style.setProperty(name, v, priority);
};
}
/* harmony default export */ var style = (function(name, value, priority) {
return arguments.length > 1
? this.each((value == null
? style_styleRemove : typeof value === "function"
? style_styleFunction
: style_styleConstant)(name, value, priority == null ? "" : priority))
: style_styleValue(this.node(), name);
});
function style_styleValue(node, name) {
return node.style.getPropertyValue(name)
|| src_window(node).getComputedStyle(node, null).getPropertyValue(name);
}
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/property.js
function propertyRemove(name) {
return function() {
delete this[name];
};
}
function propertyConstant(name, value) {
return function() {
this[name] = value;
};
}
function propertyFunction(name, value) {
return function() {
var v = value.apply(this, arguments);
if (v == null) delete this[name];
else this[name] = v;
};
}
/* harmony default export */ var property = (function(name, value) {
return arguments.length > 1
? this.each((value == null
? propertyRemove : typeof value === "function"
? propertyFunction
: propertyConstant)(name, value))
: this.node()[name];
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/classed.js
function classArray(string) {
return string.trim().split(/^|\s+/);
}
function classList(node) {
return node.classList || new ClassList(node);
}
function ClassList(node) {
this._node = node;
this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
add: function(name) {
var i = this._names.indexOf(name);
if (i < 0) {
this._names.push(name);
this._node.setAttribute("class", this._names.join(" "));
}
},
remove: function(name) {
var i = this._names.indexOf(name);
if (i >= 0) {
this._names.splice(i, 1);
this._node.setAttribute("class", this._names.join(" "));
}
},
contains: function(name) {
return this._names.indexOf(name) >= 0;
}
};
function classedAdd(node, names) {
var list = classList(node), i = -1, n = names.length;
while (++i < n) list.add(names[i]);
}
function classedRemove(node, names) {
var list = classList(node), i = -1, n = names.length;
while (++i < n) list.remove(names[i]);
}
function classedTrue(names) {
return function() {
classedAdd(this, names);
};
}
function classedFalse(names) {
return function() {
classedRemove(this, names);
};
}
function classedFunction(names, value) {
return function() {
(value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
};
}
/* harmony default export */ var classed = (function(name, value) {
var names = classArray(name + "");
if (arguments.length < 2) {
var list = classList(this.node()), i = -1, n = names.length;
while (++i < n) if (!list.contains(names[i])) return false;
return true;
}
return this.each((typeof value === "function"
? classedFunction : value
? classedTrue
: classedFalse)(names, value));
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/text.js
function textRemove() {
this.textContent = "";
}
function textConstant(value) {
return function() {
this.textContent = value;
};
}
function textFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
};
}
/* harmony default export */ var selection_text = (function(value) {
return arguments.length
? this.each(value == null
? textRemove : (typeof value === "function"
? textFunction
: textConstant)(value))
: this.node().textContent;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
this.innerHTML = "";
}
function htmlConstant(value) {
return function() {
this.innerHTML = value;
};
}
function htmlFunction(value) {
return function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
};
}
/* harmony default export */ var html = (function(value) {
return arguments.length
? this.each(value == null
? htmlRemove : (typeof value === "function"
? htmlFunction
: htmlConstant)(value))
: this.node().innerHTML;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/raise.js
function raise() {
if (this.nextSibling) this.parentNode.appendChild(this);
}
/* harmony default export */ var selection_raise = (function() {
return this.each(raise);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/lower.js
function lower() {
if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
/* harmony default export */ var selection_lower = (function() {
return this.each(lower);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/append.js
/* harmony default export */ var append = (function(name) {
var create = typeof name === "function" ? name : creator(name);
return this.select(function() {
return this.appendChild(create.apply(this, arguments));
});
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/insert.js
function insert_constantNull() {
return null;
}
/* harmony default export */ var insert = (function(name, before) {
var create = typeof name === "function" ? name : creator(name),
select = before == null ? insert_constantNull : typeof before === "function" ? before : src_selector(before);
return this.select(function() {
return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
});
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/remove.js
function remove() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
}
/* harmony default export */ var selection_remove = (function() {
return this.each(remove);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
return this.parentNode.insertBefore(this.cloneNode(false), this.nextSibling);
}
function selection_cloneDeep() {
return this.parentNode.insertBefore(this.cloneNode(true), this.nextSibling);
}
/* harmony default export */ var clone = (function(deep) {
return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/datum.js
/* harmony default export */ var datum = (function(value) {
return arguments.length
? this.property("__data__", value)
: this.node().__data__;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/on.js
var filterEvents = {};
var on_event = null;
if (typeof document !== "undefined") {
var on_element = document.documentElement;
if (!("onmouseenter" in on_element)) {
filterEvents = {mouseenter: "mouseover", mouseleave: "mouseout"};
}
}
function filterContextListener(listener, index, group) {
listener = contextListener(listener, index, group);
return function(event) {
var related = event.relatedTarget;
if (!related || (related !== this && !(related.compareDocumentPosition(this) & 8))) {
listener.call(this, event);
}
};
}
function contextListener(listener, index, group) {
return function(event1) {
var event0 = on_event; // Events can be reentrant (e.g., focus).
on_event = event1;
try {
listener.call(this, this.__data__, index, group);
} finally {
on_event = event0;
}
};
}
function parseTypenames(typenames) {
return typenames.trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
return {type: t, name: name};
});
}
function onRemove(typename) {
return function() {
var on = this.__on;
if (!on) return;
for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {
if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
this.removeEventListener(o.type, o.listener, o.capture);
} else {
on[++i] = o;
}
}
if (++i) on.length = i;
else delete this.__on;
};
}
function onAdd(typename, value, capture) {
var wrap = filterEvents.hasOwnProperty(typename.type) ? filterContextListener : contextListener;
return function(d, i, group) {
var on = this.__on, o, listener = wrap(value, i, group);
if (on) for (var j = 0, m = on.length; j < m; ++j) {
if ((o = on[j]).type === typename.type && o.name === typename.name) {
this.removeEventListener(o.type, o.listener, o.capture);
this.addEventListener(o.type, o.listener = listener, o.capture = capture);
o.value = value;
return;
}
}
this.addEventListener(typename.type, listener, capture);
o = {type: typename.type, name: typename.name, value: value, listener: listener, capture: capture};
if (!on) this.__on = [o];
else on.push(o);
};
}
/* harmony default export */ var on = (function(typename, value, capture) {
var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;
if (arguments.length < 2) {
var on = this.node().__on;
if (on) for (var j = 0, m = on.length, o; j < m; ++j) {
for (i = 0, o = on[j]; i < n; ++i) {
if ((t = typenames[i]).type === o.type && t.name === o.name) {
return o.value;
}
}
}
return;
}
on = value ? onAdd : onRemove;
if (capture == null) capture = false;
for (i = 0; i < n; ++i) this.each(on(typenames[i], value, capture));
return this;
});
function customEvent(event1, listener, that, args) {
var event0 = on_event;
event1.sourceEvent = on_event;
on_event = event1;
try {
return listener.apply(that, args);
} finally {
on_event = event0;
}
}
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/dispatch.js
function dispatch_dispatchEvent(node, type, params) {
var window = src_window(node),
event = window.CustomEvent;
if (typeof event === "function") {
event = new event(type, params);
} else {
event = window.document.createEvent("Event");
if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;
else event.initEvent(type, false, false);
}
node.dispatchEvent(event);
}
function dispatch_dispatchConstant(type, params) {
return function() {
return dispatch_dispatchEvent(this, type, params);
};
}
function dispatch_dispatchFunction(type, params) {
return function() {
return dispatch_dispatchEvent(this, type, params.apply(this, arguments));
};
}
/* harmony default export */ var dispatch = (function(type, params) {
return this.each((typeof params === "function"
? dispatch_dispatchFunction
: dispatch_dispatchConstant)(type, params));
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selection/index.js
var selection_root = [null];
function selection_Selection(groups, parents) {
this._groups = groups;
this._parents = parents;
}
function selection_selection() {
return new selection_Selection([[document.documentElement]], selection_root);
}
selection_Selection.prototype = selection_selection.prototype = {
constructor: selection_Selection,
select: selection_select,
selectAll: selectAll,
filter: filter,
data: selection_data,
enter: selection_enter,
exit: selection_exit,
merge: selection_merge,
order: order,
sort: sort,
call: call,
nodes: nodes,
node: selection_node,
size: size,
empty: selection_empty,
each: each,
attr: attr,
style: style,
property: property,
classed: classed,
text: selection_text,
html: html,
raise: selection_raise,
lower: selection_lower,
append: append,
insert: insert,
remove: selection_remove,
clone: clone,
datum: datum,
on: on,
dispatch: dispatch
};
/* harmony default export */ var src_selection = (selection_selection);
// CONCATENATED MODULE: ./node_modules/d3-selection/src/select.js
/* harmony default export */ var src_select = (function(selector) {
return typeof selector === "string"
? new selection_Selection([[document.querySelector(selector)]], [document.documentElement])
: new selection_Selection([[selector]], selection_root);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/create.js
/* harmony default export */ var src_create = (function(name) {
return src_select(creator(name).call(document.documentElement));
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/local.js
var nextId = 0;
function local() {
return new Local;
}
function Local() {
this._ = "@" + (++nextId).toString(36);
}
Local.prototype = local.prototype = {
constructor: Local,
get: function(node) {
var id = this._;
while (!(id in node)) if (!(node = node.parentNode)) return;
return node[id];
},
set: function(node, value) {
return node[this._] = value;
},
remove: function(node) {
return this._ in node && delete node[this._];
},
toString: function() {
return this._;
}
};
// CONCATENATED MODULE: ./node_modules/d3-selection/src/sourceEvent.js
/* harmony default export */ var sourceEvent = (function() {
var current = on_event, source;
while (source = current.sourceEvent) current = source;
return current;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/point.js
/* harmony default export */ var point = (function(node, event) {
var svg = node.ownerSVGElement || node;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
point.x = event.clientX, point.y = event.clientY;
point = point.matrixTransform(node.getScreenCTM().inverse());
return [point.x, point.y];
}
var rect = node.getBoundingClientRect();
return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/mouse.js
/* harmony default export */ var mouse = (function(node) {
var event = sourceEvent();
if (event.changedTouches) event = event.changedTouches[0];
return point(node, event);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/selectAll.js
/* harmony default export */ var src_selectAll = (function(selector) {
return typeof selector === "string"
? new selection_Selection([document.querySelectorAll(selector)], [document.documentElement])
: new selection_Selection([selector == null ? [] : selector], selection_root);
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/touch.js
/* harmony default export */ var src_touch = (function(node, touches, identifier) {
if (arguments.length < 3) identifier = touches, touches = sourceEvent().changedTouches;
for (var i = 0, n = touches ? touches.length : 0, touch; i < n; ++i) {
if ((touch = touches[i]).identifier === identifier) {
return point(node, touch);
}
}
return null;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/touches.js
/* harmony default export */ var src_touches = (function(node, touches) {
if (touches == null) touches = sourceEvent().touches;
for (var i = 0, n = touches ? touches.length : 0, points = new Array(n); i < n; ++i) {
points[i] = point(node, touches[i]);
}
return points;
});
// CONCATENATED MODULE: ./node_modules/d3-selection/src/index.js
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "create", function() { return src_create; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "creator", function() { return creator; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "local", function() { return local; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "matcher", function() { return src_matcher; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "mouse", function() { return mouse; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "namespace", function() { return namespace; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "namespaces", function() { return namespaces; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "clientPoint", function() { return point; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "select", function() { return src_select; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "selectAll", function() { return src_selectAll; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "selection", function() { return src_selection; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "selector", function() { return src_selector; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "selectorAll", function() { return selectorAll; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "style", function() { return style_styleValue; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "touch", function() { return src_touch; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "touches", function() { return src_touches; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "window", function() { return src_window; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "event", function() { return on_event; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "customEvent", function() { return customEvent; });
/***/ }),
/* 290 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var utils_namespaceObject = {};
__webpack_require__.d(utils_namespaceObject, "isTensor", function() { return utils_isTensor; });
__webpack_require__.d(utils_namespaceObject, "isTensor1D", function() { return utils_isTensor1D; });
__webpack_require__.d(utils_namespaceObject, "isTensor2D", function() { return utils_isTensor2D; });
__webpack_require__.d(utils_namespaceObject, "isTensor3D", function() { return utils_isTensor3D; });
__webpack_require__.d(utils_namespaceObject, "isTensor4D", function() { return utils_isTensor4D; });
__webpack_require__.d(utils_namespaceObject, "isFloat", function() { return utils_isFloat; });
__webpack_require__.d(utils_namespaceObject, "isEven", function() { return utils_isEven; });
__webpack_require__.d(utils_namespaceObject, "round", function() { return utils_round; });
__webpack_require__.d(utils_namespaceObject, "isDimensions", function() { return utils_isDimensions; });
__webpack_require__.d(utils_namespaceObject, "computeReshapedDimensions", function() { return utils_computeReshapedDimensions; });
__webpack_require__.d(utils_namespaceObject, "getCenterPoint", function() { return utils_getCenterPoint; });
__webpack_require__.d(utils_namespaceObject, "range", function() { return utils_range; });
__webpack_require__.d(utils_namespaceObject, "isValidNumber", function() { return utils_isValidNumber; });
__webpack_require__.d(utils_namespaceObject, "isValidProbablitiy", function() { return utils_isValidProbablitiy; });
var draw_namespaceObject = {};
__webpack_require__.d(draw_namespaceObject, "drawContour", function() { return drawContour; });
__webpack_require__.d(draw_namespaceObject, "drawDetections", function() { return drawDetections_drawDetections; });
__webpack_require__.d(draw_namespaceObject, "drawFaceExpressions", function() { return drawFaceExpressions_drawFaceExpressions; });
__webpack_require__.d(draw_namespaceObject, "DrawBoxOptions", function() { return DrawBox_DrawBoxOptions; });
__webpack_require__.d(draw_namespaceObject, "DrawBox", function() { return DrawBox_DrawBox; });
__webpack_require__.d(draw_namespaceObject, "DrawFaceLandmarksOptions", function() { return DrawFaceLandmarks_DrawFaceLandmarksOptions; });
__webpack_require__.d(draw_namespaceObject, "DrawFaceLandmarks", function() { return DrawFaceLandmarks_DrawFaceLandmarks; });
__webpack_require__.d(draw_namespaceObject, "drawFaceLandmarks", function() { return DrawFaceLandmarks_drawFaceLandmarks; });
__webpack_require__.d(draw_namespaceObject, "AnchorPosition", function() { return DrawTextField_AnchorPosition; });
__webpack_require__.d(draw_namespaceObject, "DrawTextFieldOptions", function() { return DrawTextField_DrawTextFieldOptions; });
__webpack_require__.d(draw_namespaceObject, "DrawTextField", function() { return DrawTextField_DrawTextField; });
// EXTERNAL MODULE: ./node_modules/face-api.js/node_modules/@tensorflow/tfjs-core/dist/tf-core.esm.js
var tf_core_esm = __webpack_require__(2);
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/drawContour.js
function drawContour(ctx, points, isClosed) {
if (isClosed === void 0) { isClosed = false; }
ctx.beginPath();
points.slice(1).forEach(function (_a, prevIdx) {
var x = _a.x, y = _a.y;
var from = points[prevIdx];
ctx.moveTo(from.x, from.y);
ctx.lineTo(x, y);
});
if (isClosed) {
var from = points[points.length - 1];
var to = points[0];
if (!from || !to) {
return;
}
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
}
ctx.stroke();
}
//# sourceMappingURL=drawContour.js.map
// EXTERNAL MODULE: ./node_modules/face-api.js/node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(3);
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/Dimensions.js
var Dimensions_Dimensions = /** @class */ (function () {
function Dimensions(width, height) {
if (!utils_isValidNumber(width) || !utils_isValidNumber(height)) {
throw new Error("Dimensions.constructor - expected width and height to be valid numbers, instead have " + JSON.stringify({ width: width, height: height }));
}
this._width = width;
this._height = height;
}
Object.defineProperty(Dimensions.prototype, "width", {
get: function () { return this._width; },
enumerable: true,
configurable: true
});
Object.defineProperty(Dimensions.prototype, "height", {
get: function () { return this._height; },
enumerable: true,
configurable: true
});
Dimensions.prototype.reverse = function () {
return new Dimensions(1 / this.width, 1 / this.height);
};
return Dimensions;
}());
//# sourceMappingURL=Dimensions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/utils/index.js
function utils_isTensor(tensor, dim) {
return tensor instanceof tf_core_esm["Tensor"] && tensor.shape.length === dim;
}
function utils_isTensor1D(tensor) {
return utils_isTensor(tensor, 1);
}
function utils_isTensor2D(tensor) {
return utils_isTensor(tensor, 2);
}
function utils_isTensor3D(tensor) {
return utils_isTensor(tensor, 3);
}
function utils_isTensor4D(tensor) {
return utils_isTensor(tensor, 4);
}
function utils_isFloat(num) {
return num % 1 !== 0;
}
function utils_isEven(num) {
return num % 2 === 0;
}
function utils_round(num, prec) {
if (prec === void 0) { prec = 2; }
var f = Math.pow(10, prec);
return Math.floor(num * f) / f;
}
function utils_isDimensions(obj) {
return obj && obj.width && obj.height;
}
function utils_computeReshapedDimensions(_a, inputSize) {
var width = _a.width, height = _a.height;
var scale = inputSize / Math.max(height, width);
return new Dimensions_Dimensions(Math.round(width * scale), Math.round(height * scale));
}
function utils_getCenterPoint(pts) {
return pts.reduce(function (sum, pt) { return sum.add(pt); }, new Point(0, 0))
.div(new Point(pts.length, pts.length));
}
function utils_range(num, start, step) {
return Array(num).fill(0).map(function (_, i) { return start + (i * step); });
}
function utils_isValidNumber(num) {
return !!num && num !== Infinity && num !== -Infinity && !isNaN(num) || num === 0;
}
function utils_isValidProbablitiy(num) {
return utils_isValidNumber(num) && 0 <= num && num <= 1.0;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/Point.js
var Point = /** @class */ (function () {
function Point(x, y) {
this._x = x;
this._y = y;
}
Object.defineProperty(Point.prototype, "x", {
get: function () { return this._x; },
enumerable: true,
configurable: true
});
Object.defineProperty(Point.prototype, "y", {
get: function () { return this._y; },
enumerable: true,
configurable: true
});
Point.prototype.add = function (pt) {
return new Point(this.x + pt.x, this.y + pt.y);
};
Point.prototype.sub = function (pt) {
return new Point(this.x - pt.x, this.y - pt.y);
};
Point.prototype.mul = function (pt) {
return new Point(this.x * pt.x, this.y * pt.y);
};
Point.prototype.div = function (pt) {
return new Point(this.x / pt.x, this.y / pt.y);
};
Point.prototype.abs = function () {
return new Point(Math.abs(this.x), Math.abs(this.y));
};
Point.prototype.magnitude = function () {
return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2));
};
Point.prototype.floor = function () {
return new Point(Math.floor(this.x), Math.floor(this.y));
};
return Point;
}());
//# sourceMappingURL=Point.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/Box.js
var Box_Box = /** @class */ (function () {
function Box(_box, allowNegativeDimensions) {
if (allowNegativeDimensions === void 0) { allowNegativeDimensions = true; }
var box = (_box || {});
var isBbox = [box.left, box.top, box.right, box.bottom].every(utils_isValidNumber);
var isRect = [box.x, box.y, box.width, box.height].every(utils_isValidNumber);
if (!isRect && !isBbox) {
throw new Error("Box.constructor - expected box to be IBoundingBox | IRect, instead have " + JSON.stringify(box));
}
var _a = isRect
? [box.x, box.y, box.width, box.height]
: [box.left, box.top, box.right - box.left, box.bottom - box.top], x = _a[0], y = _a[1], width = _a[2], height = _a[3];
Box.assertIsValidBox({ x: x, y: y, width: width, height: height }, 'Box.constructor', allowNegativeDimensions);
this._x = x;
this._y = y;
this._width = width;
this._height = height;
}
Box.isRect = function (rect) {
return !!rect && [rect.x, rect.y, rect.width, rect.height].every(utils_isValidNumber);
};
Box.assertIsValidBox = function (box, callee, allowNegativeDimensions) {
if (allowNegativeDimensions === void 0) { allowNegativeDimensions = false; }
if (!Box.isRect(box)) {
throw new Error(callee + " - invalid box: " + JSON.stringify(box) + ", expected object with properties x, y, width, height");
}
if (!allowNegativeDimensions && (box.width < 0 || box.height < 0)) {
throw new Error(callee + " - width (" + box.width + ") and height (" + box.height + ") must be positive numbers");
}
};
Object.defineProperty(Box.prototype, "x", {
get: function () { return this._x; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "y", {
get: function () { return this._y; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "width", {
get: function () { return this._width; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "height", {
get: function () { return this._height; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "left", {
get: function () { return this.x; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "top", {
get: function () { return this.y; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "right", {
get: function () { return this.x + this.width; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "bottom", {
get: function () { return this.y + this.height; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "area", {
get: function () { return this.width * this.height; },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "topLeft", {
get: function () { return new Point(this.left, this.top); },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "topRight", {
get: function () { return new Point(this.right, this.top); },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "bottomLeft", {
get: function () { return new Point(this.left, this.bottom); },
enumerable: true,
configurable: true
});
Object.defineProperty(Box.prototype, "bottomRight", {
get: function () { return new Point(this.right, this.bottom); },
enumerable: true,
configurable: true
});
Box.prototype.round = function () {
var _a = [this.x, this.y, this.width, this.height]
.map(function (val) { return Math.round(val); }), x = _a[0], y = _a[1], width = _a[2], height = _a[3];
return new Box({ x: x, y: y, width: width, height: height });
};
Box.prototype.floor = function () {
var _a = [this.x, this.y, this.width, this.height]
.map(function (val) { return Math.floor(val); }), x = _a[0], y = _a[1], width = _a[2], height = _a[3];
return new Box({ x: x, y: y, width: width, height: height });
};
Box.prototype.toSquare = function () {
var _a = this, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
var diff = Math.abs(width - height);
if (width < height) {
x -= (diff / 2);
width += diff;
}
if (height < width) {
y -= (diff / 2);
height += diff;
}
return new Box({ x: x, y: y, width: width, height: height });
};
Box.prototype.rescale = function (s) {
var scaleX = utils_isDimensions(s) ? s.width : s;
var scaleY = utils_isDimensions(s) ? s.height : s;
return new Box({
x: this.x * scaleX,
y: this.y * scaleY,
width: this.width * scaleX,
height: this.height * scaleY
});
};
Box.prototype.pad = function (padX, padY) {
var _a = [
this.x - (padX / 2),
this.y - (padY / 2),
this.width + padX,
this.height + padY
], x = _a[0], y = _a[1], width = _a[2], height = _a[3];
return new Box({ x: x, y: y, width: width, height: height });
};
Box.prototype.clipAtImageBorders = function (imgWidth, imgHeight) {
var _a = this, x = _a.x, y = _a.y, right = _a.right, bottom = _a.bottom;
var clippedX = Math.max(x, 0);
var clippedY = Math.max(y, 0);
var newWidth = right - clippedX;
var newHeight = bottom - clippedY;
var clippedWidth = Math.min(newWidth, imgWidth - clippedX);
var clippedHeight = Math.min(newHeight, imgHeight - clippedY);
return (new Box({ x: clippedX, y: clippedY, width: clippedWidth, height: clippedHeight })).floor();
};
Box.prototype.shift = function (sx, sy) {
var _a = this, width = _a.width, height = _a.height;
var x = this.x + sx;
var y = this.y + sy;
return new Box({ x: x, y: y, width: width, height: height });
};
Box.prototype.padAtBorders = function (imageHeight, imageWidth) {
var w = this.width + 1;
var h = this.height + 1;
var dx = 1;
var dy = 1;
var edx = w;
var edy = h;
var x = this.left;
var y = this.top;
var ex = this.right;
var ey = this.bottom;
if (ex > imageWidth) {
edx = -ex + imageWidth + w;
ex = imageWidth;
}
if (ey > imageHeight) {
edy = -ey + imageHeight + h;
ey = imageHeight;
}
if (x < 1) {
edy = 2 - x;
x = 1;
}
if (y < 1) {
edy = 2 - y;
y = 1;
}
return { dy: dy, edy: edy, dx: dx, edx: edx, y: y, ey: ey, x: x, ex: ex, w: w, h: h };
};
Box.prototype.calibrate = function (region) {
return new Box({
left: this.left + (region.left * this.width),
top: this.top + (region.top * this.height),
right: this.right + (region.right * this.width),
bottom: this.bottom + (region.bottom * this.height)
}).toSquare().round();
};
return Box;
}());
//# sourceMappingURL=Box.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/BoundingBox.js
var BoundingBox_BoundingBox = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(BoundingBox, _super);
function BoundingBox(left, top, right, bottom, allowNegativeDimensions) {
if (allowNegativeDimensions === void 0) { allowNegativeDimensions = false; }
return _super.call(this, { left: left, top: top, right: right, bottom: bottom }, allowNegativeDimensions) || this;
}
return BoundingBox;
}(Box_Box));
//# sourceMappingURL=BoundingBox.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/ObjectDetection.js
var ObjectDetection_ObjectDetection = /** @class */ (function () {
function ObjectDetection(score, classScore, className, relativeBox, imageDims) {
this._imageDims = new Dimensions_Dimensions(imageDims.width, imageDims.height);
this._score = score;
this._classScore = classScore;
this._className = className;
this._box = new Box_Box(relativeBox).rescale(this._imageDims);
}
Object.defineProperty(ObjectDetection.prototype, "score", {
get: function () { return this._score; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "classScore", {
get: function () { return this._classScore; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "className", {
get: function () { return this._className; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "box", {
get: function () { return this._box; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "imageDims", {
get: function () { return this._imageDims; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "imageWidth", {
get: function () { return this.imageDims.width; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "imageHeight", {
get: function () { return this.imageDims.height; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObjectDetection.prototype, "relativeBox", {
get: function () { return new Box_Box(this._box).rescale(this.imageDims.reverse()); },
enumerable: true,
configurable: true
});
ObjectDetection.prototype.forSize = function (width, height) {
return new ObjectDetection(this.score, this.classScore, this.className, this.relativeBox, { width: width, height: height });
};
return ObjectDetection;
}());
//# sourceMappingURL=ObjectDetection.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/FaceDetection.js
var FaceDetection_FaceDetection = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceDetection, _super);
function FaceDetection(score, relativeBox, imageDims) {
return _super.call(this, score, score, '', relativeBox, imageDims) || this;
}
FaceDetection.prototype.forSize = function (width, height) {
var _a = _super.prototype.forSize.call(this, width, height), score = _a.score, relativeBox = _a.relativeBox, imageDims = _a.imageDims;
return new FaceDetection(score, relativeBox, imageDims);
};
return FaceDetection;
}(ObjectDetection_ObjectDetection));
//# sourceMappingURL=FaceDetection.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/iou.js
function iou(box1, box2, isIOU) {
if (isIOU === void 0) { isIOU = true; }
var width = Math.max(0.0, Math.min(box1.right, box2.right) - Math.max(box1.left, box2.left));
var height = Math.max(0.0, Math.min(box1.bottom, box2.bottom) - Math.max(box1.top, box2.top));
var interSection = width * height;
return isIOU
? interSection / (box1.area + box2.area - interSection)
: interSection / Math.min(box1.area, box2.area);
}
//# sourceMappingURL=iou.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/minBbox.js
function minBbox_minBbox(pts) {
var xs = pts.map(function (pt) { return pt.x; });
var ys = pts.map(function (pt) { return pt.y; });
var minX = xs.reduce(function (min, x) { return x < min ? x : min; }, Infinity);
var minY = ys.reduce(function (min, y) { return y < min ? y : min; }, Infinity);
var maxX = xs.reduce(function (max, x) { return max < x ? x : max; }, 0);
var maxY = ys.reduce(function (max, y) { return max < y ? y : max; }, 0);
return new BoundingBox_BoundingBox(minX, minY, maxX, maxY);
}
//# sourceMappingURL=minBbox.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/nonMaxSuppression.js
function nonMaxSuppression_nonMaxSuppression(boxes, scores, iouThreshold, isIOU) {
if (isIOU === void 0) { isIOU = true; }
var indicesSortedByScore = scores
.map(function (score, boxIndex) { return ({ score: score, boxIndex: boxIndex }); })
.sort(function (c1, c2) { return c1.score - c2.score; })
.map(function (c) { return c.boxIndex; });
var pick = [];
var _loop_1 = function () {
var curr = indicesSortedByScore.pop();
pick.push(curr);
var indices = indicesSortedByScore;
var outputs = [];
for (var i = 0; i < indices.length; i++) {
var idx = indices[i];
var currBox = boxes[curr];
var idxBox = boxes[idx];
outputs.push(iou(currBox, idxBox, isIOU));
}
indicesSortedByScore = indicesSortedByScore.filter(function (_, j) { return outputs[j] <= iouThreshold; });
};
while (indicesSortedByScore.length > 0) {
_loop_1();
}
return pick;
}
//# sourceMappingURL=nonMaxSuppression.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/normalize.js
function normalize_normalize(x, meanRgb) {
return tf_core_esm["tidy"](function () {
var r = meanRgb[0], g = meanRgb[1], b = meanRgb[2];
var avg_r = tf_core_esm["fill"](Object(tslib_es6["e" /* __spreadArrays */])(x.shape.slice(0, 3), [1]), r);
var avg_g = tf_core_esm["fill"](Object(tslib_es6["e" /* __spreadArrays */])(x.shape.slice(0, 3), [1]), g);
var avg_b = tf_core_esm["fill"](Object(tslib_es6["e" /* __spreadArrays */])(x.shape.slice(0, 3), [1]), b);
var avg_rgb = tf_core_esm["concat"]([avg_r, avg_g, avg_b], 3);
return tf_core_esm["sub"](x, avg_rgb);
});
}
//# sourceMappingURL=normalize.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/padToSquare.js
/**
* Pads the smaller dimension of an image tensor with zeros, such that width === height.
*
* @param imgTensor The image tensor.
* @param isCenterImage (optional, default: false) If true, add an equal amount of padding on
* both sides of the minor dimension oof the image.
* @returns The padded tensor with width === height.
*/
function padToSquare_padToSquare(imgTensor, isCenterImage) {
if (isCenterImage === void 0) { isCenterImage = false; }
return tf_core_esm["tidy"](function () {
var _a = imgTensor.shape.slice(1), height = _a[0], width = _a[1];
if (height === width) {
return imgTensor;
}
var dimDiff = Math.abs(height - width);
var paddingAmount = Math.round(dimDiff * (isCenterImage ? 0.5 : 1));
var paddingAxis = height > width ? 2 : 1;
var createPaddingTensor = function (paddingAmount) {
var paddingTensorShape = imgTensor.shape.slice();
paddingTensorShape[paddingAxis] = paddingAmount;
return tf_core_esm["fill"](paddingTensorShape, 0);
};
var paddingTensorAppend = createPaddingTensor(paddingAmount);
var remainingPaddingAmount = dimDiff - paddingTensorAppend.shape[paddingAxis];
var paddingTensorPrepend = isCenterImage && remainingPaddingAmount
? createPaddingTensor(remainingPaddingAmount)
: null;
var tensorsToStack = [
paddingTensorPrepend,
imgTensor,
paddingTensorAppend
]
.filter(function (t) { return !!t; })
.map(function (t) { return t.toFloat(); });
return tf_core_esm["concat"](tensorsToStack, paddingAxis);
});
}
//# sourceMappingURL=padToSquare.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/shuffleArray.js
function shuffleArray(inputArray) {
var array = inputArray.slice();
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var x = array[i];
array[i] = array[j];
array[j] = x;
}
return array;
}
//# sourceMappingURL=shuffleArray.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ops/index.js
function sigmoid(x) {
return 1 / (1 + Math.exp(-x));
}
function inverseSigmoid(x) {
return Math.log(x / (1 - x));
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/Rect.js
var Rect_Rect = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(Rect, _super);
function Rect(x, y, width, height, allowNegativeDimensions) {
if (allowNegativeDimensions === void 0) { allowNegativeDimensions = false; }
return _super.call(this, { x: x, y: y, width: width, height: height }, allowNegativeDimensions) || this;
}
return Rect;
}(Box_Box));
//# sourceMappingURL=Rect.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/FaceLandmarks.js
// face alignment constants
var FaceLandmarks_relX = 0.5;
var FaceLandmarks_relY = 0.43;
var FaceLandmarks_relScale = 0.45;
var FaceLandmarks_FaceLandmarks = /** @class */ (function () {
function FaceLandmarks(relativeFaceLandmarkPositions, imgDims, shift) {
if (shift === void 0) { shift = new Point(0, 0); }
var width = imgDims.width, height = imgDims.height;
this._imgDims = new Dimensions_Dimensions(width, height);
this._shift = shift;
this._positions = relativeFaceLandmarkPositions.map(function (pt) { return pt.mul(new Point(width, height)).add(shift); });
}
Object.defineProperty(FaceLandmarks.prototype, "shift", {
get: function () { return new Point(this._shift.x, this._shift.y); },
enumerable: true,
configurable: true
});
Object.defineProperty(FaceLandmarks.prototype, "imageWidth", {
get: function () { return this._imgDims.width; },
enumerable: true,
configurable: true
});
Object.defineProperty(FaceLandmarks.prototype, "imageHeight", {
get: function () { return this._imgDims.height; },
enumerable: true,
configurable: true
});
Object.defineProperty(FaceLandmarks.prototype, "positions", {
get: function () { return this._positions; },
enumerable: true,
configurable: true
});
Object.defineProperty(FaceLandmarks.prototype, "relativePositions", {
get: function () {
var _this = this;
return this._positions.map(function (pt) { return pt.sub(_this._shift).div(new Point(_this.imageWidth, _this.imageHeight)); });
},
enumerable: true,
configurable: true
});
FaceLandmarks.prototype.forSize = function (width, height) {
return new this.constructor(this.relativePositions, { width: width, height: height });
};
FaceLandmarks.prototype.shiftBy = function (x, y) {
return new this.constructor(this.relativePositions, this._imgDims, new Point(x, y));
};
FaceLandmarks.prototype.shiftByPoint = function (pt) {
return this.shiftBy(pt.x, pt.y);
};
/**
* Aligns the face landmarks after face detection from the relative positions of the faces
* bounding box, or it's current shift. This function should be used to align the face images
* after face detection has been performed, before they are passed to the face recognition net.
* This will make the computed face descriptor more accurate.
*
* @param detection (optional) The bounding box of the face or the face detection result. If
* no argument was passed the position of the face landmarks are assumed to be relative to
* it's current shift.
* @returns The bounding box of the aligned face.
*/
FaceLandmarks.prototype.align = function (detection, options) {
if (options === void 0) { options = {}; }
if (detection) {
var box = detection instanceof FaceDetection_FaceDetection
? detection.box.floor()
: new Box_Box(detection);
return this.shiftBy(box.x, box.y).align(null, options);
}
var _a = Object.assign({}, { useDlibAlignment: false, minBoxPadding: 0.2 }, options), useDlibAlignment = _a.useDlibAlignment, minBoxPadding = _a.minBoxPadding;
if (useDlibAlignment) {
return this.alignDlib();
}
return this.alignMinBbox(minBoxPadding);
};
FaceLandmarks.prototype.alignDlib = function () {
var centers = this.getRefPointsForAlignment();
var leftEyeCenter = centers[0], rightEyeCenter = centers[1], mouthCenter = centers[2];
var distToMouth = function (pt) { return mouthCenter.sub(pt).magnitude(); };
var eyeToMouthDist = (distToMouth(leftEyeCenter) + distToMouth(rightEyeCenter)) / 2;
var size = Math.floor(eyeToMouthDist / FaceLandmarks_relScale);
var refPoint = utils_getCenterPoint(centers);
// TODO: pad in case rectangle is out of image bounds
var x = Math.floor(Math.max(0, refPoint.x - (FaceLandmarks_relX * size)));
var y = Math.floor(Math.max(0, refPoint.y - (FaceLandmarks_relY * size)));
return new Rect_Rect(x, y, Math.min(size, this.imageWidth + x), Math.min(size, this.imageHeight + y));
};
FaceLandmarks.prototype.alignMinBbox = function (padding) {
var box = minBbox_minBbox(this.positions);
return box.pad(box.width * padding, box.height * padding);
};
FaceLandmarks.prototype.getRefPointsForAlignment = function () {
throw new Error('getRefPointsForAlignment not implemented by base class');
};
return FaceLandmarks;
}());
//# sourceMappingURL=FaceLandmarks.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/FaceLandmarks5.js
var FaceLandmarks5_FaceLandmarks5 = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceLandmarks5, _super);
function FaceLandmarks5() {
return _super !== null && _super.apply(this, arguments) || this;
}
FaceLandmarks5.prototype.getRefPointsForAlignment = function () {
var pts = this.positions;
return [
pts[0],
pts[1],
utils_getCenterPoint([pts[3], pts[4]])
];
};
return FaceLandmarks5;
}(FaceLandmarks_FaceLandmarks));
//# sourceMappingURL=FaceLandmarks5.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/FaceLandmarks68.js
var FaceLandmarks68_FaceLandmarks68 = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceLandmarks68, _super);
function FaceLandmarks68() {
return _super !== null && _super.apply(this, arguments) || this;
}
FaceLandmarks68.prototype.getJawOutline = function () {
return this.positions.slice(0, 17);
};
FaceLandmarks68.prototype.getLeftEyeBrow = function () {
return this.positions.slice(17, 22);
};
FaceLandmarks68.prototype.getRightEyeBrow = function () {
return this.positions.slice(22, 27);
};
FaceLandmarks68.prototype.getNose = function () {
return this.positions.slice(27, 36);
};
FaceLandmarks68.prototype.getLeftEye = function () {
return this.positions.slice(36, 42);
};
FaceLandmarks68.prototype.getRightEye = function () {
return this.positions.slice(42, 48);
};
FaceLandmarks68.prototype.getMouth = function () {
return this.positions.slice(48, 68);
};
FaceLandmarks68.prototype.getRefPointsForAlignment = function () {
return [
this.getLeftEye(),
this.getRightEye(),
this.getMouth()
].map(utils_getCenterPoint);
};
return FaceLandmarks68;
}(FaceLandmarks_FaceLandmarks));
//# sourceMappingURL=FaceLandmarks68.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/FaceMatch.js
var FaceMatch_FaceMatch = /** @class */ (function () {
function FaceMatch(label, distance) {
this._label = label;
this._distance = distance;
}
Object.defineProperty(FaceMatch.prototype, "label", {
get: function () { return this._label; },
enumerable: true,
configurable: true
});
Object.defineProperty(FaceMatch.prototype, "distance", {
get: function () { return this._distance; },
enumerable: true,
configurable: true
});
FaceMatch.prototype.toString = function (withDistance) {
if (withDistance === void 0) { withDistance = true; }
return "" + this.label + (withDistance ? " (" + utils_round(this.distance) + ")" : '');
};
return FaceMatch;
}());
//# sourceMappingURL=FaceMatch.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/LabeledBox.js
var LabeledBox_LabeledBox = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(LabeledBox, _super);
function LabeledBox(box, label) {
var _this = _super.call(this, box) || this;
_this._label = label;
return _this;
}
LabeledBox.assertIsValidLabeledBox = function (box, callee) {
Box_Box.assertIsValidBox(box, callee);
if (!utils_isValidNumber(box.label)) {
throw new Error(callee + " - expected property label (" + box.label + ") to be a number");
}
};
Object.defineProperty(LabeledBox.prototype, "label", {
get: function () { return this._label; },
enumerable: true,
configurable: true
});
return LabeledBox;
}(Box_Box));
//# sourceMappingURL=LabeledBox.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/LabeledFaceDescriptors.js
var LabeledFaceDescriptors = /** @class */ (function () {
function LabeledFaceDescriptors(label, descriptors) {
if (!(typeof label === 'string')) {
throw new Error('LabeledFaceDescriptors - constructor expected label to be a string');
}
if (!Array.isArray(descriptors) || descriptors.some(function (desc) { return !(desc instanceof Float32Array); })) {
throw new Error('LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array');
}
this._label = label;
this._descriptors = descriptors;
}
Object.defineProperty(LabeledFaceDescriptors.prototype, "label", {
get: function () { return this._label; },
enumerable: true,
configurable: true
});
Object.defineProperty(LabeledFaceDescriptors.prototype, "descriptors", {
get: function () { return this._descriptors; },
enumerable: true,
configurable: true
});
LabeledFaceDescriptors.prototype.toJSON = function () {
return {
label: this.label,
descriptors: this.descriptors.map(function (d) { return Array.from(d); })
};
};
LabeledFaceDescriptors.fromJSON = function (json) {
var descriptors = json.descriptors.map(function (d) {
return new Float32Array(d);
});
return new LabeledFaceDescriptors(json.label, descriptors);
};
return LabeledFaceDescriptors;
}());
//# sourceMappingURL=LabeledFaceDescriptors.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/PredictedBox.js
var PredictedBox_PredictedBox = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictedBox, _super);
function PredictedBox(box, label, score, classScore) {
var _this = _super.call(this, box, label) || this;
_this._score = score;
_this._classScore = classScore;
return _this;
}
PredictedBox.assertIsValidPredictedBox = function (box, callee) {
LabeledBox_LabeledBox.assertIsValidLabeledBox(box, callee);
if (!utils_isValidProbablitiy(box.score)
|| !utils_isValidProbablitiy(box.classScore)) {
throw new Error(callee + " - expected properties score (" + box.score + ") and (" + box.classScore + ") to be a number between [0, 1]");
}
};
Object.defineProperty(PredictedBox.prototype, "score", {
get: function () { return this._score; },
enumerable: true,
configurable: true
});
Object.defineProperty(PredictedBox.prototype, "classScore", {
get: function () { return this._classScore; },
enumerable: true,
configurable: true
});
return PredictedBox;
}(LabeledBox_LabeledBox));
//# sourceMappingURL=PredictedBox.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/classes/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/WithFaceDetection.js
function WithFaceDetection_isWithFaceDetection(obj) {
return obj['detection'] instanceof FaceDetection_FaceDetection;
}
function WithFaceDetection_extendWithFaceDetection(sourceObj, detection) {
var extension = { detection: detection };
return Object.assign({}, sourceObj, extension);
}
//# sourceMappingURL=WithFaceDetection.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/env/createBrowserEnv.js
function createBrowserEnv() {
var fetch = window['fetch'] || function () {
throw new Error('fetch - missing fetch implementation for browser environment');
};
var readFile = function () {
throw new Error('readFile - filesystem not available for browser environment');
};
return {
Canvas: HTMLCanvasElement,
CanvasRenderingContext2D: CanvasRenderingContext2D,
Image: HTMLImageElement,
ImageData: ImageData,
Video: HTMLVideoElement,
createCanvasElement: function () { return document.createElement('canvas'); },
createImageElement: function () { return document.createElement('img'); },
fetch: fetch,
readFile: readFile
};
}
//# sourceMappingURL=createBrowserEnv.js.map
// EXTERNAL MODULE: ./node_modules/face-api.js/build/es6/env/createFileSystem.js
var createFileSystem = __webpack_require__(138);
// EXTERNAL MODULE: ./node_modules/face-api.js/build/es6/env/createNodejsEnv.js
var createNodejsEnv = __webpack_require__(194);
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/env/isBrowser.js
function isBrowser() {
return typeof window === 'object'
&& typeof document !== 'undefined'
&& typeof HTMLImageElement !== 'undefined'
&& typeof HTMLCanvasElement !== 'undefined'
&& typeof HTMLVideoElement !== 'undefined'
&& typeof ImageData !== 'undefined'
&& typeof CanvasRenderingContext2D !== 'undefined';
}
//# sourceMappingURL=isBrowser.js.map
// EXTERNAL MODULE: ./node_modules/face-api.js/build/es6/env/isNodejs.js
var isNodejs = __webpack_require__(193);
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/env/index.js
var env_environment;
function env_getEnv() {
if (!env_environment) {
throw new Error('getEnv - environment is not defined, check isNodejs() and isBrowser()');
}
return env_environment;
}
function env_setEnv(env) {
env_environment = env;
}
function env_initialize() {
// check for isBrowser() first to prevent electron renderer process
// to be initialized with wrong environment due to isNodejs() returning true
if (isBrowser()) {
env_setEnv(createBrowserEnv());
}
if (Object(isNodejs["a" /* isNodejs */])()) {
env_setEnv(Object(createNodejsEnv["a" /* createNodejsEnv */])());
}
}
function env_monkeyPatch(env) {
if (!env_environment) {
env_initialize();
}
if (!env_environment) {
throw new Error('monkeyPatch - environment is not defined, check isNodejs() and isBrowser()');
}
var _a = env.Canvas, Canvas = _a === void 0 ? env_environment.Canvas : _a, _b = env.Image, Image = _b === void 0 ? env_environment.Image : _b;
env_environment.Canvas = Canvas;
env_environment.Image = Image;
env_environment.createCanvasElement = env.createCanvasElement || (function () { return new Canvas(); });
env_environment.createImageElement = env.createImageElement || (function () { return new Image(); });
env_environment.ImageData = env.ImageData || env_environment.ImageData;
env_environment.Video = env.Video || env_environment.Video;
env_environment.fetch = env.fetch || env_environment.fetch;
env_environment.readFile = env.readFile || env_environment.readFile;
}
var env_env = {
getEnv: env_getEnv,
setEnv: env_setEnv,
initialize: env_initialize,
createBrowserEnv: createBrowserEnv,
createFileSystem: createFileSystem["a" /* createFileSystem */],
createNodejsEnv: createNodejsEnv["a" /* createNodejsEnv */],
monkeyPatch: env_monkeyPatch,
isBrowser: isBrowser,
isNodejs: isNodejs["a" /* isNodejs */]
};
env_initialize();
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/resolveInput.js
function resolveInput_resolveInput(arg) {
if (!env_env.isNodejs() && typeof arg === 'string') {
return document.getElementById(arg);
}
return arg;
}
//# sourceMappingURL=resolveInput.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/getContext2dOrThrow.js
function getContext2dOrThrow_getContext2dOrThrow(canvasArg) {
var _a = env_env.getEnv(), Canvas = _a.Canvas, CanvasRenderingContext2D = _a.CanvasRenderingContext2D;
if (canvasArg instanceof CanvasRenderingContext2D) {
return canvasArg;
}
var canvas = resolveInput_resolveInput(canvasArg);
if (!(canvas instanceof Canvas)) {
throw new Error('resolveContext2d - expected canvas to be of instance of Canvas');
}
var ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('resolveContext2d - canvas 2d context is null');
}
return ctx;
}
//# sourceMappingURL=getContext2dOrThrow.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/DrawTextField.js
var DrawTextField_AnchorPosition;
(function (AnchorPosition) {
AnchorPosition["TOP_LEFT"] = "TOP_LEFT";
AnchorPosition["TOP_RIGHT"] = "TOP_RIGHT";
AnchorPosition["BOTTOM_LEFT"] = "BOTTOM_LEFT";
AnchorPosition["BOTTOM_RIGHT"] = "BOTTOM_RIGHT";
})(DrawTextField_AnchorPosition || (DrawTextField_AnchorPosition = {}));
var DrawTextField_DrawTextFieldOptions = /** @class */ (function () {
function DrawTextFieldOptions(options) {
if (options === void 0) { options = {}; }
var anchorPosition = options.anchorPosition, backgroundColor = options.backgroundColor, fontColor = options.fontColor, fontSize = options.fontSize, fontStyle = options.fontStyle, padding = options.padding;
this.anchorPosition = anchorPosition || DrawTextField_AnchorPosition.TOP_LEFT;
this.backgroundColor = backgroundColor || 'rgba(0, 0, 0, 0.5)';
this.fontColor = fontColor || 'rgba(255, 255, 255, 1)';
this.fontSize = fontSize || 14;
this.fontStyle = fontStyle || 'Georgia';
this.padding = padding || 4;
}
return DrawTextFieldOptions;
}());
var DrawTextField_DrawTextField = /** @class */ (function () {
function DrawTextField(text, anchor, options) {
if (options === void 0) { options = {}; }
this.text = typeof text === 'string'
? [text]
: (text instanceof DrawTextField ? text.text : text);
this.anchor = anchor;
this.options = new DrawTextField_DrawTextFieldOptions(options);
}
DrawTextField.prototype.measureWidth = function (ctx) {
var padding = this.options.padding;
return this.text.map(function (l) { return ctx.measureText(l).width; }).reduce(function (w0, w1) { return w0 < w1 ? w1 : w0; }, 0) + (2 * padding);
};
DrawTextField.prototype.measureHeight = function () {
var _a = this.options, fontSize = _a.fontSize, padding = _a.padding;
return this.text.length * fontSize + (2 * padding);
};
DrawTextField.prototype.getUpperLeft = function (ctx, canvasDims) {
var anchorPosition = this.options.anchorPosition;
var isShiftLeft = anchorPosition === DrawTextField_AnchorPosition.BOTTOM_RIGHT || anchorPosition === DrawTextField_AnchorPosition.TOP_RIGHT;
var isShiftTop = anchorPosition === DrawTextField_AnchorPosition.BOTTOM_LEFT || anchorPosition === DrawTextField_AnchorPosition.BOTTOM_RIGHT;
var textFieldWidth = this.measureWidth(ctx);
var textFieldHeight = this.measureHeight();
var x = (isShiftLeft ? this.anchor.x - textFieldWidth : this.anchor.x);
var y = isShiftTop ? this.anchor.y - textFieldHeight : this.anchor.y;
// adjust anchor if text box exceeds canvas borders
if (canvasDims) {
var width = canvasDims.width, height = canvasDims.height;
var newX = Math.max(Math.min(x, width - textFieldWidth), 0);
var newY = Math.max(Math.min(y, height - textFieldHeight), 0);
return { x: newX, y: newY };
}
return { x: x, y: y };
};
DrawTextField.prototype.draw = function (canvasArg) {
var canvas = resolveInput_resolveInput(canvasArg);
var ctx = getContext2dOrThrow_getContext2dOrThrow(canvas);
var _a = this.options, backgroundColor = _a.backgroundColor, fontColor = _a.fontColor, fontSize = _a.fontSize, fontStyle = _a.fontStyle, padding = _a.padding;
ctx.font = fontSize + "px " + fontStyle;
var maxTextWidth = this.measureWidth(ctx);
var textHeight = this.measureHeight();
ctx.fillStyle = backgroundColor;
var upperLeft = this.getUpperLeft(ctx, canvas);
ctx.fillRect(upperLeft.x, upperLeft.y, maxTextWidth, textHeight);
ctx.fillStyle = fontColor;
this.text.forEach(function (textLine, i) {
var x = padding + upperLeft.x;
var y = padding + upperLeft.y + ((i + 1) * fontSize);
ctx.fillText(textLine, x, y);
});
};
return DrawTextField;
}());
//# sourceMappingURL=DrawTextField.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/DrawBox.js
var DrawBox_DrawBoxOptions = /** @class */ (function () {
function DrawBoxOptions(options) {
if (options === void 0) { options = {}; }
var boxColor = options.boxColor, lineWidth = options.lineWidth, label = options.label, drawLabelOptions = options.drawLabelOptions;
this.boxColor = boxColor || 'rgba(0, 0, 255, 1)';
this.lineWidth = lineWidth || 2;
this.label = label;
var defaultDrawLabelOptions = {
anchorPosition: DrawTextField_AnchorPosition.BOTTOM_LEFT,
backgroundColor: this.boxColor
};
this.drawLabelOptions = new DrawTextField_DrawTextFieldOptions(Object.assign({}, defaultDrawLabelOptions, drawLabelOptions));
}
return DrawBoxOptions;
}());
var DrawBox_DrawBox = /** @class */ (function () {
function DrawBox(box, options) {
if (options === void 0) { options = {}; }
this.box = new Box_Box(box);
this.options = new DrawBox_DrawBoxOptions(options);
}
DrawBox.prototype.draw = function (canvasArg) {
var ctx = getContext2dOrThrow_getContext2dOrThrow(canvasArg);
var _a = this.options, boxColor = _a.boxColor, lineWidth = _a.lineWidth;
var _b = this.box, x = _b.x, y = _b.y, width = _b.width, height = _b.height;
ctx.strokeStyle = boxColor;
ctx.lineWidth = lineWidth;
ctx.strokeRect(x, y, width, height);
var label = this.options.label;
if (label) {
new DrawTextField_DrawTextField([label], { x: x - (lineWidth / 2), y: y }, this.options.drawLabelOptions).draw(canvasArg);
}
};
return DrawBox;
}());
//# sourceMappingURL=DrawBox.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/drawDetections.js
function drawDetections_drawDetections(canvasArg, detections) {
var detectionsArray = Array.isArray(detections) ? detections : [detections];
detectionsArray.forEach(function (det) {
var score = det instanceof FaceDetection_FaceDetection
? det.score
: (WithFaceDetection_isWithFaceDetection(det) ? det.detection.score : undefined);
var box = det instanceof FaceDetection_FaceDetection
? det.box
: (WithFaceDetection_isWithFaceDetection(det) ? det.detection.box : new Box_Box(det));
var label = score ? "" + utils_round(score) : undefined;
new DrawBox_DrawBox(box, { label: label }).draw(canvasArg);
});
}
//# sourceMappingURL=drawDetections.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/isMediaLoaded.js
function isMediaLoaded_isMediaLoaded(media) {
var _a = env_env.getEnv(), Image = _a.Image, Video = _a.Video;
return (media instanceof Image && media.complete)
|| (media instanceof Video && media.readyState >= 3);
}
//# sourceMappingURL=isMediaLoaded.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/awaitMediaLoaded.js
function awaitMediaLoaded_awaitMediaLoaded(media) {
return new Promise(function (resolve, reject) {
if (media instanceof env_env.getEnv().Canvas || isMediaLoaded_isMediaLoaded(media)) {
return resolve();
}
function onLoad(e) {
if (!e.currentTarget)
return;
e.currentTarget.removeEventListener('load', onLoad);
e.currentTarget.removeEventListener('error', onError);
resolve(e);
}
function onError(e) {
if (!e.currentTarget)
return;
e.currentTarget.removeEventListener('load', onLoad);
e.currentTarget.removeEventListener('error', onError);
reject(e);
}
media.addEventListener('load', onLoad);
media.addEventListener('error', onError);
});
}
//# sourceMappingURL=awaitMediaLoaded.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/bufferToImage.js
function bufferToImage_bufferToImage(buf) {
return new Promise(function (resolve, reject) {
if (!(buf instanceof Blob)) {
return reject('bufferToImage - expected buf to be of type: Blob');
}
var reader = new FileReader();
reader.onload = function () {
if (typeof reader.result !== 'string') {
return reject('bufferToImage - expected reader.result to be a string, in onload');
}
var img = env_env.getEnv().createImageElement();
img.onload = function () { return resolve(img); };
img.onerror = reject;
img.src = reader.result;
};
reader.onerror = reject;
reader.readAsDataURL(buf);
});
}
//# sourceMappingURL=bufferToImage.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/getMediaDimensions.js
function getMediaDimensions_getMediaDimensions(input) {
var _a = env_env.getEnv(), Image = _a.Image, Video = _a.Video;
if (input instanceof Image) {
return new Dimensions_Dimensions(input.naturalWidth, input.naturalHeight);
}
if (input instanceof Video) {
return new Dimensions_Dimensions(input.videoWidth, input.videoHeight);
}
return new Dimensions_Dimensions(input.width, input.height);
}
//# sourceMappingURL=getMediaDimensions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/createCanvas.js
function createCanvas_createCanvas(_a) {
var width = _a.width, height = _a.height;
var createCanvasElement = env_env.getEnv().createCanvasElement;
var canvas = createCanvasElement();
canvas.width = width;
canvas.height = height;
return canvas;
}
function createCanvas_createCanvasFromMedia(media, dims) {
var ImageData = env_env.getEnv().ImageData;
if (!(media instanceof ImageData) && !isMediaLoaded_isMediaLoaded(media)) {
throw new Error('createCanvasFromMedia - media has not finished loading yet');
}
var _a = dims || getMediaDimensions_getMediaDimensions(media), width = _a.width, height = _a.height;
var canvas = createCanvas_createCanvas({ width: width, height: height });
if (media instanceof ImageData) {
getContext2dOrThrow_getContext2dOrThrow(canvas).putImageData(media, 0, 0);
}
else {
getContext2dOrThrow_getContext2dOrThrow(canvas).drawImage(media, 0, 0, width, height);
}
return canvas;
}
//# sourceMappingURL=createCanvas.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/imageTensorToCanvas.js
function imageTensorToCanvas_imageTensorToCanvas(imgTensor, canvas) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var targetCanvas, _a, height, width, numChannels, imgTensor3D;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
targetCanvas = canvas || env_env.getEnv().createCanvasElement();
_a = imgTensor.shape.slice(utils_isTensor4D(imgTensor) ? 1 : 0), height = _a[0], width = _a[1], numChannels = _a[2];
imgTensor3D = tf_core_esm["tidy"](function () { return imgTensor.as3D(height, width, numChannels).toInt(); });
return [4 /*yield*/, tf_core_esm["browser"].toPixels(imgTensor3D, targetCanvas)];
case 1:
_b.sent();
imgTensor3D.dispose();
return [2 /*return*/, targetCanvas];
}
});
});
}
//# sourceMappingURL=imageTensorToCanvas.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/isMediaElement.js
function isMediaElement_isMediaElement(input) {
var _a = env_env.getEnv(), Image = _a.Image, Canvas = _a.Canvas, Video = _a.Video;
return input instanceof Image
|| input instanceof Canvas
|| input instanceof Video;
}
//# sourceMappingURL=isMediaElement.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/imageToSquare.js
function imageToSquare_imageToSquare(input, inputSize, centerImage) {
if (centerImage === void 0) { centerImage = false; }
var _a = env_env.getEnv(), Image = _a.Image, Canvas = _a.Canvas;
if (!(input instanceof Image || input instanceof Canvas)) {
throw new Error('imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement');
}
var dims = getMediaDimensions_getMediaDimensions(input);
var scale = inputSize / Math.max(dims.height, dims.width);
var width = scale * dims.width;
var height = scale * dims.height;
var targetCanvas = createCanvas_createCanvas({ width: inputSize, height: inputSize });
var inputCanvas = input instanceof Canvas ? input : createCanvas_createCanvasFromMedia(input);
var offset = Math.abs(width - height) / 2;
var dx = centerImage && width < height ? offset : 0;
var dy = centerImage && height < width ? offset : 0;
getContext2dOrThrow_getContext2dOrThrow(targetCanvas).drawImage(inputCanvas, dx, dy, width, height);
return targetCanvas;
}
//# sourceMappingURL=imageToSquare.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/NetInput.js
var NetInput_NetInput = /** @class */ (function () {
function NetInput(inputs, treatAsBatchInput) {
var _this = this;
if (treatAsBatchInput === void 0) { treatAsBatchInput = false; }
this._imageTensors = [];
this._canvases = [];
this._treatAsBatchInput = false;
this._inputDimensions = [];
if (!Array.isArray(inputs)) {
throw new Error("NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have " + inputs);
}
this._treatAsBatchInput = treatAsBatchInput;
this._batchSize = inputs.length;
inputs.forEach(function (input, idx) {
if (utils_isTensor3D(input)) {
_this._imageTensors[idx] = input;
_this._inputDimensions[idx] = input.shape;
return;
}
if (utils_isTensor4D(input)) {
var batchSize = input.shape[0];
if (batchSize !== 1) {
throw new Error("NetInput - tf.Tensor4D with batchSize " + batchSize + " passed, but not supported in input array");
}
_this._imageTensors[idx] = input;
_this._inputDimensions[idx] = input.shape.slice(1);
return;
}
var canvas = input instanceof env_env.getEnv().Canvas ? input : createCanvas_createCanvasFromMedia(input);
_this._canvases[idx] = canvas;
_this._inputDimensions[idx] = [canvas.height, canvas.width, 3];
});
}
Object.defineProperty(NetInput.prototype, "imageTensors", {
get: function () {
return this._imageTensors;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NetInput.prototype, "canvases", {
get: function () {
return this._canvases;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NetInput.prototype, "isBatchInput", {
get: function () {
return this.batchSize > 1 || this._treatAsBatchInput;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NetInput.prototype, "batchSize", {
get: function () {
return this._batchSize;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NetInput.prototype, "inputDimensions", {
get: function () {
return this._inputDimensions;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NetInput.prototype, "inputSize", {
get: function () {
return this._inputSize;
},
enumerable: true,
configurable: true
});
Object.defineProperty(NetInput.prototype, "reshapedInputDimensions", {
get: function () {
var _this = this;
return utils_range(this.batchSize, 0, 1).map(function (_, batchIdx) { return _this.getReshapedInputDimensions(batchIdx); });
},
enumerable: true,
configurable: true
});
NetInput.prototype.getInput = function (batchIdx) {
return this.canvases[batchIdx] || this.imageTensors[batchIdx];
};
NetInput.prototype.getInputDimensions = function (batchIdx) {
return this._inputDimensions[batchIdx];
};
NetInput.prototype.getInputHeight = function (batchIdx) {
return this._inputDimensions[batchIdx][0];
};
NetInput.prototype.getInputWidth = function (batchIdx) {
return this._inputDimensions[batchIdx][1];
};
NetInput.prototype.getReshapedInputDimensions = function (batchIdx) {
if (typeof this.inputSize !== 'number') {
throw new Error('getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet');
}
var width = this.getInputWidth(batchIdx);
var height = this.getInputHeight(batchIdx);
return utils_computeReshapedDimensions({ width: width, height: height }, this.inputSize);
};
/**
* Create a batch tensor from all input canvases and tensors
* with size [batchSize, inputSize, inputSize, 3].
*
* @param inputSize Height and width of the tensor.
* @param isCenterImage (optional, default: false) If true, add an equal amount of padding on
* both sides of the minor dimension oof the image.
* @returns The batch tensor.
*/
NetInput.prototype.toBatchTensor = function (inputSize, isCenterInputs) {
var _this = this;
if (isCenterInputs === void 0) { isCenterInputs = true; }
this._inputSize = inputSize;
return tf_core_esm["tidy"](function () {
var inputTensors = utils_range(_this.batchSize, 0, 1).map(function (batchIdx) {
var input = _this.getInput(batchIdx);
if (input instanceof tf_core_esm["Tensor"]) {
var imgTensor = utils_isTensor4D(input) ? input : input.expandDims();
imgTensor = padToSquare_padToSquare(imgTensor, isCenterInputs);
if (imgTensor.shape[1] !== inputSize || imgTensor.shape[2] !== inputSize) {
imgTensor = tf_core_esm["image"].resizeBilinear(imgTensor, [inputSize, inputSize]);
}
return imgTensor.as3D(inputSize, inputSize, 3);
}
if (input instanceof env_env.getEnv().Canvas) {
return tf_core_esm["browser"].fromPixels(imageToSquare_imageToSquare(input, inputSize, isCenterInputs));
}
throw new Error("toBatchTensor - at batchIdx " + batchIdx + ", expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have " + input);
});
var batchTensor = tf_core_esm["stack"](inputTensors.map(function (t) { return t.toFloat(); })).as4D(_this.batchSize, inputSize, inputSize, 3);
return batchTensor;
});
};
return NetInput;
}());
//# sourceMappingURL=NetInput.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/toNetInput.js
/**
* Validates the input to make sure, they are valid net inputs and awaits all media elements
* to be finished loading.
*
* @param input The input, which can be a media element or an array of different media elements.
* @returns A NetInput instance, which can be passed into one of the neural networks.
*/
function toNetInput_toNetInput(inputs) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var inputArgArray, getIdxHint, inputArray;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
if (inputs instanceof NetInput_NetInput) {
return [2 /*return*/, inputs];
}
inputArgArray = Array.isArray(inputs)
? inputs
: [inputs];
if (!inputArgArray.length) {
throw new Error('toNetInput - empty array passed as input');
}
getIdxHint = function (idx) { return Array.isArray(inputs) ? " at input index " + idx + ":" : ''; };
inputArray = inputArgArray.map(resolveInput_resolveInput);
inputArray.forEach(function (input, i) {
if (!isMediaElement_isMediaElement(input) && !utils_isTensor3D(input) && !utils_isTensor4D(input)) {
if (typeof inputArgArray[i] === 'string') {
throw new Error("toNetInput -" + getIdxHint(i) + " string passed, but could not resolve HTMLElement for element id " + inputArgArray[i]);
}
throw new Error("toNetInput -" + getIdxHint(i) + " expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id");
}
if (utils_isTensor4D(input)) {
// if tf.Tensor4D is passed in the input array, the batch size has to be 1
var batchSize = input.shape[0];
if (batchSize !== 1) {
throw new Error("toNetInput -" + getIdxHint(i) + " tf.Tensor4D with batchSize " + batchSize + " passed, but not supported in input array");
}
}
});
// wait for all media elements being loaded
return [4 /*yield*/, Promise.all(inputArray.map(function (input) { return isMediaElement_isMediaElement(input) && awaitMediaLoaded_awaitMediaLoaded(input); }))];
case 1:
// wait for all media elements being loaded
_a.sent();
return [2 /*return*/, new NetInput_NetInput(inputArray, Array.isArray(inputs))];
}
});
});
}
//# sourceMappingURL=toNetInput.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/extractFaces.js
/**
* Extracts the image regions containing the detected faces.
*
* @param input The image that face detection has been performed on.
* @param detections The face detection results or face bounding boxes for that image.
* @returns The Canvases of the corresponding image region for each detected face.
*/
function extractFaces_extractFaces(input, detections) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var Canvas, canvas, netInput, tensorOrCanvas, _a, ctx, boxes;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
Canvas = env_env.getEnv().Canvas;
canvas = input;
if (!!(input instanceof Canvas)) return [3 /*break*/, 5];
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _b.sent();
if (netInput.batchSize > 1) {
throw new Error('extractFaces - batchSize > 1 not supported');
}
tensorOrCanvas = netInput.getInput(0);
if (!(tensorOrCanvas instanceof Canvas)) return [3 /*break*/, 2];
_a = tensorOrCanvas;
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, imageTensorToCanvas_imageTensorToCanvas(tensorOrCanvas)];
case 3:
_a = _b.sent();
_b.label = 4;
case 4:
canvas = _a;
_b.label = 5;
case 5:
ctx = getContext2dOrThrow_getContext2dOrThrow(canvas);
boxes = detections.map(function (det) { return det instanceof FaceDetection_FaceDetection
? det.forSize(canvas.width, canvas.height).box.floor()
: det; })
.map(function (box) { return box.clipAtImageBorders(canvas.width, canvas.height); });
return [2 /*return*/, boxes.map(function (_a) {
var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
var faceImg = createCanvas_createCanvas({ width: width, height: height });
getContext2dOrThrow_getContext2dOrThrow(faceImg)
.putImageData(ctx.getImageData(x, y, width, height), 0, 0);
return faceImg;
})];
}
});
});
}
//# sourceMappingURL=extractFaces.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/extractFaceTensors.js
/**
* Extracts the tensors of the image regions containing the detected faces.
* Useful if you want to compute the face descriptors for the face images.
* Using this method is faster then extracting a canvas for each face and
* converting them to tensors individually.
*
* @param imageTensor The image tensor that face detection has been performed on.
* @param detections The face detection results or face bounding boxes for that image.
* @returns Tensors of the corresponding image region for each detected face.
*/
function extractFaceTensors_extractFaceTensors(imageTensor, detections) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
if (!utils_isTensor3D(imageTensor) && !utils_isTensor4D(imageTensor)) {
throw new Error('extractFaceTensors - expected image tensor to be 3D or 4D');
}
if (utils_isTensor4D(imageTensor) && imageTensor.shape[0] > 1) {
throw new Error('extractFaceTensors - batchSize > 1 not supported');
}
return [2 /*return*/, tf_core_esm["tidy"](function () {
var _a = imageTensor.shape.slice(utils_isTensor4D(imageTensor) ? 1 : 0), imgHeight = _a[0], imgWidth = _a[1], numChannels = _a[2];
var boxes = detections.map(function (det) { return det instanceof FaceDetection_FaceDetection
? det.forSize(imgWidth, imgHeight).box
: det; })
.map(function (box) { return box.clipAtImageBorders(imgWidth, imgHeight); });
var faceTensors = boxes.map(function (_a) {
var x = _a.x, y = _a.y, width = _a.width, height = _a.height;
return tf_core_esm["slice3d"](imageTensor.as3D(imgHeight, imgWidth, numChannels), [y, x, 0], [height, width, numChannels]);
});
return faceTensors;
})];
});
});
}
//# sourceMappingURL=extractFaceTensors.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/fetchOrThrow.js
function fetchOrThrow_fetchOrThrow(url, init) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var fetch, res;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
fetch = env_env.getEnv().fetch;
return [4 /*yield*/, fetch(url, init)];
case 1:
res = _a.sent();
if (!(res.status < 400)) {
throw new Error("failed to fetch: (" + res.status + ") " + res.statusText + ", from url: " + res.url);
}
return [2 /*return*/, res];
}
});
});
}
//# sourceMappingURL=fetchOrThrow.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/fetchImage.js
function fetchImage_fetchImage(uri) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var res, blob;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetchOrThrow_fetchOrThrow(uri)];
case 1:
res = _a.sent();
return [4 /*yield*/, (res).blob()];
case 2:
blob = _a.sent();
if (!blob.type.startsWith('image/')) {
throw new Error("fetchImage - expected blob type to be of type image/*, instead have: " + blob.type + ", for url: " + res.url);
}
return [2 /*return*/, bufferToImage_bufferToImage(blob)];
}
});
});
}
//# sourceMappingURL=fetchImage.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/fetchJson.js
function fetchJson_fetchJson(uri) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetchOrThrow_fetchOrThrow(uri)];
case 1: return [2 /*return*/, (_a.sent()).json()];
}
});
});
}
//# sourceMappingURL=fetchJson.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/fetchNetWeights.js
function fetchNetWeights_fetchNetWeights(uri) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = Float32Array.bind;
return [4 /*yield*/, fetchOrThrow_fetchOrThrow(uri)];
case 1: return [4 /*yield*/, (_b.sent()).arrayBuffer()];
case 2: return [2 /*return*/, new (_a.apply(Float32Array, [void 0, _b.sent()]))()];
}
});
});
}
//# sourceMappingURL=fetchNetWeights.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/getModelUris.js
function getModelUris(uri, defaultModelName) {
var defaultManifestFilename = defaultModelName + "-weights_manifest.json";
if (!uri) {
return {
modelBaseUri: '',
manifestUri: defaultManifestFilename
};
}
if (uri === '/') {
return {
modelBaseUri: '/',
manifestUri: "/" + defaultManifestFilename
};
}
var protocol = uri.startsWith('http://') ? 'http://' : uri.startsWith('https://') ? 'https://' : '';
uri = uri.replace(protocol, '');
var parts = uri.split('/').filter(function (s) { return s; });
var manifestFile = uri.endsWith('.json')
? parts[parts.length - 1]
: defaultManifestFilename;
var modelBaseUri = protocol + (uri.endsWith('.json') ? parts.slice(0, parts.length - 1) : parts).join('/');
modelBaseUri = uri.startsWith('/') ? "/" + modelBaseUri : modelBaseUri;
return {
modelBaseUri: modelBaseUri,
manifestUri: modelBaseUri === '/' ? "/" + manifestFile : modelBaseUri + "/" + manifestFile
};
}
//# sourceMappingURL=getModelUris.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/loadWeightMap.js
function loadWeightMap_loadWeightMap(uri, defaultModelName) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a, manifestUri, modelBaseUri, manifest;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = getModelUris(uri, defaultModelName), manifestUri = _a.manifestUri, modelBaseUri = _a.modelBaseUri;
return [4 /*yield*/, fetchJson_fetchJson(manifestUri)];
case 1:
manifest = _b.sent();
return [2 /*return*/, tf_core_esm["io"].loadWeights(manifest, modelBaseUri)];
}
});
});
}
//# sourceMappingURL=loadWeightMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/matchDimensions.js
function matchDimensions_matchDimensions(input, reference, useMediaDimensions) {
if (useMediaDimensions === void 0) { useMediaDimensions = false; }
var _a = useMediaDimensions
? getMediaDimensions_getMediaDimensions(reference)
: reference, width = _a.width, height = _a.height;
input.width = width;
input.height = height;
return { width: width, height: height };
}
//# sourceMappingURL=matchDimensions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/dom/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/NeuralNetwork.js
var NeuralNetwork_NeuralNetwork = /** @class */ (function () {
function NeuralNetwork(_name) {
this._name = _name;
this._params = undefined;
this._paramMappings = [];
}
Object.defineProperty(NeuralNetwork.prototype, "params", {
get: function () { return this._params; },
enumerable: true,
configurable: true
});
Object.defineProperty(NeuralNetwork.prototype, "paramMappings", {
get: function () { return this._paramMappings; },
enumerable: true,
configurable: true
});
Object.defineProperty(NeuralNetwork.prototype, "isLoaded", {
get: function () { return !!this.params; },
enumerable: true,
configurable: true
});
NeuralNetwork.prototype.getParamFromPath = function (paramPath) {
var _a = this.traversePropertyPath(paramPath), obj = _a.obj, objProp = _a.objProp;
return obj[objProp];
};
NeuralNetwork.prototype.reassignParamFromPath = function (paramPath, tensor) {
var _a = this.traversePropertyPath(paramPath), obj = _a.obj, objProp = _a.objProp;
obj[objProp].dispose();
obj[objProp] = tensor;
};
NeuralNetwork.prototype.getParamList = function () {
var _this = this;
return this._paramMappings.map(function (_a) {
var paramPath = _a.paramPath;
return ({
path: paramPath,
tensor: _this.getParamFromPath(paramPath)
});
});
};
NeuralNetwork.prototype.getTrainableParams = function () {
return this.getParamList().filter(function (param) { return param.tensor instanceof tf_core_esm["Variable"]; });
};
NeuralNetwork.prototype.getFrozenParams = function () {
return this.getParamList().filter(function (param) { return !(param.tensor instanceof tf_core_esm["Variable"]); });
};
NeuralNetwork.prototype.variable = function () {
var _this = this;
this.getFrozenParams().forEach(function (_a) {
var path = _a.path, tensor = _a.tensor;
_this.reassignParamFromPath(path, tensor.variable());
});
};
NeuralNetwork.prototype.freeze = function () {
var _this = this;
this.getTrainableParams().forEach(function (_a) {
var path = _a.path, variable = _a.tensor;
var tensor = tf_core_esm["tensor"](variable.dataSync());
variable.dispose();
_this.reassignParamFromPath(path, tensor);
});
};
NeuralNetwork.prototype.dispose = function (throwOnRedispose) {
if (throwOnRedispose === void 0) { throwOnRedispose = true; }
this.getParamList().forEach(function (param) {
if (throwOnRedispose && param.tensor.isDisposed) {
throw new Error("param tensor has already been disposed for path " + param.path);
}
param.tensor.dispose();
});
this._params = undefined;
};
NeuralNetwork.prototype.serializeParams = function () {
return new Float32Array(this.getParamList()
.map(function (_a) {
var tensor = _a.tensor;
return Array.from(tensor.dataSync());
})
.reduce(function (flat, arr) { return flat.concat(arr); }));
};
NeuralNetwork.prototype.load = function (weightsOrUrl) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
if (weightsOrUrl instanceof Float32Array) {
this.extractWeights(weightsOrUrl);
return [2 /*return*/];
}
return [4 /*yield*/, this.loadFromUri(weightsOrUrl)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
NeuralNetwork.prototype.loadFromUri = function (uri) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var weightMap;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
if (uri && typeof uri !== 'string') {
throw new Error(this._name + ".loadFromUri - expected model uri");
}
return [4 /*yield*/, loadWeightMap_loadWeightMap(uri, this.getDefaultModelName())];
case 1:
weightMap = _a.sent();
this.loadFromWeightMap(weightMap);
return [2 /*return*/];
}
});
});
};
NeuralNetwork.prototype.loadFromDisk = function (filePath) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var readFile, _a, manifestUri, modelBaseUri, fetchWeightsFromDisk, loadWeights, manifest, _b, _c, weightMap;
return Object(tslib_es6["d" /* __generator */])(this, function (_d) {
switch (_d.label) {
case 0:
if (filePath && typeof filePath !== 'string') {
throw new Error(this._name + ".loadFromDisk - expected model file path");
}
readFile = env_env.getEnv().readFile;
_a = getModelUris(filePath, this.getDefaultModelName()), manifestUri = _a.manifestUri, modelBaseUri = _a.modelBaseUri;
fetchWeightsFromDisk = function (filePaths) { return Promise.all(filePaths.map(function (filePath) { return readFile(filePath).then(function (buf) { return buf.buffer; }); })); };
loadWeights = tf_core_esm["io"].weightsLoaderFactory(fetchWeightsFromDisk);
_c = (_b = JSON).parse;
return [4 /*yield*/, readFile(manifestUri)];
case 1:
manifest = _c.apply(_b, [(_d.sent()).toString()]);
return [4 /*yield*/, loadWeights(manifest, modelBaseUri)];
case 2:
weightMap = _d.sent();
this.loadFromWeightMap(weightMap);
return [2 /*return*/];
}
});
});
};
NeuralNetwork.prototype.loadFromWeightMap = function (weightMap) {
var _a = this.extractParamsFromWeigthMap(weightMap), paramMappings = _a.paramMappings, params = _a.params;
this._paramMappings = paramMappings;
this._params = params;
};
NeuralNetwork.prototype.extractWeights = function (weights) {
var _a = this.extractParams(weights), paramMappings = _a.paramMappings, params = _a.params;
this._paramMappings = paramMappings;
this._params = params;
};
NeuralNetwork.prototype.traversePropertyPath = function (paramPath) {
if (!this.params) {
throw new Error("traversePropertyPath - model has no loaded params");
}
var result = paramPath.split('/').reduce(function (res, objProp) {
if (!res.nextObj.hasOwnProperty(objProp)) {
throw new Error("traversePropertyPath - object does not have property " + objProp + ", for path " + paramPath);
}
return { obj: res.nextObj, objProp: objProp, nextObj: res.nextObj[objProp] };
}, { nextObj: this.params });
var obj = result.obj, objProp = result.objProp;
if (!obj || !objProp || !(obj[objProp] instanceof tf_core_esm["Tensor"])) {
throw new Error("traversePropertyPath - parameter is not a tensor, for path " + paramPath);
}
return { obj: obj, objProp: objProp };
};
return NeuralNetwork;
}());
//# sourceMappingURL=NeuralNetwork.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/depthwiseSeparableConv.js
function depthwiseSeparableConv_depthwiseSeparableConv(x, params, stride) {
return tf_core_esm["tidy"](function () {
var out = tf_core_esm["separableConv2d"](x, params.depthwise_filter, params.pointwise_filter, stride, 'same');
out = tf_core_esm["add"](out, params.bias);
return out;
});
}
//# sourceMappingURL=depthwiseSeparableConv.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/denseBlock.js
function denseBlock_denseBlock3(x, denseBlockParams, isFirstLayer) {
if (isFirstLayer === void 0) { isFirstLayer = false; }
return tf_core_esm["tidy"](function () {
var out1 = tf_core_esm["relu"](isFirstLayer
? tf_core_esm["add"](tf_core_esm["conv2d"](x, denseBlockParams.conv0.filters, [2, 2], 'same'), denseBlockParams.conv0.bias)
: depthwiseSeparableConv_depthwiseSeparableConv(x, denseBlockParams.conv0, [2, 2]));
var out2 = depthwiseSeparableConv_depthwiseSeparableConv(out1, denseBlockParams.conv1, [1, 1]);
var in3 = tf_core_esm["relu"](tf_core_esm["add"](out1, out2));
var out3 = depthwiseSeparableConv_depthwiseSeparableConv(in3, denseBlockParams.conv2, [1, 1]);
return tf_core_esm["relu"](tf_core_esm["add"](out1, tf_core_esm["add"](out2, out3)));
});
}
function denseBlock_denseBlock4(x, denseBlockParams, isFirstLayer, isScaleDown) {
if (isFirstLayer === void 0) { isFirstLayer = false; }
if (isScaleDown === void 0) { isScaleDown = true; }
return tf_core_esm["tidy"](function () {
var out1 = tf_core_esm["relu"](isFirstLayer
? tf_core_esm["add"](tf_core_esm["conv2d"](x, denseBlockParams.conv0.filters, isScaleDown ? [2, 2] : [1, 1], 'same'), denseBlockParams.conv0.bias)
: depthwiseSeparableConv_depthwiseSeparableConv(x, denseBlockParams.conv0, isScaleDown ? [2, 2] : [1, 1]));
var out2 = depthwiseSeparableConv_depthwiseSeparableConv(out1, denseBlockParams.conv1, [1, 1]);
var in3 = tf_core_esm["relu"](tf_core_esm["add"](out1, out2));
var out3 = depthwiseSeparableConv_depthwiseSeparableConv(in3, denseBlockParams.conv2, [1, 1]);
var in4 = tf_core_esm["relu"](tf_core_esm["add"](out1, tf_core_esm["add"](out2, out3)));
var out4 = depthwiseSeparableConv_depthwiseSeparableConv(in4, denseBlockParams.conv3, [1, 1]);
return tf_core_esm["relu"](tf_core_esm["add"](out1, tf_core_esm["add"](out2, tf_core_esm["add"](out3, out4))));
});
}
//# sourceMappingURL=denseBlock.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/convLayer.js
function convLayer_convLayer(x, params, padding, withRelu) {
if (padding === void 0) { padding = 'same'; }
if (withRelu === void 0) { withRelu = false; }
return tf_core_esm["tidy"](function () {
var out = tf_core_esm["add"](tf_core_esm["conv2d"](x, params.filters, [1, 1], padding), params.bias);
return withRelu ? tf_core_esm["relu"](out) : out;
});
}
//# sourceMappingURL=convLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/disposeUnusedWeightTensors.js
function disposeUnusedWeightTensors(weightMap, paramMappings) {
Object.keys(weightMap).forEach(function (path) {
if (!paramMappings.some(function (pm) { return pm.originalPath === path; })) {
weightMap[path].dispose();
}
});
}
//# sourceMappingURL=disposeUnusedWeightTensors.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/extractConvParamsFactory.js
function extractConvParamsFactory_extractConvParamsFactory(extractWeights, paramMappings) {
return function (channelsIn, channelsOut, filterSize, mappedPrefix) {
var filters = tf_core_esm["tensor4d"](extractWeights(channelsIn * channelsOut * filterSize * filterSize), [filterSize, filterSize, channelsIn, channelsOut]);
var bias = tf_core_esm["tensor1d"](extractWeights(channelsOut));
paramMappings.push({ paramPath: mappedPrefix + "/filters" }, { paramPath: mappedPrefix + "/bias" });
return { filters: filters, bias: bias };
};
}
//# sourceMappingURL=extractConvParamsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/extractFCParamsFactory.js
function extractFCParamsFactory_extractFCParamsFactory(extractWeights, paramMappings) {
return function (channelsIn, channelsOut, mappedPrefix) {
var fc_weights = tf_core_esm["tensor2d"](extractWeights(channelsIn * channelsOut), [channelsIn, channelsOut]);
var fc_bias = tf_core_esm["tensor1d"](extractWeights(channelsOut));
paramMappings.push({ paramPath: mappedPrefix + "/weights" }, { paramPath: mappedPrefix + "/bias" });
return {
weights: fc_weights,
bias: fc_bias
};
};
}
//# sourceMappingURL=extractFCParamsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/types.js
var SeparableConvParams = /** @class */ (function () {
function SeparableConvParams(depthwise_filter, pointwise_filter, bias) {
this.depthwise_filter = depthwise_filter;
this.pointwise_filter = pointwise_filter;
this.bias = bias;
}
return SeparableConvParams;
}());
//# sourceMappingURL=types.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/extractSeparableConvParamsFactory.js
function extractSeparableConvParamsFactory_extractSeparableConvParamsFactory(extractWeights, paramMappings) {
return function (channelsIn, channelsOut, mappedPrefix) {
var depthwise_filter = tf_core_esm["tensor4d"](extractWeights(3 * 3 * channelsIn), [3, 3, channelsIn, 1]);
var pointwise_filter = tf_core_esm["tensor4d"](extractWeights(channelsIn * channelsOut), [1, 1, channelsIn, channelsOut]);
var bias = tf_core_esm["tensor1d"](extractWeights(channelsOut));
paramMappings.push({ paramPath: mappedPrefix + "/depthwise_filter" }, { paramPath: mappedPrefix + "/pointwise_filter" }, { paramPath: mappedPrefix + "/bias" });
return new SeparableConvParams(depthwise_filter, pointwise_filter, bias);
};
}
function extractSeparableConvParamsFactory_loadSeparableConvParamsFactory(extractWeightEntry) {
return function (prefix) {
var depthwise_filter = extractWeightEntry(prefix + "/depthwise_filter", 4);
var pointwise_filter = extractWeightEntry(prefix + "/pointwise_filter", 4);
var bias = extractWeightEntry(prefix + "/bias", 1);
return new SeparableConvParams(depthwise_filter, pointwise_filter, bias);
};
}
//# sourceMappingURL=extractSeparableConvParamsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/extractWeightEntryFactory.js
function extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings) {
return function (originalPath, paramRank, mappedPath) {
var tensor = weightMap[originalPath];
if (!utils_isTensor(tensor, paramRank)) {
throw new Error("expected weightMap[" + originalPath + "] to be a Tensor" + paramRank + "D, instead have " + tensor);
}
paramMappings.push({ originalPath: originalPath, paramPath: mappedPath || originalPath });
return tensor;
};
}
//# sourceMappingURL=extractWeightEntryFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/extractWeightsFactory.js
function extractWeightsFactory(weights) {
var remainingWeights = weights;
function extractWeights(numWeights) {
var ret = remainingWeights.slice(0, numWeights);
remainingWeights = remainingWeights.slice(numWeights);
return ret;
}
function getRemainingWeights() {
return remainingWeights;
}
return {
extractWeights: extractWeights,
getRemainingWeights: getRemainingWeights
};
}
//# sourceMappingURL=extractWeightsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/extractorsFactory.js
function extractorsFactory_extractorsFactory(extractWeights, paramMappings) {
var extractConvParams = extractConvParamsFactory_extractConvParamsFactory(extractWeights, paramMappings);
var extractSeparableConvParams = extractSeparableConvParamsFactory_extractSeparableConvParamsFactory(extractWeights, paramMappings);
function extractDenseBlock3Params(channelsIn, channelsOut, mappedPrefix, isFirstLayer) {
if (isFirstLayer === void 0) { isFirstLayer = false; }
var conv0 = isFirstLayer
? extractConvParams(channelsIn, channelsOut, 3, mappedPrefix + "/conv0")
: extractSeparableConvParams(channelsIn, channelsOut, mappedPrefix + "/conv0");
var conv1 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/conv1");
var conv2 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/conv2");
return { conv0: conv0, conv1: conv1, conv2: conv2 };
}
function extractDenseBlock4Params(channelsIn, channelsOut, mappedPrefix, isFirstLayer) {
if (isFirstLayer === void 0) { isFirstLayer = false; }
var _a = extractDenseBlock3Params(channelsIn, channelsOut, mappedPrefix, isFirstLayer), conv0 = _a.conv0, conv1 = _a.conv1, conv2 = _a.conv2;
var conv3 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/conv3");
return { conv0: conv0, conv1: conv1, conv2: conv2, conv3: conv3 };
}
return {
extractDenseBlock3Params: extractDenseBlock3Params,
extractDenseBlock4Params: extractDenseBlock4Params
};
}
//# sourceMappingURL=extractorsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/extractParams.js
function extractParams_extractParams(weights) {
var paramMappings = [];
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var extractDenseBlock4Params = extractorsFactory_extractorsFactory(extractWeights, paramMappings).extractDenseBlock4Params;
var dense0 = extractDenseBlock4Params(3, 32, 'dense0', true);
var dense1 = extractDenseBlock4Params(32, 64, 'dense1');
var dense2 = extractDenseBlock4Params(64, 128, 'dense2');
var dense3 = extractDenseBlock4Params(128, 256, 'dense3');
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return {
paramMappings: paramMappings,
params: { dense0: dense0, dense1: dense1, dense2: dense2, dense3: dense3 }
};
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/loadConvParamsFactory.js
function loadConvParamsFactory(extractWeightEntry) {
return function (prefix) {
var filters = extractWeightEntry(prefix + "/filters", 4);
var bias = extractWeightEntry(prefix + "/bias", 1);
return { filters: filters, bias: bias };
};
}
//# sourceMappingURL=loadConvParamsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/loadParamsFactory.js
function loadParamsFactory_loadParamsFactory(weightMap, paramMappings) {
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
var extractConvParams = loadConvParamsFactory(extractWeightEntry);
var extractSeparableConvParams = extractSeparableConvParamsFactory_loadSeparableConvParamsFactory(extractWeightEntry);
function extractDenseBlock3Params(prefix, isFirstLayer) {
if (isFirstLayer === void 0) { isFirstLayer = false; }
var conv0 = isFirstLayer
? extractConvParams(prefix + "/conv0")
: extractSeparableConvParams(prefix + "/conv0");
var conv1 = extractSeparableConvParams(prefix + "/conv1");
var conv2 = extractSeparableConvParams(prefix + "/conv2");
return { conv0: conv0, conv1: conv1, conv2: conv2 };
}
function extractDenseBlock4Params(prefix, isFirstLayer) {
if (isFirstLayer === void 0) { isFirstLayer = false; }
var conv0 = isFirstLayer
? extractConvParams(prefix + "/conv0")
: extractSeparableConvParams(prefix + "/conv0");
var conv1 = extractSeparableConvParams(prefix + "/conv1");
var conv2 = extractSeparableConvParams(prefix + "/conv2");
var conv3 = extractSeparableConvParams(prefix + "/conv3");
return { conv0: conv0, conv1: conv1, conv2: conv2, conv3: conv3 };
}
return {
extractDenseBlock3Params: extractDenseBlock3Params,
extractDenseBlock4Params: extractDenseBlock4Params
};
}
//# sourceMappingURL=loadParamsFactory.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/extractParamsFromWeigthMap.js
function extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap) {
var paramMappings = [];
var extractDenseBlock4Params = loadParamsFactory_loadParamsFactory(weightMap, paramMappings).extractDenseBlock4Params;
var params = {
dense0: extractDenseBlock4Params('dense0', true),
dense1: extractDenseBlock4Params('dense1'),
dense2: extractDenseBlock4Params('dense2'),
dense3: extractDenseBlock4Params('dense3')
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/FaceFeatureExtractor.js
var FaceFeatureExtractor_FaceFeatureExtractor = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceFeatureExtractor, _super);
function FaceFeatureExtractor() {
return _super.call(this, 'FaceFeatureExtractor') || this;
}
FaceFeatureExtractor.prototype.forwardInput = function (input) {
var params = this.params;
if (!params) {
throw new Error('FaceFeatureExtractor - load model before inference');
}
return tf_core_esm["tidy"](function () {
var batchTensor = input.toBatchTensor(112, true);
var meanRgb = [122.782, 117.001, 104.298];
var normalized = normalize_normalize(batchTensor, meanRgb).div(tf_core_esm["scalar"](255));
var out = denseBlock_denseBlock4(normalized, params.dense0, true);
out = denseBlock_denseBlock4(out, params.dense1);
out = denseBlock_denseBlock4(out, params.dense2);
out = denseBlock_denseBlock4(out, params.dense3);
out = tf_core_esm["avgPool"](out, [7, 7], [2, 2], 'valid');
return out;
});
};
FaceFeatureExtractor.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
FaceFeatureExtractor.prototype.getDefaultModelName = function () {
return 'face_feature_extractor_model';
};
FaceFeatureExtractor.prototype.extractParamsFromWeigthMap = function (weightMap) {
return extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap);
};
FaceFeatureExtractor.prototype.extractParams = function (weights) {
return extractParams_extractParams(weights);
};
return FaceFeatureExtractor;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=FaceFeatureExtractor.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/common/fullyConnectedLayer.js
function fullyConnectedLayer_fullyConnectedLayer(x, params) {
return tf_core_esm["tidy"](function () {
return tf_core_esm["add"](tf_core_esm["matMul"](x, params.weights), params.bias);
});
}
//# sourceMappingURL=fullyConnectedLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceProcessor/extractParams.js
function faceProcessor_extractParams_extractParams(weights, channelsIn, channelsOut) {
var paramMappings = [];
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var extractFCParams = extractFCParamsFactory_extractFCParamsFactory(extractWeights, paramMappings);
var fc = extractFCParams(channelsIn, channelsOut, 'fc');
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return {
paramMappings: paramMappings,
params: { fc: fc }
};
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceProcessor/extractParamsFromWeigthMap.js
function faceProcessor_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap) {
var paramMappings = [];
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
function extractFcParams(prefix) {
var weights = extractWeightEntry(prefix + "/weights", 2);
var bias = extractWeightEntry(prefix + "/bias", 1);
return { weights: weights, bias: bias };
}
var params = {
fc: extractFcParams('fc')
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceProcessor/util.js
function seperateWeightMaps(weightMap) {
var featureExtractorMap = {};
var classifierMap = {};
Object.keys(weightMap).forEach(function (key) {
var map = key.startsWith('fc') ? classifierMap : featureExtractorMap;
map[key] = weightMap[key];
});
return { featureExtractorMap: featureExtractorMap, classifierMap: classifierMap };
}
//# sourceMappingURL=util.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceProcessor/FaceProcessor.js
var FaceProcessor_FaceProcessor = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceProcessor, _super);
function FaceProcessor(_name, faceFeatureExtractor) {
var _this = _super.call(this, _name) || this;
_this._faceFeatureExtractor = faceFeatureExtractor;
return _this;
}
Object.defineProperty(FaceProcessor.prototype, "faceFeatureExtractor", {
get: function () {
return this._faceFeatureExtractor;
},
enumerable: true,
configurable: true
});
FaceProcessor.prototype.runNet = function (input) {
var _this = this;
var params = this.params;
if (!params) {
throw new Error(this._name + " - load model before inference");
}
return tf_core_esm["tidy"](function () {
var bottleneckFeatures = input instanceof NetInput_NetInput
? _this.faceFeatureExtractor.forwardInput(input)
: input;
return fullyConnectedLayer_fullyConnectedLayer(bottleneckFeatures.as2D(bottleneckFeatures.shape[0], -1), params.fc);
});
};
FaceProcessor.prototype.dispose = function (throwOnRedispose) {
if (throwOnRedispose === void 0) { throwOnRedispose = true; }
this.faceFeatureExtractor.dispose(throwOnRedispose);
_super.prototype.dispose.call(this, throwOnRedispose);
};
FaceProcessor.prototype.loadClassifierParams = function (weights) {
var _a = this.extractClassifierParams(weights), params = _a.params, paramMappings = _a.paramMappings;
this._params = params;
this._paramMappings = paramMappings;
};
FaceProcessor.prototype.extractClassifierParams = function (weights) {
return faceProcessor_extractParams_extractParams(weights, this.getClassifierChannelsIn(), this.getClassifierChannelsOut());
};
FaceProcessor.prototype.extractParamsFromWeigthMap = function (weightMap) {
var _a = seperateWeightMaps(weightMap), featureExtractorMap = _a.featureExtractorMap, classifierMap = _a.classifierMap;
this.faceFeatureExtractor.loadFromWeightMap(featureExtractorMap);
return faceProcessor_extractParamsFromWeigthMap_extractParamsFromWeigthMap(classifierMap);
};
FaceProcessor.prototype.extractParams = function (weights) {
var cIn = this.getClassifierChannelsIn();
var cOut = this.getClassifierChannelsOut();
var classifierWeightSize = (cOut * cIn) + cOut;
var featureExtractorWeights = weights.slice(0, weights.length - classifierWeightSize);
var classifierWeights = weights.slice(weights.length - classifierWeightSize);
this.faceFeatureExtractor.extractWeights(featureExtractorWeights);
return this.extractClassifierParams(classifierWeights);
};
return FaceProcessor;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=FaceProcessor.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceExpressionNet/FaceExpressions.js
var FACE_EXPRESSION_LABELS = ['neutral', 'happy', 'sad', 'angry', 'fearful', 'disgusted', 'surprised'];
var FaceExpressions = /** @class */ (function () {
function FaceExpressions(probabilities) {
var _this = this;
if (probabilities.length !== 7) {
throw new Error("FaceExpressions.constructor - expected probabilities.length to be 7, have: " + probabilities.length);
}
FACE_EXPRESSION_LABELS.forEach(function (expression, idx) {
_this[expression] = probabilities[idx];
});
}
FaceExpressions.prototype.asSortedArray = function () {
var _this = this;
return FACE_EXPRESSION_LABELS
.map(function (expression) { return ({ expression: expression, probability: _this[expression] }); })
.sort(function (e0, e1) { return e1.probability - e0.probability; });
};
return FaceExpressions;
}());
//# sourceMappingURL=FaceExpressions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceExpressionNet/FaceExpressionNet.js
var FaceExpressionNet_FaceExpressionNet = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceExpressionNet, _super);
function FaceExpressionNet(faceFeatureExtractor) {
if (faceFeatureExtractor === void 0) { faceFeatureExtractor = new FaceFeatureExtractor_FaceFeatureExtractor(); }
return _super.call(this, 'FaceExpressionNet', faceFeatureExtractor) || this;
}
FaceExpressionNet.prototype.forwardInput = function (input) {
var _this = this;
return tf_core_esm["tidy"](function () { return tf_core_esm["softmax"](_this.runNet(input)); });
};
FaceExpressionNet.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
FaceExpressionNet.prototype.predictExpressions = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var netInput, out, probabilitesByBatch, predictionsByBatch;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _a.sent();
return [4 /*yield*/, this.forwardInput(netInput)];
case 2:
out = _a.sent();
return [4 /*yield*/, Promise.all(tf_core_esm["unstack"](out).map(function (t) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
var data;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, t.data()];
case 1:
data = _a.sent();
t.dispose();
return [2 /*return*/, data];
}
});
}); }))];
case 3:
probabilitesByBatch = _a.sent();
out.dispose();
predictionsByBatch = probabilitesByBatch
.map(function (probabilites) { return new FaceExpressions(probabilites); });
return [2 /*return*/, netInput.isBatchInput
? predictionsByBatch
: predictionsByBatch[0]];
}
});
});
};
FaceExpressionNet.prototype.getDefaultModelName = function () {
return 'face_expression_model';
};
FaceExpressionNet.prototype.getClassifierChannelsIn = function () {
return 256;
};
FaceExpressionNet.prototype.getClassifierChannelsOut = function () {
return 7;
};
return FaceExpressionNet;
}(FaceProcessor_FaceProcessor));
//# sourceMappingURL=FaceExpressionNet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceExpressionNet/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/WithFaceExpressions.js
function WithFaceExpressions_isWithFaceExpressions(obj) {
return obj['expressions'] instanceof FaceExpressions;
}
function WithFaceExpressions_extendWithFaceExpressions(sourceObj, expressions) {
var extension = { expressions: expressions };
return Object.assign({}, sourceObj, extension);
}
//# sourceMappingURL=WithFaceExpressions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/drawFaceExpressions.js
function drawFaceExpressions_drawFaceExpressions(canvasArg, faceExpressions, minConfidence, textFieldAnchor) {
if (minConfidence === void 0) { minConfidence = 0.1; }
var faceExpressionsArray = Array.isArray(faceExpressions) ? faceExpressions : [faceExpressions];
faceExpressionsArray.forEach(function (e) {
var expr = e instanceof FaceExpressions
? e
: (WithFaceExpressions_isWithFaceExpressions(e) ? e.expressions : undefined);
if (!expr) {
throw new Error('drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof');
}
var sorted = expr.asSortedArray();
var resultsToDisplay = sorted.filter(function (expr) { return expr.probability > minConfidence; });
var anchor = WithFaceDetection_isWithFaceDetection(e)
? e.detection.box.bottomLeft
: (textFieldAnchor || new Point(0, 0));
var drawTextField = new DrawTextField_DrawTextField(resultsToDisplay.map(function (expr) { return expr.expression + " (" + utils_round(expr.probability) + ")"; }), anchor);
drawTextField.draw(canvasArg);
});
}
//# sourceMappingURL=drawFaceExpressions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/WithFaceLandmarks.js
function WithFaceLandmarks_isWithFaceLandmarks(obj) {
return WithFaceDetection_isWithFaceDetection(obj)
&& obj['landmarks'] instanceof FaceLandmarks_FaceLandmarks
&& obj['unshiftedLandmarks'] instanceof FaceLandmarks_FaceLandmarks
&& obj['alignedRect'] instanceof FaceDetection_FaceDetection;
}
function WithFaceLandmarks_extendWithFaceLandmarks(sourceObj, unshiftedLandmarks) {
var shift = sourceObj.detection.box;
var landmarks = unshiftedLandmarks.shiftBy(shift.x, shift.y);
var rect = landmarks.align();
var imageDims = sourceObj.detection.imageDims;
var alignedRect = new FaceDetection_FaceDetection(sourceObj.detection.score, rect.rescale(imageDims.reverse()), imageDims);
var extension = {
landmarks: landmarks,
unshiftedLandmarks: unshiftedLandmarks,
alignedRect: alignedRect
};
return Object.assign({}, sourceObj, extension);
}
//# sourceMappingURL=WithFaceLandmarks.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/DrawFaceLandmarks.js
var DrawFaceLandmarks_DrawFaceLandmarksOptions = /** @class */ (function () {
function DrawFaceLandmarksOptions(options) {
if (options === void 0) { options = {}; }
var _a = options.drawLines, drawLines = _a === void 0 ? true : _a, _b = options.drawPoints, drawPoints = _b === void 0 ? true : _b, lineWidth = options.lineWidth, lineColor = options.lineColor, pointSize = options.pointSize, pointColor = options.pointColor;
this.drawLines = drawLines;
this.drawPoints = drawPoints;
this.lineWidth = lineWidth || 1;
this.pointSize = pointSize || 2;
this.lineColor = lineColor || 'rgba(0, 255, 255, 1)';
this.pointColor = pointColor || 'rgba(255, 0, 255, 1)';
}
return DrawFaceLandmarksOptions;
}());
var DrawFaceLandmarks_DrawFaceLandmarks = /** @class */ (function () {
function DrawFaceLandmarks(faceLandmarks, options) {
if (options === void 0) { options = {}; }
this.faceLandmarks = faceLandmarks;
this.options = new DrawFaceLandmarks_DrawFaceLandmarksOptions(options);
}
DrawFaceLandmarks.prototype.draw = function (canvasArg) {
var ctx = getContext2dOrThrow_getContext2dOrThrow(canvasArg);
var _a = this.options, drawLines = _a.drawLines, drawPoints = _a.drawPoints, lineWidth = _a.lineWidth, lineColor = _a.lineColor, pointSize = _a.pointSize, pointColor = _a.pointColor;
if (drawLines && this.faceLandmarks instanceof FaceLandmarks68_FaceLandmarks68) {
ctx.strokeStyle = lineColor;
ctx.lineWidth = lineWidth;
drawContour(ctx, this.faceLandmarks.getJawOutline());
drawContour(ctx, this.faceLandmarks.getLeftEyeBrow());
drawContour(ctx, this.faceLandmarks.getRightEyeBrow());
drawContour(ctx, this.faceLandmarks.getNose());
drawContour(ctx, this.faceLandmarks.getLeftEye(), true);
drawContour(ctx, this.faceLandmarks.getRightEye(), true);
drawContour(ctx, this.faceLandmarks.getMouth(), true);
}
if (drawPoints) {
ctx.strokeStyle = pointColor;
ctx.fillStyle = pointColor;
var drawPoint = function (pt) {
ctx.beginPath();
ctx.arc(pt.x, pt.y, pointSize, 0, 2 * Math.PI);
ctx.fill();
};
this.faceLandmarks.positions.forEach(drawPoint);
}
};
return DrawFaceLandmarks;
}());
function DrawFaceLandmarks_drawFaceLandmarks(canvasArg, faceLandmarks) {
var faceLandmarksArray = Array.isArray(faceLandmarks) ? faceLandmarks : [faceLandmarks];
faceLandmarksArray.forEach(function (f) {
var landmarks = f instanceof FaceLandmarks_FaceLandmarks
? f
: (WithFaceLandmarks_isWithFaceLandmarks(f) ? f.landmarks : undefined);
if (!landmarks) {
throw new Error('drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof');
}
new DrawFaceLandmarks_DrawFaceLandmarks(landmarks).draw(canvasArg);
});
}
//# sourceMappingURL=DrawFaceLandmarks.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/draw/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/xception/extractParams.js
function extractParams_extractorsFactory(extractWeights, paramMappings) {
var extractConvParams = extractConvParamsFactory_extractConvParamsFactory(extractWeights, paramMappings);
var extractSeparableConvParams = extractSeparableConvParamsFactory_extractSeparableConvParamsFactory(extractWeights, paramMappings);
function extractReductionBlockParams(channelsIn, channelsOut, mappedPrefix) {
var separable_conv0 = extractSeparableConvParams(channelsIn, channelsOut, mappedPrefix + "/separable_conv0");
var separable_conv1 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/separable_conv1");
var expansion_conv = extractConvParams(channelsIn, channelsOut, 1, mappedPrefix + "/expansion_conv");
return { separable_conv0: separable_conv0, separable_conv1: separable_conv1, expansion_conv: expansion_conv };
}
function extractMainBlockParams(channels, mappedPrefix) {
var separable_conv0 = extractSeparableConvParams(channels, channels, mappedPrefix + "/separable_conv0");
var separable_conv1 = extractSeparableConvParams(channels, channels, mappedPrefix + "/separable_conv1");
var separable_conv2 = extractSeparableConvParams(channels, channels, mappedPrefix + "/separable_conv2");
return { separable_conv0: separable_conv0, separable_conv1: separable_conv1, separable_conv2: separable_conv2 };
}
return {
extractConvParams: extractConvParams,
extractSeparableConvParams: extractSeparableConvParams,
extractReductionBlockParams: extractReductionBlockParams,
extractMainBlockParams: extractMainBlockParams
};
}
function xception_extractParams_extractParams(weights, numMainBlocks) {
var paramMappings = [];
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var _b = extractParams_extractorsFactory(extractWeights, paramMappings), extractConvParams = _b.extractConvParams, extractSeparableConvParams = _b.extractSeparableConvParams, extractReductionBlockParams = _b.extractReductionBlockParams, extractMainBlockParams = _b.extractMainBlockParams;
var entry_flow_conv_in = extractConvParams(3, 32, 3, 'entry_flow/conv_in');
var entry_flow_reduction_block_0 = extractReductionBlockParams(32, 64, 'entry_flow/reduction_block_0');
var entry_flow_reduction_block_1 = extractReductionBlockParams(64, 128, 'entry_flow/reduction_block_1');
var entry_flow = {
conv_in: entry_flow_conv_in,
reduction_block_0: entry_flow_reduction_block_0,
reduction_block_1: entry_flow_reduction_block_1
};
var middle_flow = {};
utils_range(numMainBlocks, 0, 1).forEach(function (idx) {
middle_flow["main_block_" + idx] = extractMainBlockParams(128, "middle_flow/main_block_" + idx);
});
var exit_flow_reduction_block = extractReductionBlockParams(128, 256, 'exit_flow/reduction_block');
var exit_flow_separable_conv = extractSeparableConvParams(256, 512, 'exit_flow/separable_conv');
var exit_flow = {
reduction_block: exit_flow_reduction_block,
separable_conv: exit_flow_separable_conv
};
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return {
paramMappings: paramMappings,
params: { entry_flow: entry_flow, middle_flow: middle_flow, exit_flow: exit_flow }
};
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/xception/extractParamsFromWeigthMap.js
function extractParamsFromWeigthMap_loadParamsFactory(weightMap, paramMappings) {
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
var extractConvParams = loadConvParamsFactory(extractWeightEntry);
var extractSeparableConvParams = extractSeparableConvParamsFactory_loadSeparableConvParamsFactory(extractWeightEntry);
function extractReductionBlockParams(mappedPrefix) {
var separable_conv0 = extractSeparableConvParams(mappedPrefix + "/separable_conv0");
var separable_conv1 = extractSeparableConvParams(mappedPrefix + "/separable_conv1");
var expansion_conv = extractConvParams(mappedPrefix + "/expansion_conv");
return { separable_conv0: separable_conv0, separable_conv1: separable_conv1, expansion_conv: expansion_conv };
}
function extractMainBlockParams(mappedPrefix) {
var separable_conv0 = extractSeparableConvParams(mappedPrefix + "/separable_conv0");
var separable_conv1 = extractSeparableConvParams(mappedPrefix + "/separable_conv1");
var separable_conv2 = extractSeparableConvParams(mappedPrefix + "/separable_conv2");
return { separable_conv0: separable_conv0, separable_conv1: separable_conv1, separable_conv2: separable_conv2 };
}
return {
extractConvParams: extractConvParams,
extractSeparableConvParams: extractSeparableConvParams,
extractReductionBlockParams: extractReductionBlockParams,
extractMainBlockParams: extractMainBlockParams
};
}
function xception_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap, numMainBlocks) {
var paramMappings = [];
var _a = extractParamsFromWeigthMap_loadParamsFactory(weightMap, paramMappings), extractConvParams = _a.extractConvParams, extractSeparableConvParams = _a.extractSeparableConvParams, extractReductionBlockParams = _a.extractReductionBlockParams, extractMainBlockParams = _a.extractMainBlockParams;
var entry_flow_conv_in = extractConvParams('entry_flow/conv_in');
var entry_flow_reduction_block_0 = extractReductionBlockParams('entry_flow/reduction_block_0');
var entry_flow_reduction_block_1 = extractReductionBlockParams('entry_flow/reduction_block_1');
var entry_flow = {
conv_in: entry_flow_conv_in,
reduction_block_0: entry_flow_reduction_block_0,
reduction_block_1: entry_flow_reduction_block_1
};
var middle_flow = {};
utils_range(numMainBlocks, 0, 1).forEach(function (idx) {
middle_flow["main_block_" + idx] = extractMainBlockParams("middle_flow/main_block_" + idx);
});
var exit_flow_reduction_block = extractReductionBlockParams('exit_flow/reduction_block');
var exit_flow_separable_conv = extractSeparableConvParams('exit_flow/separable_conv');
var exit_flow = {
reduction_block: exit_flow_reduction_block,
separable_conv: exit_flow_separable_conv
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: { entry_flow: entry_flow, middle_flow: middle_flow, exit_flow: exit_flow }, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/xception/TinyXception.js
function TinyXception_conv(x, params, stride) {
return tf_core_esm["add"](tf_core_esm["conv2d"](x, params.filters, stride, 'same'), params.bias);
}
function TinyXception_reductionBlock(x, params, isActivateInput) {
if (isActivateInput === void 0) { isActivateInput = true; }
var out = isActivateInput ? tf_core_esm["relu"](x) : x;
out = depthwiseSeparableConv_depthwiseSeparableConv(out, params.separable_conv0, [1, 1]);
out = depthwiseSeparableConv_depthwiseSeparableConv(tf_core_esm["relu"](out), params.separable_conv1, [1, 1]);
out = tf_core_esm["maxPool"](out, [3, 3], [2, 2], 'same');
out = tf_core_esm["add"](out, TinyXception_conv(x, params.expansion_conv, [2, 2]));
return out;
}
function TinyXception_mainBlock(x, params) {
var out = depthwiseSeparableConv_depthwiseSeparableConv(tf_core_esm["relu"](x), params.separable_conv0, [1, 1]);
out = depthwiseSeparableConv_depthwiseSeparableConv(tf_core_esm["relu"](out), params.separable_conv1, [1, 1]);
out = depthwiseSeparableConv_depthwiseSeparableConv(tf_core_esm["relu"](out), params.separable_conv2, [1, 1]);
out = tf_core_esm["add"](out, x);
return out;
}
var TinyXception_TinyXception = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(TinyXception, _super);
function TinyXception(numMainBlocks) {
var _this = _super.call(this, 'TinyXception') || this;
_this._numMainBlocks = numMainBlocks;
return _this;
}
TinyXception.prototype.forwardInput = function (input) {
var _this = this;
var params = this.params;
if (!params) {
throw new Error('TinyXception - load model before inference');
}
return tf_core_esm["tidy"](function () {
var batchTensor = input.toBatchTensor(112, true);
var meanRgb = [122.782, 117.001, 104.298];
var normalized = normalize_normalize(batchTensor, meanRgb).div(tf_core_esm["scalar"](256));
var out = tf_core_esm["relu"](TinyXception_conv(normalized, params.entry_flow.conv_in, [2, 2]));
out = TinyXception_reductionBlock(out, params.entry_flow.reduction_block_0, false);
out = TinyXception_reductionBlock(out, params.entry_flow.reduction_block_1);
utils_range(_this._numMainBlocks, 0, 1).forEach(function (idx) {
out = TinyXception_mainBlock(out, params.middle_flow["main_block_" + idx]);
});
out = TinyXception_reductionBlock(out, params.exit_flow.reduction_block);
out = tf_core_esm["relu"](depthwiseSeparableConv_depthwiseSeparableConv(out, params.exit_flow.separable_conv, [1, 1]));
return out;
});
};
TinyXception.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
TinyXception.prototype.getDefaultModelName = function () {
return 'tiny_xception_model';
};
TinyXception.prototype.extractParamsFromWeigthMap = function (weightMap) {
return xception_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap, this._numMainBlocks);
};
TinyXception.prototype.extractParams = function (weights) {
return xception_extractParams_extractParams(weights, this._numMainBlocks);
};
return TinyXception;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=TinyXception.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ageGenderNet/extractParams.js
function ageGenderNet_extractParams_extractParams(weights) {
var paramMappings = [];
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var extractFCParams = extractFCParamsFactory_extractFCParamsFactory(extractWeights, paramMappings);
var age = extractFCParams(512, 1, 'fc/age');
var gender = extractFCParams(512, 2, 'fc/gender');
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return {
paramMappings: paramMappings,
params: { fc: { age: age, gender: gender } }
};
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ageGenderNet/extractParamsFromWeigthMap.js
function ageGenderNet_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap) {
var paramMappings = [];
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
function extractFcParams(prefix) {
var weights = extractWeightEntry(prefix + "/weights", 2);
var bias = extractWeightEntry(prefix + "/bias", 1);
return { weights: weights, bias: bias };
}
var params = {
fc: {
age: extractFcParams('fc/age'),
gender: extractFcParams('fc/gender')
}
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ageGenderNet/types.js
var Gender;
(function (Gender) {
Gender["FEMALE"] = "female";
Gender["MALE"] = "male";
})(Gender || (Gender = {}));
//# sourceMappingURL=types.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ageGenderNet/AgeGenderNet.js
var AgeGenderNet_AgeGenderNet = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(AgeGenderNet, _super);
function AgeGenderNet(faceFeatureExtractor) {
if (faceFeatureExtractor === void 0) { faceFeatureExtractor = new TinyXception_TinyXception(2); }
var _this = _super.call(this, 'AgeGenderNet') || this;
_this._faceFeatureExtractor = faceFeatureExtractor;
return _this;
}
Object.defineProperty(AgeGenderNet.prototype, "faceFeatureExtractor", {
get: function () {
return this._faceFeatureExtractor;
},
enumerable: true,
configurable: true
});
AgeGenderNet.prototype.runNet = function (input) {
var _this = this;
var params = this.params;
if (!params) {
throw new Error(this._name + " - load model before inference");
}
return tf_core_esm["tidy"](function () {
var bottleneckFeatures = input instanceof NetInput_NetInput
? _this.faceFeatureExtractor.forwardInput(input)
: input;
var pooled = tf_core_esm["avgPool"](bottleneckFeatures, [7, 7], [2, 2], 'valid').as2D(bottleneckFeatures.shape[0], -1);
var age = fullyConnectedLayer_fullyConnectedLayer(pooled, params.fc.age).as1D();
var gender = fullyConnectedLayer_fullyConnectedLayer(pooled, params.fc.gender);
return { age: age, gender: gender };
});
};
AgeGenderNet.prototype.forwardInput = function (input) {
var _this = this;
return tf_core_esm["tidy"](function () {
var _a = _this.runNet(input), age = _a.age, gender = _a.gender;
return { age: age, gender: tf_core_esm["softmax"](gender) };
});
};
AgeGenderNet.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
AgeGenderNet.prototype.predictAgeAndGender = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var netInput, out, ages, genders, ageAndGenderTensors, predictionsByBatch;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _a.sent();
return [4 /*yield*/, this.forwardInput(netInput)];
case 2:
out = _a.sent();
ages = tf_core_esm["unstack"](out.age);
genders = tf_core_esm["unstack"](out.gender);
ageAndGenderTensors = ages.map(function (ageTensor, i) { return ({
ageTensor: ageTensor,
genderTensor: genders[i]
}); });
return [4 /*yield*/, Promise.all(ageAndGenderTensors.map(function (_a) {
var ageTensor = _a.ageTensor, genderTensor = _a.genderTensor;
return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
var age, probMale, isMale, gender, genderProbability;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, ageTensor.data()];
case 1:
age = (_b.sent())[0];
return [4 /*yield*/, genderTensor.data()];
case 2:
probMale = (_b.sent())[0];
isMale = probMale > 0.5;
gender = isMale ? Gender.MALE : Gender.FEMALE;
genderProbability = isMale ? probMale : (1 - probMale);
ageTensor.dispose();
genderTensor.dispose();
return [2 /*return*/, { age: age, gender: gender, genderProbability: genderProbability }];
}
});
});
}))];
case 3:
predictionsByBatch = _a.sent();
out.age.dispose();
out.gender.dispose();
return [2 /*return*/, netInput.isBatchInput
? predictionsByBatch
: predictionsByBatch[0]];
}
});
});
};
AgeGenderNet.prototype.getDefaultModelName = function () {
return 'age_gender_model';
};
AgeGenderNet.prototype.dispose = function (throwOnRedispose) {
if (throwOnRedispose === void 0) { throwOnRedispose = true; }
this.faceFeatureExtractor.dispose(throwOnRedispose);
_super.prototype.dispose.call(this, throwOnRedispose);
};
AgeGenderNet.prototype.loadClassifierParams = function (weights) {
var _a = this.extractClassifierParams(weights), params = _a.params, paramMappings = _a.paramMappings;
this._params = params;
this._paramMappings = paramMappings;
};
AgeGenderNet.prototype.extractClassifierParams = function (weights) {
return ageGenderNet_extractParams_extractParams(weights);
};
AgeGenderNet.prototype.extractParamsFromWeigthMap = function (weightMap) {
var _a = seperateWeightMaps(weightMap), featureExtractorMap = _a.featureExtractorMap, classifierMap = _a.classifierMap;
this.faceFeatureExtractor.loadFromWeightMap(featureExtractorMap);
return ageGenderNet_extractParamsFromWeigthMap_extractParamsFromWeigthMap(classifierMap);
};
AgeGenderNet.prototype.extractParams = function (weights) {
var classifierWeightSize = (512 * 1 + 1) + (512 * 2 + 2);
var featureExtractorWeights = weights.slice(0, weights.length - classifierWeightSize);
var classifierWeights = weights.slice(weights.length - classifierWeightSize);
this.faceFeatureExtractor.extractWeights(featureExtractorWeights);
return this.extractClassifierParams(classifierWeights);
};
return AgeGenderNet;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=AgeGenderNet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ageGenderNet/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceLandmarkNet/FaceLandmark68NetBase.js
var FaceLandmark68NetBase_FaceLandmark68NetBase = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceLandmark68NetBase, _super);
function FaceLandmark68NetBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
FaceLandmark68NetBase.prototype.postProcess = function (output, inputSize, originalDimensions) {
var inputDimensions = originalDimensions.map(function (_a) {
var width = _a.width, height = _a.height;
var scale = inputSize / Math.max(height, width);
return {
width: width * scale,
height: height * scale
};
});
var batchSize = inputDimensions.length;
return tf_core_esm["tidy"](function () {
var createInterleavedTensor = function (fillX, fillY) {
return tf_core_esm["stack"]([
tf_core_esm["fill"]([68], fillX),
tf_core_esm["fill"]([68], fillY)
], 1).as2D(1, 136).as1D();
};
var getPadding = function (batchIdx, cond) {
var _a = inputDimensions[batchIdx], width = _a.width, height = _a.height;
return cond(width, height) ? Math.abs(width - height) / 2 : 0;
};
var getPaddingX = function (batchIdx) { return getPadding(batchIdx, function (w, h) { return w < h; }); };
var getPaddingY = function (batchIdx) { return getPadding(batchIdx, function (w, h) { return h < w; }); };
var landmarkTensors = output
.mul(tf_core_esm["fill"]([batchSize, 136], inputSize))
.sub(tf_core_esm["stack"](Array.from(Array(batchSize), function (_, batchIdx) {
return createInterleavedTensor(getPaddingX(batchIdx), getPaddingY(batchIdx));
})))
.div(tf_core_esm["stack"](Array.from(Array(batchSize), function (_, batchIdx) {
return createInterleavedTensor(inputDimensions[batchIdx].width, inputDimensions[batchIdx].height);
})));
return landmarkTensors;
});
};
FaceLandmark68NetBase.prototype.forwardInput = function (input) {
var _this = this;
return tf_core_esm["tidy"](function () {
var out = _this.runNet(input);
return _this.postProcess(out, input.inputSize, input.inputDimensions.map(function (_a) {
var height = _a[0], width = _a[1];
return ({ height: height, width: width });
}));
});
};
FaceLandmark68NetBase.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
FaceLandmark68NetBase.prototype.detectLandmarks = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var netInput, landmarkTensors, landmarksForBatch;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _a.sent();
landmarkTensors = tf_core_esm["tidy"](function () { return tf_core_esm["unstack"](_this.forwardInput(netInput)); });
return [4 /*yield*/, Promise.all(landmarkTensors.map(function (landmarkTensor, batchIdx) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
var landmarksArray, _a, _b, xCoords, yCoords;
return Object(tslib_es6["d" /* __generator */])(this, function (_c) {
switch (_c.label) {
case 0:
_b = (_a = Array).from;
return [4 /*yield*/, landmarkTensor.data()];
case 1:
landmarksArray = _b.apply(_a, [_c.sent()]);
xCoords = landmarksArray.filter(function (_, i) { return utils_isEven(i); });
yCoords = landmarksArray.filter(function (_, i) { return !utils_isEven(i); });
return [2 /*return*/, new FaceLandmarks68_FaceLandmarks68(Array(68).fill(0).map(function (_, i) { return new Point(xCoords[i], yCoords[i]); }), {
height: netInput.getInputHeight(batchIdx),
width: netInput.getInputWidth(batchIdx),
})];
}
});
}); }))];
case 2:
landmarksForBatch = _a.sent();
landmarkTensors.forEach(function (t) { return t.dispose(); });
return [2 /*return*/, netInput.isBatchInput
? landmarksForBatch
: landmarksForBatch[0]];
}
});
});
};
FaceLandmark68NetBase.prototype.getClassifierChannelsOut = function () {
return 136;
};
return FaceLandmark68NetBase;
}(FaceProcessor_FaceProcessor));
//# sourceMappingURL=FaceLandmark68NetBase.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceLandmarkNet/FaceLandmark68Net.js
var FaceLandmark68Net_FaceLandmark68Net = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceLandmark68Net, _super);
function FaceLandmark68Net(faceFeatureExtractor) {
if (faceFeatureExtractor === void 0) { faceFeatureExtractor = new FaceFeatureExtractor_FaceFeatureExtractor(); }
return _super.call(this, 'FaceLandmark68Net', faceFeatureExtractor) || this;
}
FaceLandmark68Net.prototype.getDefaultModelName = function () {
return 'face_landmark_68_model';
};
FaceLandmark68Net.prototype.getClassifierChannelsIn = function () {
return 256;
};
return FaceLandmark68Net;
}(FaceLandmark68NetBase_FaceLandmark68NetBase));
//# sourceMappingURL=FaceLandmark68Net.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/extractParamsFromWeigthMapTiny.js
function extractParamsFromWeigthMapTiny_extractParamsFromWeigthMapTiny(weightMap) {
var paramMappings = [];
var extractDenseBlock3Params = loadParamsFactory_loadParamsFactory(weightMap, paramMappings).extractDenseBlock3Params;
var params = {
dense0: extractDenseBlock3Params('dense0', true),
dense1: extractDenseBlock3Params('dense1'),
dense2: extractDenseBlock3Params('dense2')
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMapTiny.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/extractParamsTiny.js
function extractParamsTiny_extractParamsTiny(weights) {
var paramMappings = [];
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var extractDenseBlock3Params = extractorsFactory_extractorsFactory(extractWeights, paramMappings).extractDenseBlock3Params;
var dense0 = extractDenseBlock3Params(3, 32, 'dense0', true);
var dense1 = extractDenseBlock3Params(32, 64, 'dense1');
var dense2 = extractDenseBlock3Params(64, 128, 'dense2');
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return {
paramMappings: paramMappings,
params: { dense0: dense0, dense1: dense1, dense2: dense2 }
};
}
//# sourceMappingURL=extractParamsTiny.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceFeatureExtractor/TinyFaceFeatureExtractor.js
var TinyFaceFeatureExtractor_TinyFaceFeatureExtractor = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(TinyFaceFeatureExtractor, _super);
function TinyFaceFeatureExtractor() {
return _super.call(this, 'TinyFaceFeatureExtractor') || this;
}
TinyFaceFeatureExtractor.prototype.forwardInput = function (input) {
var params = this.params;
if (!params) {
throw new Error('TinyFaceFeatureExtractor - load model before inference');
}
return tf_core_esm["tidy"](function () {
var batchTensor = input.toBatchTensor(112, true);
var meanRgb = [122.782, 117.001, 104.298];
var normalized = normalize_normalize(batchTensor, meanRgb).div(tf_core_esm["scalar"](255));
var out = denseBlock_denseBlock3(normalized, params.dense0, true);
out = denseBlock_denseBlock3(out, params.dense1);
out = denseBlock_denseBlock3(out, params.dense2);
out = tf_core_esm["avgPool"](out, [14, 14], [2, 2], 'valid');
return out;
});
};
TinyFaceFeatureExtractor.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
TinyFaceFeatureExtractor.prototype.getDefaultModelName = function () {
return 'face_feature_extractor_tiny_model';
};
TinyFaceFeatureExtractor.prototype.extractParamsFromWeigthMap = function (weightMap) {
return extractParamsFromWeigthMapTiny_extractParamsFromWeigthMapTiny(weightMap);
};
TinyFaceFeatureExtractor.prototype.extractParams = function (weights) {
return extractParamsTiny_extractParamsTiny(weights);
};
return TinyFaceFeatureExtractor;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=TinyFaceFeatureExtractor.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceLandmarkNet/FaceLandmark68TinyNet.js
var FaceLandmark68TinyNet_FaceLandmark68TinyNet = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceLandmark68TinyNet, _super);
function FaceLandmark68TinyNet(faceFeatureExtractor) {
if (faceFeatureExtractor === void 0) { faceFeatureExtractor = new TinyFaceFeatureExtractor_TinyFaceFeatureExtractor(); }
return _super.call(this, 'FaceLandmark68TinyNet', faceFeatureExtractor) || this;
}
FaceLandmark68TinyNet.prototype.getDefaultModelName = function () {
return 'face_landmark_68_tiny_model';
};
FaceLandmark68TinyNet.prototype.getClassifierChannelsIn = function () {
return 128;
};
return FaceLandmark68TinyNet;
}(FaceLandmark68NetBase_FaceLandmark68NetBase));
//# sourceMappingURL=FaceLandmark68TinyNet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceLandmarkNet/index.js
var faceLandmarkNet_FaceLandmarkNet = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceLandmarkNet, _super);
function FaceLandmarkNet() {
return _super !== null && _super.apply(this, arguments) || this;
}
return FaceLandmarkNet;
}(FaceLandmark68Net_FaceLandmark68Net));
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/scaleLayer.js
function scaleLayer_scale(x, params) {
return tf_core_esm["add"](tf_core_esm["mul"](x, params.weights), params.biases);
}
//# sourceMappingURL=scaleLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/convLayer.js
function faceRecognitionNet_convLayer_convLayer(x, params, strides, withRelu, padding) {
if (padding === void 0) { padding = 'same'; }
var _a = params.conv, filters = _a.filters, bias = _a.bias;
var out = tf_core_esm["conv2d"](x, filters, strides, padding);
out = tf_core_esm["add"](out, bias);
out = scaleLayer_scale(out, params.scale);
return withRelu ? tf_core_esm["relu"](out) : out;
}
function convLayer_conv(x, params) {
return faceRecognitionNet_convLayer_convLayer(x, params, [1, 1], true);
}
function convLayer_convNoRelu(x, params) {
return faceRecognitionNet_convLayer_convLayer(x, params, [1, 1], false);
}
function convLayer_convDown(x, params) {
return faceRecognitionNet_convLayer_convLayer(x, params, [2, 2], true, 'valid');
}
//# sourceMappingURL=convLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/extractParams.js
function faceRecognitionNet_extractParams_extractorsFactory(extractWeights, paramMappings) {
function extractFilterValues(numFilterValues, numFilters, filterSize) {
var weights = extractWeights(numFilterValues);
var depth = weights.length / (numFilters * filterSize * filterSize);
if (utils_isFloat(depth)) {
throw new Error("depth has to be an integer: " + depth + ", weights.length: " + weights.length + ", numFilters: " + numFilters + ", filterSize: " + filterSize);
}
return tf_core_esm["tidy"](function () { return tf_core_esm["transpose"](tf_core_esm["tensor4d"](weights, [numFilters, depth, filterSize, filterSize]), [2, 3, 1, 0]); });
}
function extractConvParams(numFilterValues, numFilters, filterSize, mappedPrefix) {
var filters = extractFilterValues(numFilterValues, numFilters, filterSize);
var bias = tf_core_esm["tensor1d"](extractWeights(numFilters));
paramMappings.push({ paramPath: mappedPrefix + "/filters" }, { paramPath: mappedPrefix + "/bias" });
return { filters: filters, bias: bias };
}
function extractScaleLayerParams(numWeights, mappedPrefix) {
var weights = tf_core_esm["tensor1d"](extractWeights(numWeights));
var biases = tf_core_esm["tensor1d"](extractWeights(numWeights));
paramMappings.push({ paramPath: mappedPrefix + "/weights" }, { paramPath: mappedPrefix + "/biases" });
return {
weights: weights,
biases: biases
};
}
function extractConvLayerParams(numFilterValues, numFilters, filterSize, mappedPrefix) {
var conv = extractConvParams(numFilterValues, numFilters, filterSize, mappedPrefix + "/conv");
var scale = extractScaleLayerParams(numFilters, mappedPrefix + "/scale");
return { conv: conv, scale: scale };
}
function extractResidualLayerParams(numFilterValues, numFilters, filterSize, mappedPrefix, isDown) {
if (isDown === void 0) { isDown = false; }
var conv1 = extractConvLayerParams((isDown ? 0.5 : 1) * numFilterValues, numFilters, filterSize, mappedPrefix + "/conv1");
var conv2 = extractConvLayerParams(numFilterValues, numFilters, filterSize, mappedPrefix + "/conv2");
return { conv1: conv1, conv2: conv2 };
}
return {
extractConvLayerParams: extractConvLayerParams,
extractResidualLayerParams: extractResidualLayerParams
};
}
function faceRecognitionNet_extractParams_extractParams(weights) {
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var paramMappings = [];
var _b = faceRecognitionNet_extractParams_extractorsFactory(extractWeights, paramMappings), extractConvLayerParams = _b.extractConvLayerParams, extractResidualLayerParams = _b.extractResidualLayerParams;
var conv32_down = extractConvLayerParams(4704, 32, 7, 'conv32_down');
var conv32_1 = extractResidualLayerParams(9216, 32, 3, 'conv32_1');
var conv32_2 = extractResidualLayerParams(9216, 32, 3, 'conv32_2');
var conv32_3 = extractResidualLayerParams(9216, 32, 3, 'conv32_3');
var conv64_down = extractResidualLayerParams(36864, 64, 3, 'conv64_down', true);
var conv64_1 = extractResidualLayerParams(36864, 64, 3, 'conv64_1');
var conv64_2 = extractResidualLayerParams(36864, 64, 3, 'conv64_2');
var conv64_3 = extractResidualLayerParams(36864, 64, 3, 'conv64_3');
var conv128_down = extractResidualLayerParams(147456, 128, 3, 'conv128_down', true);
var conv128_1 = extractResidualLayerParams(147456, 128, 3, 'conv128_1');
var conv128_2 = extractResidualLayerParams(147456, 128, 3, 'conv128_2');
var conv256_down = extractResidualLayerParams(589824, 256, 3, 'conv256_down', true);
var conv256_1 = extractResidualLayerParams(589824, 256, 3, 'conv256_1');
var conv256_2 = extractResidualLayerParams(589824, 256, 3, 'conv256_2');
var conv256_down_out = extractResidualLayerParams(589824, 256, 3, 'conv256_down_out');
var fc = tf_core_esm["tidy"](function () { return tf_core_esm["transpose"](tf_core_esm["tensor2d"](extractWeights(256 * 128), [128, 256]), [1, 0]); });
paramMappings.push({ paramPath: "fc" });
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
var params = {
conv32_down: conv32_down,
conv32_1: conv32_1,
conv32_2: conv32_2,
conv32_3: conv32_3,
conv64_down: conv64_down,
conv64_1: conv64_1,
conv64_2: conv64_2,
conv64_3: conv64_3,
conv128_down: conv128_down,
conv128_1: conv128_1,
conv128_2: conv128_2,
conv256_down: conv256_down,
conv256_1: conv256_1,
conv256_2: conv256_2,
conv256_down_out: conv256_down_out,
fc: fc
};
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/extractParamsFromWeigthMap.js
function extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings) {
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
function extractScaleLayerParams(prefix) {
var weights = extractWeightEntry(prefix + "/scale/weights", 1);
var biases = extractWeightEntry(prefix + "/scale/biases", 1);
return { weights: weights, biases: biases };
}
function extractConvLayerParams(prefix) {
var filters = extractWeightEntry(prefix + "/conv/filters", 4);
var bias = extractWeightEntry(prefix + "/conv/bias", 1);
var scale = extractScaleLayerParams(prefix);
return { conv: { filters: filters, bias: bias }, scale: scale };
}
function extractResidualLayerParams(prefix) {
return {
conv1: extractConvLayerParams(prefix + "/conv1"),
conv2: extractConvLayerParams(prefix + "/conv2")
};
}
return {
extractConvLayerParams: extractConvLayerParams,
extractResidualLayerParams: extractResidualLayerParams
};
}
function faceRecognitionNet_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap) {
var paramMappings = [];
var _a = extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings), extractConvLayerParams = _a.extractConvLayerParams, extractResidualLayerParams = _a.extractResidualLayerParams;
var conv32_down = extractConvLayerParams('conv32_down');
var conv32_1 = extractResidualLayerParams('conv32_1');
var conv32_2 = extractResidualLayerParams('conv32_2');
var conv32_3 = extractResidualLayerParams('conv32_3');
var conv64_down = extractResidualLayerParams('conv64_down');
var conv64_1 = extractResidualLayerParams('conv64_1');
var conv64_2 = extractResidualLayerParams('conv64_2');
var conv64_3 = extractResidualLayerParams('conv64_3');
var conv128_down = extractResidualLayerParams('conv128_down');
var conv128_1 = extractResidualLayerParams('conv128_1');
var conv128_2 = extractResidualLayerParams('conv128_2');
var conv256_down = extractResidualLayerParams('conv256_down');
var conv256_1 = extractResidualLayerParams('conv256_1');
var conv256_2 = extractResidualLayerParams('conv256_2');
var conv256_down_out = extractResidualLayerParams('conv256_down_out');
var fc = weightMap['fc'];
paramMappings.push({ originalPath: 'fc', paramPath: 'fc' });
if (!utils_isTensor2D(fc)) {
throw new Error("expected weightMap[fc] to be a Tensor2D, instead have " + fc);
}
var params = {
conv32_down: conv32_down,
conv32_1: conv32_1,
conv32_2: conv32_2,
conv32_3: conv32_3,
conv64_down: conv64_down,
conv64_1: conv64_1,
conv64_2: conv64_2,
conv64_3: conv64_3,
conv128_down: conv128_down,
conv128_1: conv128_1,
conv128_2: conv128_2,
conv256_down: conv256_down,
conv256_1: conv256_1,
conv256_2: conv256_2,
conv256_down_out: conv256_down_out,
fc: fc
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/residualLayer.js
function residualLayer_residual(x, params) {
var out = convLayer_conv(x, params.conv1);
out = convLayer_convNoRelu(out, params.conv2);
out = tf_core_esm["add"](out, x);
out = tf_core_esm["relu"](out);
return out;
}
function residualLayer_residualDown(x, params) {
var out = convLayer_convDown(x, params.conv1);
out = convLayer_convNoRelu(out, params.conv2);
var pooled = tf_core_esm["avgPool"](x, 2, 2, 'valid');
var zeros = tf_core_esm["zeros"](pooled.shape);
var isPad = pooled.shape[3] !== out.shape[3];
var isAdjustShape = pooled.shape[1] !== out.shape[1] || pooled.shape[2] !== out.shape[2];
if (isAdjustShape) {
var padShapeX = Object(tslib_es6["e" /* __spreadArrays */])(out.shape);
padShapeX[1] = 1;
var zerosW = tf_core_esm["zeros"](padShapeX);
out = tf_core_esm["concat"]([out, zerosW], 1);
var padShapeY = Object(tslib_es6["e" /* __spreadArrays */])(out.shape);
padShapeY[2] = 1;
var zerosH = tf_core_esm["zeros"](padShapeY);
out = tf_core_esm["concat"]([out, zerosH], 2);
}
pooled = isPad ? tf_core_esm["concat"]([pooled, zeros], 3) : pooled;
out = tf_core_esm["add"](pooled, out);
out = tf_core_esm["relu"](out);
return out;
}
//# sourceMappingURL=residualLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/FaceRecognitionNet.js
var FaceRecognitionNet_FaceRecognitionNet = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceRecognitionNet, _super);
function FaceRecognitionNet() {
return _super.call(this, 'FaceRecognitionNet') || this;
}
FaceRecognitionNet.prototype.forwardInput = function (input) {
var params = this.params;
if (!params) {
throw new Error('FaceRecognitionNet - load model before inference');
}
return tf_core_esm["tidy"](function () {
var batchTensor = input.toBatchTensor(150, true).toFloat();
var meanRgb = [122.782, 117.001, 104.298];
var normalized = normalize_normalize(batchTensor, meanRgb).div(tf_core_esm["scalar"](256));
var out = convLayer_convDown(normalized, params.conv32_down);
out = tf_core_esm["maxPool"](out, 3, 2, 'valid');
out = residualLayer_residual(out, params.conv32_1);
out = residualLayer_residual(out, params.conv32_2);
out = residualLayer_residual(out, params.conv32_3);
out = residualLayer_residualDown(out, params.conv64_down);
out = residualLayer_residual(out, params.conv64_1);
out = residualLayer_residual(out, params.conv64_2);
out = residualLayer_residual(out, params.conv64_3);
out = residualLayer_residualDown(out, params.conv128_down);
out = residualLayer_residual(out, params.conv128_1);
out = residualLayer_residual(out, params.conv128_2);
out = residualLayer_residualDown(out, params.conv256_down);
out = residualLayer_residual(out, params.conv256_1);
out = residualLayer_residual(out, params.conv256_2);
out = residualLayer_residualDown(out, params.conv256_down_out);
var globalAvg = out.mean([1, 2]);
var fullyConnected = tf_core_esm["matMul"](globalAvg, params.fc);
return fullyConnected;
});
};
FaceRecognitionNet.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
FaceRecognitionNet.prototype.computeFaceDescriptor = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var netInput, faceDescriptorTensors, faceDescriptorsForBatch;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _a.sent();
faceDescriptorTensors = tf_core_esm["tidy"](function () { return tf_core_esm["unstack"](_this.forwardInput(netInput)); });
return [4 /*yield*/, Promise.all(faceDescriptorTensors.map(function (t) { return t.data(); }))];
case 2:
faceDescriptorsForBatch = _a.sent();
faceDescriptorTensors.forEach(function (t) { return t.dispose(); });
return [2 /*return*/, netInput.isBatchInput
? faceDescriptorsForBatch
: faceDescriptorsForBatch[0]];
}
});
});
};
FaceRecognitionNet.prototype.getDefaultModelName = function () {
return 'face_recognition_model';
};
FaceRecognitionNet.prototype.extractParamsFromWeigthMap = function (weightMap) {
return faceRecognitionNet_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap);
};
FaceRecognitionNet.prototype.extractParams = function (weights) {
return faceRecognitionNet_extractParams_extractParams(weights);
};
return FaceRecognitionNet;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=FaceRecognitionNet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/faceRecognitionNet/index.js
function faceRecognitionNet_createFaceRecognitionNet(weights) {
var net = new FaceRecognitionNet_FaceRecognitionNet();
net.extractWeights(weights);
return net;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/WithFaceDescriptor.js
function extendWithFaceDescriptor(sourceObj, descriptor) {
var extension = { descriptor: descriptor };
return Object.assign({}, sourceObj, extension);
}
//# sourceMappingURL=WithFaceDescriptor.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/WithAge.js
function isWithAge(obj) {
return typeof obj['age'] === 'number';
}
function extendWithAge(sourceObj, age) {
var extension = { age: age };
return Object.assign({}, sourceObj, extension);
}
//# sourceMappingURL=WithAge.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/WithGender.js
function WithGender_isWithGender(obj) {
return (obj['gender'] === Gender.MALE || obj['gender'] === Gender.FEMALE)
&& utils_isValidProbablitiy(obj['genderProbability']);
}
function WithGender_extendWithGender(sourceObj, gender, genderProbability) {
var extension = { gender: gender, genderProbability: genderProbability };
return Object.assign({}, sourceObj, extension);
}
//# sourceMappingURL=WithGender.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/factories/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/MtcnnOptions.js
var MtcnnOptions = /** @class */ (function () {
function MtcnnOptions(_a) {
var _b = _a === void 0 ? {} : _a, minFaceSize = _b.minFaceSize, scaleFactor = _b.scaleFactor, maxNumScales = _b.maxNumScales, scoreThresholds = _b.scoreThresholds, scaleSteps = _b.scaleSteps;
this._name = 'MtcnnOptions';
this._minFaceSize = minFaceSize || 20;
this._scaleFactor = scaleFactor || 0.709;
this._maxNumScales = maxNumScales || 10;
this._scoreThresholds = scoreThresholds || [0.6, 0.7, 0.7];
this._scaleSteps = scaleSteps;
if (typeof this._minFaceSize !== 'number' || this._minFaceSize < 0) {
throw new Error(this._name + " - expected minFaceSize to be a number > 0");
}
if (typeof this._scaleFactor !== 'number' || this._scaleFactor <= 0 || this._scaleFactor >= 1) {
throw new Error(this._name + " - expected scaleFactor to be a number between 0 and 1");
}
if (typeof this._maxNumScales !== 'number' || this._maxNumScales < 0) {
throw new Error(this._name + " - expected maxNumScales to be a number > 0");
}
if (!Array.isArray(this._scoreThresholds)
|| this._scoreThresholds.length !== 3
|| this._scoreThresholds.some(function (th) { return typeof th !== 'number'; })) {
throw new Error(this._name + " - expected scoreThresholds to be an array of numbers of length 3");
}
if (this._scaleSteps
&& (!Array.isArray(this._scaleSteps) || this._scaleSteps.some(function (th) { return typeof th !== 'number'; }))) {
throw new Error(this._name + " - expected scaleSteps to be an array of numbers");
}
}
Object.defineProperty(MtcnnOptions.prototype, "minFaceSize", {
get: function () { return this._minFaceSize; },
enumerable: true,
configurable: true
});
Object.defineProperty(MtcnnOptions.prototype, "scaleFactor", {
get: function () { return this._scaleFactor; },
enumerable: true,
configurable: true
});
Object.defineProperty(MtcnnOptions.prototype, "maxNumScales", {
get: function () { return this._maxNumScales; },
enumerable: true,
configurable: true
});
Object.defineProperty(MtcnnOptions.prototype, "scoreThresholds", {
get: function () { return this._scoreThresholds; },
enumerable: true,
configurable: true
});
Object.defineProperty(MtcnnOptions.prototype, "scaleSteps", {
get: function () { return this._scaleSteps; },
enumerable: true,
configurable: true
});
return MtcnnOptions;
}());
//# sourceMappingURL=MtcnnOptions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/extractParams.js
function ssdMobilenetv1_extractParams_extractorsFactory(extractWeights, paramMappings) {
function extractDepthwiseConvParams(numChannels, mappedPrefix) {
var filters = tf_core_esm["tensor4d"](extractWeights(3 * 3 * numChannels), [3, 3, numChannels, 1]);
var batch_norm_scale = tf_core_esm["tensor1d"](extractWeights(numChannels));
var batch_norm_offset = tf_core_esm["tensor1d"](extractWeights(numChannels));
var batch_norm_mean = tf_core_esm["tensor1d"](extractWeights(numChannels));
var batch_norm_variance = tf_core_esm["tensor1d"](extractWeights(numChannels));
paramMappings.push({ paramPath: mappedPrefix + "/filters" }, { paramPath: mappedPrefix + "/batch_norm_scale" }, { paramPath: mappedPrefix + "/batch_norm_offset" }, { paramPath: mappedPrefix + "/batch_norm_mean" }, { paramPath: mappedPrefix + "/batch_norm_variance" });
return {
filters: filters,
batch_norm_scale: batch_norm_scale,
batch_norm_offset: batch_norm_offset,
batch_norm_mean: batch_norm_mean,
batch_norm_variance: batch_norm_variance
};
}
function extractConvParams(channelsIn, channelsOut, filterSize, mappedPrefix, isPointwiseConv) {
var filters = tf_core_esm["tensor4d"](extractWeights(channelsIn * channelsOut * filterSize * filterSize), [filterSize, filterSize, channelsIn, channelsOut]);
var bias = tf_core_esm["tensor1d"](extractWeights(channelsOut));
paramMappings.push({ paramPath: mappedPrefix + "/filters" }, { paramPath: mappedPrefix + "/" + (isPointwiseConv ? 'batch_norm_offset' : 'bias') });
return { filters: filters, bias: bias };
}
function extractPointwiseConvParams(channelsIn, channelsOut, filterSize, mappedPrefix) {
var _a = extractConvParams(channelsIn, channelsOut, filterSize, mappedPrefix, true), filters = _a.filters, bias = _a.bias;
return {
filters: filters,
batch_norm_offset: bias
};
}
function extractConvPairParams(channelsIn, channelsOut, mappedPrefix) {
var depthwise_conv = extractDepthwiseConvParams(channelsIn, mappedPrefix + "/depthwise_conv");
var pointwise_conv = extractPointwiseConvParams(channelsIn, channelsOut, 1, mappedPrefix + "/pointwise_conv");
return { depthwise_conv: depthwise_conv, pointwise_conv: pointwise_conv };
}
function extractMobilenetV1Params() {
var conv_0 = extractPointwiseConvParams(3, 32, 3, 'mobilenetv1/conv_0');
var conv_1 = extractConvPairParams(32, 64, 'mobilenetv1/conv_1');
var conv_2 = extractConvPairParams(64, 128, 'mobilenetv1/conv_2');
var conv_3 = extractConvPairParams(128, 128, 'mobilenetv1/conv_3');
var conv_4 = extractConvPairParams(128, 256, 'mobilenetv1/conv_4');
var conv_5 = extractConvPairParams(256, 256, 'mobilenetv1/conv_5');
var conv_6 = extractConvPairParams(256, 512, 'mobilenetv1/conv_6');
var conv_7 = extractConvPairParams(512, 512, 'mobilenetv1/conv_7');
var conv_8 = extractConvPairParams(512, 512, 'mobilenetv1/conv_8');
var conv_9 = extractConvPairParams(512, 512, 'mobilenetv1/conv_9');
var conv_10 = extractConvPairParams(512, 512, 'mobilenetv1/conv_10');
var conv_11 = extractConvPairParams(512, 512, 'mobilenetv1/conv_11');
var conv_12 = extractConvPairParams(512, 1024, 'mobilenetv1/conv_12');
var conv_13 = extractConvPairParams(1024, 1024, 'mobilenetv1/conv_13');
return {
conv_0: conv_0,
conv_1: conv_1,
conv_2: conv_2,
conv_3: conv_3,
conv_4: conv_4,
conv_5: conv_5,
conv_6: conv_6,
conv_7: conv_7,
conv_8: conv_8,
conv_9: conv_9,
conv_10: conv_10,
conv_11: conv_11,
conv_12: conv_12,
conv_13: conv_13
};
}
function extractPredictionLayerParams() {
var conv_0 = extractPointwiseConvParams(1024, 256, 1, 'prediction_layer/conv_0');
var conv_1 = extractPointwiseConvParams(256, 512, 3, 'prediction_layer/conv_1');
var conv_2 = extractPointwiseConvParams(512, 128, 1, 'prediction_layer/conv_2');
var conv_3 = extractPointwiseConvParams(128, 256, 3, 'prediction_layer/conv_3');
var conv_4 = extractPointwiseConvParams(256, 128, 1, 'prediction_layer/conv_4');
var conv_5 = extractPointwiseConvParams(128, 256, 3, 'prediction_layer/conv_5');
var conv_6 = extractPointwiseConvParams(256, 64, 1, 'prediction_layer/conv_6');
var conv_7 = extractPointwiseConvParams(64, 128, 3, 'prediction_layer/conv_7');
var box_encoding_0_predictor = extractConvParams(512, 12, 1, 'prediction_layer/box_predictor_0/box_encoding_predictor');
var class_predictor_0 = extractConvParams(512, 9, 1, 'prediction_layer/box_predictor_0/class_predictor');
var box_encoding_1_predictor = extractConvParams(1024, 24, 1, 'prediction_layer/box_predictor_1/box_encoding_predictor');
var class_predictor_1 = extractConvParams(1024, 18, 1, 'prediction_layer/box_predictor_1/class_predictor');
var box_encoding_2_predictor = extractConvParams(512, 24, 1, 'prediction_layer/box_predictor_2/box_encoding_predictor');
var class_predictor_2 = extractConvParams(512, 18, 1, 'prediction_layer/box_predictor_2/class_predictor');
var box_encoding_3_predictor = extractConvParams(256, 24, 1, 'prediction_layer/box_predictor_3/box_encoding_predictor');
var class_predictor_3 = extractConvParams(256, 18, 1, 'prediction_layer/box_predictor_3/class_predictor');
var box_encoding_4_predictor = extractConvParams(256, 24, 1, 'prediction_layer/box_predictor_4/box_encoding_predictor');
var class_predictor_4 = extractConvParams(256, 18, 1, 'prediction_layer/box_predictor_4/class_predictor');
var box_encoding_5_predictor = extractConvParams(128, 24, 1, 'prediction_layer/box_predictor_5/box_encoding_predictor');
var class_predictor_5 = extractConvParams(128, 18, 1, 'prediction_layer/box_predictor_5/class_predictor');
var box_predictor_0 = {
box_encoding_predictor: box_encoding_0_predictor,
class_predictor: class_predictor_0
};
var box_predictor_1 = {
box_encoding_predictor: box_encoding_1_predictor,
class_predictor: class_predictor_1
};
var box_predictor_2 = {
box_encoding_predictor: box_encoding_2_predictor,
class_predictor: class_predictor_2
};
var box_predictor_3 = {
box_encoding_predictor: box_encoding_3_predictor,
class_predictor: class_predictor_3
};
var box_predictor_4 = {
box_encoding_predictor: box_encoding_4_predictor,
class_predictor: class_predictor_4
};
var box_predictor_5 = {
box_encoding_predictor: box_encoding_5_predictor,
class_predictor: class_predictor_5
};
return {
conv_0: conv_0,
conv_1: conv_1,
conv_2: conv_2,
conv_3: conv_3,
conv_4: conv_4,
conv_5: conv_5,
conv_6: conv_6,
conv_7: conv_7,
box_predictor_0: box_predictor_0,
box_predictor_1: box_predictor_1,
box_predictor_2: box_predictor_2,
box_predictor_3: box_predictor_3,
box_predictor_4: box_predictor_4,
box_predictor_5: box_predictor_5
};
}
return {
extractMobilenetV1Params: extractMobilenetV1Params,
extractPredictionLayerParams: extractPredictionLayerParams
};
}
function ssdMobilenetv1_extractParams_extractParams(weights) {
var paramMappings = [];
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var _b = ssdMobilenetv1_extractParams_extractorsFactory(extractWeights, paramMappings), extractMobilenetV1Params = _b.extractMobilenetV1Params, extractPredictionLayerParams = _b.extractPredictionLayerParams;
var mobilenetv1 = extractMobilenetV1Params();
var prediction_layer = extractPredictionLayerParams();
var extra_dim = tf_core_esm["tensor3d"](extractWeights(5118 * 4), [1, 5118, 4]);
var output_layer = {
extra_dim: extra_dim
};
paramMappings.push({ paramPath: 'output_layer/extra_dim' });
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return {
params: {
mobilenetv1: mobilenetv1,
prediction_layer: prediction_layer,
output_layer: output_layer
},
paramMappings: paramMappings
};
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/extractParamsFromWeigthMap.js
function ssdMobilenetv1_extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings) {
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
function extractPointwiseConvParams(prefix, idx, mappedPrefix) {
var filters = extractWeightEntry(prefix + "/Conv2d_" + idx + "_pointwise/weights", 4, mappedPrefix + "/filters");
var batch_norm_offset = extractWeightEntry(prefix + "/Conv2d_" + idx + "_pointwise/convolution_bn_offset", 1, mappedPrefix + "/batch_norm_offset");
return { filters: filters, batch_norm_offset: batch_norm_offset };
}
function extractConvPairParams(idx) {
var mappedPrefix = "mobilenetv1/conv_" + idx;
var prefixDepthwiseConv = "MobilenetV1/Conv2d_" + idx + "_depthwise";
var mappedPrefixDepthwiseConv = mappedPrefix + "/depthwise_conv";
var mappedPrefixPointwiseConv = mappedPrefix + "/pointwise_conv";
var filters = extractWeightEntry(prefixDepthwiseConv + "/depthwise_weights", 4, mappedPrefixDepthwiseConv + "/filters");
var batch_norm_scale = extractWeightEntry(prefixDepthwiseConv + "/BatchNorm/gamma", 1, mappedPrefixDepthwiseConv + "/batch_norm_scale");
var batch_norm_offset = extractWeightEntry(prefixDepthwiseConv + "/BatchNorm/beta", 1, mappedPrefixDepthwiseConv + "/batch_norm_offset");
var batch_norm_mean = extractWeightEntry(prefixDepthwiseConv + "/BatchNorm/moving_mean", 1, mappedPrefixDepthwiseConv + "/batch_norm_mean");
var batch_norm_variance = extractWeightEntry(prefixDepthwiseConv + "/BatchNorm/moving_variance", 1, mappedPrefixDepthwiseConv + "/batch_norm_variance");
return {
depthwise_conv: {
filters: filters,
batch_norm_scale: batch_norm_scale,
batch_norm_offset: batch_norm_offset,
batch_norm_mean: batch_norm_mean,
batch_norm_variance: batch_norm_variance
},
pointwise_conv: extractPointwiseConvParams('MobilenetV1', idx, mappedPrefixPointwiseConv)
};
}
function extractMobilenetV1Params() {
return {
conv_0: extractPointwiseConvParams('MobilenetV1', 0, 'mobilenetv1/conv_0'),
conv_1: extractConvPairParams(1),
conv_2: extractConvPairParams(2),
conv_3: extractConvPairParams(3),
conv_4: extractConvPairParams(4),
conv_5: extractConvPairParams(5),
conv_6: extractConvPairParams(6),
conv_7: extractConvPairParams(7),
conv_8: extractConvPairParams(8),
conv_9: extractConvPairParams(9),
conv_10: extractConvPairParams(10),
conv_11: extractConvPairParams(11),
conv_12: extractConvPairParams(12),
conv_13: extractConvPairParams(13)
};
}
function extractConvParams(prefix, mappedPrefix) {
var filters = extractWeightEntry(prefix + "/weights", 4, mappedPrefix + "/filters");
var bias = extractWeightEntry(prefix + "/biases", 1, mappedPrefix + "/bias");
return { filters: filters, bias: bias };
}
function extractBoxPredictorParams(idx) {
var box_encoding_predictor = extractConvParams("Prediction/BoxPredictor_" + idx + "/BoxEncodingPredictor", "prediction_layer/box_predictor_" + idx + "/box_encoding_predictor");
var class_predictor = extractConvParams("Prediction/BoxPredictor_" + idx + "/ClassPredictor", "prediction_layer/box_predictor_" + idx + "/class_predictor");
return { box_encoding_predictor: box_encoding_predictor, class_predictor: class_predictor };
}
function extractPredictionLayerParams() {
return {
conv_0: extractPointwiseConvParams('Prediction', 0, 'prediction_layer/conv_0'),
conv_1: extractPointwiseConvParams('Prediction', 1, 'prediction_layer/conv_1'),
conv_2: extractPointwiseConvParams('Prediction', 2, 'prediction_layer/conv_2'),
conv_3: extractPointwiseConvParams('Prediction', 3, 'prediction_layer/conv_3'),
conv_4: extractPointwiseConvParams('Prediction', 4, 'prediction_layer/conv_4'),
conv_5: extractPointwiseConvParams('Prediction', 5, 'prediction_layer/conv_5'),
conv_6: extractPointwiseConvParams('Prediction', 6, 'prediction_layer/conv_6'),
conv_7: extractPointwiseConvParams('Prediction', 7, 'prediction_layer/conv_7'),
box_predictor_0: extractBoxPredictorParams(0),
box_predictor_1: extractBoxPredictorParams(1),
box_predictor_2: extractBoxPredictorParams(2),
box_predictor_3: extractBoxPredictorParams(3),
box_predictor_4: extractBoxPredictorParams(4),
box_predictor_5: extractBoxPredictorParams(5)
};
}
return {
extractMobilenetV1Params: extractMobilenetV1Params,
extractPredictionLayerParams: extractPredictionLayerParams
};
}
function ssdMobilenetv1_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap) {
var paramMappings = [];
var _a = ssdMobilenetv1_extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings), extractMobilenetV1Params = _a.extractMobilenetV1Params, extractPredictionLayerParams = _a.extractPredictionLayerParams;
var extra_dim = weightMap['Output/extra_dim'];
paramMappings.push({ originalPath: 'Output/extra_dim', paramPath: 'output_layer/extra_dim' });
if (!utils_isTensor3D(extra_dim)) {
throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have " + extra_dim);
}
var params = {
mobilenetv1: extractMobilenetV1Params(),
prediction_layer: extractPredictionLayerParams(),
output_layer: {
extra_dim: extra_dim
}
};
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/pointwiseConvLayer.js
function pointwiseConvLayer_pointwiseConvLayer(x, params, strides) {
return tf_core_esm["tidy"](function () {
var out = tf_core_esm["conv2d"](x, params.filters, strides, 'same');
out = tf_core_esm["add"](out, params.batch_norm_offset);
return tf_core_esm["clipByValue"](out, 0, 6);
});
}
//# sourceMappingURL=pointwiseConvLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/mobileNetV1.js
var mobileNetV1_epsilon = 0.0010000000474974513;
function mobileNetV1_depthwiseConvLayer(x, params, strides) {
return tf_core_esm["tidy"](function () {
var out = tf_core_esm["depthwiseConv2d"](x, params.filters, strides, 'same');
out = tf_core_esm["batchNorm"](out, params.batch_norm_mean, params.batch_norm_variance, params.batch_norm_offset, params.batch_norm_scale, mobileNetV1_epsilon);
return tf_core_esm["clipByValue"](out, 0, 6);
});
}
function mobileNetV1_getStridesForLayerIdx(layerIdx) {
return [2, 4, 6, 12].some(function (idx) { return idx === layerIdx; }) ? [2, 2] : [1, 1];
}
function mobileNetV1_mobileNetV1(x, params) {
return tf_core_esm["tidy"](function () {
var conv11 = null;
var out = pointwiseConvLayer_pointwiseConvLayer(x, params.conv_0, [2, 2]);
var convPairParams = [
params.conv_1,
params.conv_2,
params.conv_3,
params.conv_4,
params.conv_5,
params.conv_6,
params.conv_7,
params.conv_8,
params.conv_9,
params.conv_10,
params.conv_11,
params.conv_12,
params.conv_13
];
convPairParams.forEach(function (param, i) {
var layerIdx = i + 1;
var depthwiseConvStrides = mobileNetV1_getStridesForLayerIdx(layerIdx);
out = mobileNetV1_depthwiseConvLayer(out, param.depthwise_conv, depthwiseConvStrides);
out = pointwiseConvLayer_pointwiseConvLayer(out, param.pointwise_conv, [1, 1]);
if (layerIdx === 11) {
conv11 = out;
}
});
if (conv11 === null) {
throw new Error('mobileNetV1 - output of conv layer 11 is null');
}
return {
out: out,
conv11: conv11
};
});
}
//# sourceMappingURL=mobileNetV1.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/nonMaxSuppression.js
function ssdMobilenetv1_nonMaxSuppression_nonMaxSuppression(boxes, scores, maxOutputSize, iouThreshold, scoreThreshold) {
var numBoxes = boxes.shape[0];
var outputSize = Math.min(maxOutputSize, numBoxes);
var candidates = scores
.map(function (score, boxIndex) { return ({ score: score, boxIndex: boxIndex }); })
.filter(function (c) { return c.score > scoreThreshold; })
.sort(function (c1, c2) { return c2.score - c1.score; });
var suppressFunc = function (x) { return x <= iouThreshold ? 1 : 0; };
var selected = [];
candidates.forEach(function (c) {
if (selected.length >= outputSize) {
return;
}
var originalScore = c.score;
for (var j = selected.length - 1; j >= 0; --j) {
var iou = IOU(boxes, c.boxIndex, selected[j]);
if (iou === 0.0) {
continue;
}
c.score *= suppressFunc(iou);
if (c.score <= scoreThreshold) {
break;
}
}
if (originalScore === c.score) {
selected.push(c.boxIndex);
}
});
return selected;
}
function IOU(boxes, i, j) {
var boxesData = boxes.arraySync();
var yminI = Math.min(boxesData[i][0], boxesData[i][2]);
var xminI = Math.min(boxesData[i][1], boxesData[i][3]);
var ymaxI = Math.max(boxesData[i][0], boxesData[i][2]);
var xmaxI = Math.max(boxesData[i][1], boxesData[i][3]);
var yminJ = Math.min(boxesData[j][0], boxesData[j][2]);
var xminJ = Math.min(boxesData[j][1], boxesData[j][3]);
var ymaxJ = Math.max(boxesData[j][0], boxesData[j][2]);
var xmaxJ = Math.max(boxesData[j][1], boxesData[j][3]);
var areaI = (ymaxI - yminI) * (xmaxI - xminI);
var areaJ = (ymaxJ - yminJ) * (xmaxJ - xminJ);
if (areaI <= 0 || areaJ <= 0) {
return 0.0;
}
var intersectionYmin = Math.max(yminI, yminJ);
var intersectionXmin = Math.max(xminI, xminJ);
var intersectionYmax = Math.min(ymaxI, ymaxJ);
var intersectionXmax = Math.min(xmaxI, xmaxJ);
var intersectionArea = Math.max(intersectionYmax - intersectionYmin, 0.0) *
Math.max(intersectionXmax - intersectionXmin, 0.0);
return intersectionArea / (areaI + areaJ - intersectionArea);
}
//# sourceMappingURL=nonMaxSuppression.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/outputLayer.js
function outputLayer_getCenterCoordinatesAndSizesLayer(x) {
var vec = tf_core_esm["unstack"](tf_core_esm["transpose"](x, [1, 0]));
var sizes = [
tf_core_esm["sub"](vec[2], vec[0]),
tf_core_esm["sub"](vec[3], vec[1])
];
var centers = [
tf_core_esm["add"](vec[0], tf_core_esm["div"](sizes[0], tf_core_esm["scalar"](2))),
tf_core_esm["add"](vec[1], tf_core_esm["div"](sizes[1], tf_core_esm["scalar"](2)))
];
return {
sizes: sizes,
centers: centers
};
}
function outputLayer_decodeBoxesLayer(x0, x1) {
var _a = outputLayer_getCenterCoordinatesAndSizesLayer(x0), sizes = _a.sizes, centers = _a.centers;
var vec = tf_core_esm["unstack"](tf_core_esm["transpose"](x1, [1, 0]));
var div0_out = tf_core_esm["div"](tf_core_esm["mul"](tf_core_esm["exp"](tf_core_esm["div"](vec[2], tf_core_esm["scalar"](5))), sizes[0]), tf_core_esm["scalar"](2));
var add0_out = tf_core_esm["add"](tf_core_esm["mul"](tf_core_esm["div"](vec[0], tf_core_esm["scalar"](10)), sizes[0]), centers[0]);
var div1_out = tf_core_esm["div"](tf_core_esm["mul"](tf_core_esm["exp"](tf_core_esm["div"](vec[3], tf_core_esm["scalar"](5))), sizes[1]), tf_core_esm["scalar"](2));
var add1_out = tf_core_esm["add"](tf_core_esm["mul"](tf_core_esm["div"](vec[1], tf_core_esm["scalar"](10)), sizes[1]), centers[1]);
return tf_core_esm["transpose"](tf_core_esm["stack"]([
tf_core_esm["sub"](add0_out, div0_out),
tf_core_esm["sub"](add1_out, div1_out),
tf_core_esm["add"](add0_out, div0_out),
tf_core_esm["add"](add1_out, div1_out)
]), [1, 0]);
}
function outputLayer_outputLayer(boxPredictions, classPredictions, params) {
return tf_core_esm["tidy"](function () {
var batchSize = boxPredictions.shape[0];
var boxes = outputLayer_decodeBoxesLayer(tf_core_esm["reshape"](tf_core_esm["tile"](params.extra_dim, [batchSize, 1, 1]), [-1, 4]), tf_core_esm["reshape"](boxPredictions, [-1, 4]));
boxes = tf_core_esm["reshape"](boxes, [batchSize, (boxes.shape[0] / batchSize), 4]);
var scoresAndClasses = tf_core_esm["sigmoid"](tf_core_esm["slice"](classPredictions, [0, 0, 1], [-1, -1, -1]));
var scores = tf_core_esm["slice"](scoresAndClasses, [0, 0, 0], [-1, -1, 1]);
scores = tf_core_esm["reshape"](scores, [batchSize, scores.shape[1]]);
var boxesByBatch = tf_core_esm["unstack"](boxes);
var scoresByBatch = tf_core_esm["unstack"](scores);
return {
boxes: boxesByBatch,
scores: scoresByBatch
};
});
}
//# sourceMappingURL=outputLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/boxPredictionLayer.js
function boxPredictionLayer_boxPredictionLayer(x, params) {
return tf_core_esm["tidy"](function () {
var batchSize = x.shape[0];
var boxPredictionEncoding = tf_core_esm["reshape"](convLayer_convLayer(x, params.box_encoding_predictor), [batchSize, -1, 1, 4]);
var classPrediction = tf_core_esm["reshape"](convLayer_convLayer(x, params.class_predictor), [batchSize, -1, 3]);
return {
boxPredictionEncoding: boxPredictionEncoding,
classPrediction: classPrediction
};
});
}
//# sourceMappingURL=boxPredictionLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/predictionLayer.js
function predictionLayer_predictionLayer(x, conv11, params) {
return tf_core_esm["tidy"](function () {
var conv0 = pointwiseConvLayer_pointwiseConvLayer(x, params.conv_0, [1, 1]);
var conv1 = pointwiseConvLayer_pointwiseConvLayer(conv0, params.conv_1, [2, 2]);
var conv2 = pointwiseConvLayer_pointwiseConvLayer(conv1, params.conv_2, [1, 1]);
var conv3 = pointwiseConvLayer_pointwiseConvLayer(conv2, params.conv_3, [2, 2]);
var conv4 = pointwiseConvLayer_pointwiseConvLayer(conv3, params.conv_4, [1, 1]);
var conv5 = pointwiseConvLayer_pointwiseConvLayer(conv4, params.conv_5, [2, 2]);
var conv6 = pointwiseConvLayer_pointwiseConvLayer(conv5, params.conv_6, [1, 1]);
var conv7 = pointwiseConvLayer_pointwiseConvLayer(conv6, params.conv_7, [2, 2]);
var boxPrediction0 = boxPredictionLayer_boxPredictionLayer(conv11, params.box_predictor_0);
var boxPrediction1 = boxPredictionLayer_boxPredictionLayer(x, params.box_predictor_1);
var boxPrediction2 = boxPredictionLayer_boxPredictionLayer(conv1, params.box_predictor_2);
var boxPrediction3 = boxPredictionLayer_boxPredictionLayer(conv3, params.box_predictor_3);
var boxPrediction4 = boxPredictionLayer_boxPredictionLayer(conv5, params.box_predictor_4);
var boxPrediction5 = boxPredictionLayer_boxPredictionLayer(conv7, params.box_predictor_5);
var boxPredictions = tf_core_esm["concat"]([
boxPrediction0.boxPredictionEncoding,
boxPrediction1.boxPredictionEncoding,
boxPrediction2.boxPredictionEncoding,
boxPrediction3.boxPredictionEncoding,
boxPrediction4.boxPredictionEncoding,
boxPrediction5.boxPredictionEncoding
], 1);
var classPredictions = tf_core_esm["concat"]([
boxPrediction0.classPrediction,
boxPrediction1.classPrediction,
boxPrediction2.classPrediction,
boxPrediction3.classPrediction,
boxPrediction4.classPrediction,
boxPrediction5.classPrediction
], 1);
return {
boxPredictions: boxPredictions,
classPredictions: classPredictions
};
});
}
//# sourceMappingURL=predictionLayer.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/SsdMobilenetv1Options.js
var SsdMobilenetv1Options = /** @class */ (function () {
function SsdMobilenetv1Options(_a) {
var _b = _a === void 0 ? {} : _a, minConfidence = _b.minConfidence, maxResults = _b.maxResults;
this._name = 'SsdMobilenetv1Options';
this._minConfidence = minConfidence || 0.5;
this._maxResults = maxResults || 100;
if (typeof this._minConfidence !== 'number' || this._minConfidence <= 0 || this._minConfidence >= 1) {
throw new Error(this._name + " - expected minConfidence to be a number between 0 and 1");
}
if (typeof this._maxResults !== 'number') {
throw new Error(this._name + " - expected maxResults to be a number");
}
}
Object.defineProperty(SsdMobilenetv1Options.prototype, "minConfidence", {
get: function () { return this._minConfidence; },
enumerable: true,
configurable: true
});
Object.defineProperty(SsdMobilenetv1Options.prototype, "maxResults", {
get: function () { return this._maxResults; },
enumerable: true,
configurable: true
});
return SsdMobilenetv1Options;
}());
//# sourceMappingURL=SsdMobilenetv1Options.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/SsdMobilenetv1.js
var SsdMobilenetv1_SsdMobilenetv1 = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(SsdMobilenetv1, _super);
function SsdMobilenetv1() {
return _super.call(this, 'SsdMobilenetv1') || this;
}
SsdMobilenetv1.prototype.forwardInput = function (input) {
var params = this.params;
if (!params) {
throw new Error('SsdMobilenetv1 - load model before inference');
}
return tf_core_esm["tidy"](function () {
var batchTensor = input.toBatchTensor(512, false).toFloat();
var x = tf_core_esm["sub"](tf_core_esm["mul"](batchTensor, tf_core_esm["scalar"](0.007843137718737125)), tf_core_esm["scalar"](1));
var features = mobileNetV1_mobileNetV1(x, params.mobilenetv1);
var _a = predictionLayer_predictionLayer(features.out, features.conv11, params.prediction_layer), boxPredictions = _a.boxPredictions, classPredictions = _a.classPredictions;
return outputLayer_outputLayer(boxPredictions, classPredictions, params.output_layer);
});
};
SsdMobilenetv1.prototype.forward = function (input) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent()])];
}
});
});
};
SsdMobilenetv1.prototype.locateFaces = function (input, options) {
if (options === void 0) { options = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a, maxResults, minConfidence, netInput, _b, _boxes, _scores, boxes, scores, i, scoresData, _c, _d, iouThreshold, indices, reshapedDims, inputSize, padX, padY, boxesData, results;
return Object(tslib_es6["d" /* __generator */])(this, function (_e) {
switch (_e.label) {
case 0:
_a = new SsdMobilenetv1Options(options), maxResults = _a.maxResults, minConfidence = _a.minConfidence;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _e.sent();
_b = this.forwardInput(netInput), _boxes = _b.boxes, _scores = _b.scores;
boxes = _boxes[0];
scores = _scores[0];
for (i = 1; i < _boxes.length; i++) {
_boxes[i].dispose();
_scores[i].dispose();
}
_d = (_c = Array).from;
return [4 /*yield*/, scores.data()];
case 2:
scoresData = _d.apply(_c, [_e.sent()]);
iouThreshold = 0.5;
indices = ssdMobilenetv1_nonMaxSuppression_nonMaxSuppression(boxes, scoresData, maxResults, iouThreshold, minConfidence);
reshapedDims = netInput.getReshapedInputDimensions(0);
inputSize = netInput.inputSize;
padX = inputSize / reshapedDims.width;
padY = inputSize / reshapedDims.height;
boxesData = boxes.arraySync();
results = indices
.map(function (idx) {
var _a = [
Math.max(0, boxesData[idx][0]),
Math.min(1.0, boxesData[idx][2])
].map(function (val) { return val * padY; }), top = _a[0], bottom = _a[1];
var _b = [
Math.max(0, boxesData[idx][1]),
Math.min(1.0, boxesData[idx][3])
].map(function (val) { return val * padX; }), left = _b[0], right = _b[1];
return new FaceDetection_FaceDetection(scoresData[idx], new Rect_Rect(left, top, right - left, bottom - top), {
height: netInput.getInputHeight(0),
width: netInput.getInputWidth(0)
});
});
boxes.dispose();
scores.dispose();
return [2 /*return*/, results];
}
});
});
};
SsdMobilenetv1.prototype.getDefaultModelName = function () {
return 'ssd_mobilenetv1_model';
};
SsdMobilenetv1.prototype.extractParamsFromWeigthMap = function (weightMap) {
return ssdMobilenetv1_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap);
};
SsdMobilenetv1.prototype.extractParams = function (weights) {
return ssdMobilenetv1_extractParams_extractParams(weights);
};
return SsdMobilenetv1;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=SsdMobilenetv1.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/ssdMobilenetv1/index.js
function ssdMobilenetv1_createSsdMobilenetv1(weights) {
var net = new SsdMobilenetv1_SsdMobilenetv1();
net.extractWeights(weights);
return net;
}
function ssdMobilenetv1_createFaceDetectionNet(weights) {
return ssdMobilenetv1_createSsdMobilenetv1(weights);
}
// alias for backward compatibily
var ssdMobilenetv1_FaceDetectionNet = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(FaceDetectionNet, _super);
function FaceDetectionNet() {
return _super !== null && _super.apply(this, arguments) || this;
}
return FaceDetectionNet;
}(SsdMobilenetv1_SsdMobilenetv1));
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/const.js
var const_IOU_THRESHOLD = 0.4;
var const_BOX_ANCHORS = [
new Point(0.738768, 0.874946),
new Point(2.42204, 2.65704),
new Point(4.30971, 7.04493),
new Point(10.246, 4.59428),
new Point(12.6868, 11.8741)
];
var const_BOX_ANCHORS_SEPARABLE = [
new Point(1.603231, 2.094468),
new Point(6.041143, 7.080126),
new Point(2.882459, 3.518061),
new Point(4.266906, 5.178857),
new Point(9.041765, 10.66308)
];
var const_MEAN_RGB_SEPARABLE = [117.001, 114.697, 97.404];
var const_DEFAULT_MODEL_NAME = 'tiny_yolov2_model';
var const_DEFAULT_MODEL_NAME_SEPARABLE_CONV = 'tiny_yolov2_separable_conv_model';
//# sourceMappingURL=const.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/config.js
var isNumber = function (arg) { return typeof arg === 'number'; };
function validateConfig(config) {
if (!config) {
throw new Error("invalid config: " + config);
}
if (typeof config.withSeparableConvs !== 'boolean') {
throw new Error("config.withSeparableConvs has to be a boolean, have: " + config.withSeparableConvs);
}
if (!isNumber(config.iouThreshold) || config.iouThreshold < 0 || config.iouThreshold > 1.0) {
throw new Error("config.iouThreshold has to be a number between [0, 1], have: " + config.iouThreshold);
}
if (!Array.isArray(config.classes)
|| !config.classes.length
|| !config.classes.every(function (c) { return typeof c === 'string'; })) {
throw new Error("config.classes has to be an array class names: string[], have: " + JSON.stringify(config.classes));
}
if (!Array.isArray(config.anchors)
|| !config.anchors.length
|| !config.anchors.map(function (a) { return a || {}; }).every(function (a) { return isNumber(a.x) && isNumber(a.y); })) {
throw new Error("config.anchors has to be an array of { x: number, y: number }, have: " + JSON.stringify(config.anchors));
}
if (config.meanRgb && (!Array.isArray(config.meanRgb)
|| config.meanRgb.length !== 3
|| !config.meanRgb.every(isNumber))) {
throw new Error("config.meanRgb has to be an array of shape [number, number, number], have: " + JSON.stringify(config.meanRgb));
}
}
//# sourceMappingURL=config.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/leaky.js
function leaky_leaky(x) {
return tf_core_esm["tidy"](function () {
var min = tf_core_esm["mul"](x, tf_core_esm["scalar"](0.10000000149011612));
return tf_core_esm["add"](tf_core_esm["relu"](tf_core_esm["sub"](x, min)), min);
//return tf.maximum(x, min)
});
}
//# sourceMappingURL=leaky.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/convWithBatchNorm.js
function convWithBatchNorm_convWithBatchNorm(x, params) {
return tf_core_esm["tidy"](function () {
var out = tf_core_esm["pad"](x, [[0, 0], [1, 1], [1, 1], [0, 0]]);
out = tf_core_esm["conv2d"](out, params.conv.filters, [1, 1], 'valid');
out = tf_core_esm["sub"](out, params.bn.sub);
out = tf_core_esm["mul"](out, params.bn.truediv);
out = tf_core_esm["add"](out, params.conv.bias);
return leaky_leaky(out);
});
}
//# sourceMappingURL=convWithBatchNorm.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/depthwiseSeparableConv.js
function tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(x, params) {
return tf_core_esm["tidy"](function () {
var out = tf_core_esm["pad"](x, [[0, 0], [1, 1], [1, 1], [0, 0]]);
out = tf_core_esm["separableConv2d"](out, params.depthwise_filter, params.pointwise_filter, [1, 1], 'valid');
out = tf_core_esm["add"](out, params.bias);
return leaky_leaky(out);
});
}
//# sourceMappingURL=depthwiseSeparableConv.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/extractParams.js
function tinyYolov2_extractParams_extractorsFactory(extractWeights, paramMappings) {
var extractConvParams = extractConvParamsFactory_extractConvParamsFactory(extractWeights, paramMappings);
function extractBatchNormParams(size, mappedPrefix) {
var sub = tf_core_esm["tensor1d"](extractWeights(size));
var truediv = tf_core_esm["tensor1d"](extractWeights(size));
paramMappings.push({ paramPath: mappedPrefix + "/sub" }, { paramPath: mappedPrefix + "/truediv" });
return { sub: sub, truediv: truediv };
}
function extractConvWithBatchNormParams(channelsIn, channelsOut, mappedPrefix) {
var conv = extractConvParams(channelsIn, channelsOut, 3, mappedPrefix + "/conv");
var bn = extractBatchNormParams(channelsOut, mappedPrefix + "/bn");
return { conv: conv, bn: bn };
}
var extractSeparableConvParams = extractSeparableConvParamsFactory_extractSeparableConvParamsFactory(extractWeights, paramMappings);
return {
extractConvParams: extractConvParams,
extractConvWithBatchNormParams: extractConvWithBatchNormParams,
extractSeparableConvParams: extractSeparableConvParams
};
}
function tinyYolov2_extractParams_extractParams(weights, config, boxEncodingSize, filterSizes) {
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var paramMappings = [];
var _b = tinyYolov2_extractParams_extractorsFactory(extractWeights, paramMappings), extractConvParams = _b.extractConvParams, extractConvWithBatchNormParams = _b.extractConvWithBatchNormParams, extractSeparableConvParams = _b.extractSeparableConvParams;
var params;
if (config.withSeparableConvs) {
var s0 = filterSizes[0], s1 = filterSizes[1], s2 = filterSizes[2], s3 = filterSizes[3], s4 = filterSizes[4], s5 = filterSizes[5], s6 = filterSizes[6], s7 = filterSizes[7], s8 = filterSizes[8];
var conv0 = config.isFirstLayerConv2d
? extractConvParams(s0, s1, 3, 'conv0')
: extractSeparableConvParams(s0, s1, 'conv0');
var conv1 = extractSeparableConvParams(s1, s2, 'conv1');
var conv2 = extractSeparableConvParams(s2, s3, 'conv2');
var conv3 = extractSeparableConvParams(s3, s4, 'conv3');
var conv4 = extractSeparableConvParams(s4, s5, 'conv4');
var conv5 = extractSeparableConvParams(s5, s6, 'conv5');
var conv6 = s7 ? extractSeparableConvParams(s6, s7, 'conv6') : undefined;
var conv7 = s8 ? extractSeparableConvParams(s7, s8, 'conv7') : undefined;
var conv8 = extractConvParams(s8 || s7 || s6, 5 * boxEncodingSize, 1, 'conv8');
params = { conv0: conv0, conv1: conv1, conv2: conv2, conv3: conv3, conv4: conv4, conv5: conv5, conv6: conv6, conv7: conv7, conv8: conv8 };
}
else {
var s0 = filterSizes[0], s1 = filterSizes[1], s2 = filterSizes[2], s3 = filterSizes[3], s4 = filterSizes[4], s5 = filterSizes[5], s6 = filterSizes[6], s7 = filterSizes[7], s8 = filterSizes[8];
var conv0 = extractConvWithBatchNormParams(s0, s1, 'conv0');
var conv1 = extractConvWithBatchNormParams(s1, s2, 'conv1');
var conv2 = extractConvWithBatchNormParams(s2, s3, 'conv2');
var conv3 = extractConvWithBatchNormParams(s3, s4, 'conv3');
var conv4 = extractConvWithBatchNormParams(s4, s5, 'conv4');
var conv5 = extractConvWithBatchNormParams(s5, s6, 'conv5');
var conv6 = extractConvWithBatchNormParams(s6, s7, 'conv6');
var conv7 = extractConvWithBatchNormParams(s7, s8, 'conv7');
var conv8 = extractConvParams(s8, 5 * boxEncodingSize, 1, 'conv8');
params = { conv0: conv0, conv1: conv1, conv2: conv2, conv3: conv3, conv4: conv4, conv5: conv5, conv6: conv6, conv7: conv7, conv8: conv8 };
}
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/extractParamsFromWeigthMap.js
function tinyYolov2_extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings) {
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
function extractBatchNormParams(prefix) {
var sub = extractWeightEntry(prefix + "/sub", 1);
var truediv = extractWeightEntry(prefix + "/truediv", 1);
return { sub: sub, truediv: truediv };
}
function extractConvParams(prefix) {
var filters = extractWeightEntry(prefix + "/filters", 4);
var bias = extractWeightEntry(prefix + "/bias", 1);
return { filters: filters, bias: bias };
}
function extractConvWithBatchNormParams(prefix) {
var conv = extractConvParams(prefix + "/conv");
var bn = extractBatchNormParams(prefix + "/bn");
return { conv: conv, bn: bn };
}
var extractSeparableConvParams = extractSeparableConvParamsFactory_loadSeparableConvParamsFactory(extractWeightEntry);
return {
extractConvParams: extractConvParams,
extractConvWithBatchNormParams: extractConvWithBatchNormParams,
extractSeparableConvParams: extractSeparableConvParams
};
}
function tinyYolov2_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap, config) {
var paramMappings = [];
var _a = tinyYolov2_extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings), extractConvParams = _a.extractConvParams, extractConvWithBatchNormParams = _a.extractConvWithBatchNormParams, extractSeparableConvParams = _a.extractSeparableConvParams;
var params;
if (config.withSeparableConvs) {
var numFilters = (config.filterSizes && config.filterSizes.length || 9);
params = {
conv0: config.isFirstLayerConv2d ? extractConvParams('conv0') : extractSeparableConvParams('conv0'),
conv1: extractSeparableConvParams('conv1'),
conv2: extractSeparableConvParams('conv2'),
conv3: extractSeparableConvParams('conv3'),
conv4: extractSeparableConvParams('conv4'),
conv5: extractSeparableConvParams('conv5'),
conv6: numFilters > 7 ? extractSeparableConvParams('conv6') : undefined,
conv7: numFilters > 8 ? extractSeparableConvParams('conv7') : undefined,
conv8: extractConvParams('conv8')
};
}
else {
params = {
conv0: extractConvWithBatchNormParams('conv0'),
conv1: extractConvWithBatchNormParams('conv1'),
conv2: extractConvWithBatchNormParams('conv2'),
conv3: extractConvWithBatchNormParams('conv3'),
conv4: extractConvWithBatchNormParams('conv4'),
conv5: extractConvWithBatchNormParams('conv5'),
conv6: extractConvWithBatchNormParams('conv6'),
conv7: extractConvWithBatchNormParams('conv7'),
conv8: extractConvParams('conv8')
};
}
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: params, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/TinyYolov2Options.js
var TinyYolov2SizeType;
(function (TinyYolov2SizeType) {
TinyYolov2SizeType[TinyYolov2SizeType["XS"] = 224] = "XS";
TinyYolov2SizeType[TinyYolov2SizeType["SM"] = 320] = "SM";
TinyYolov2SizeType[TinyYolov2SizeType["MD"] = 416] = "MD";
TinyYolov2SizeType[TinyYolov2SizeType["LG"] = 608] = "LG";
})(TinyYolov2SizeType || (TinyYolov2SizeType = {}));
var TinyYolov2Options = /** @class */ (function () {
function TinyYolov2Options(_a) {
var _b = _a === void 0 ? {} : _a, inputSize = _b.inputSize, scoreThreshold = _b.scoreThreshold;
this._name = 'TinyYolov2Options';
this._inputSize = inputSize || 416;
this._scoreThreshold = scoreThreshold || 0.5;
if (typeof this._inputSize !== 'number' || this._inputSize % 32 !== 0) {
throw new Error(this._name + " - expected inputSize to be a number divisible by 32");
}
if (typeof this._scoreThreshold !== 'number' || this._scoreThreshold <= 0 || this._scoreThreshold >= 1) {
throw new Error(this._name + " - expected scoreThreshold to be a number between 0 and 1");
}
}
Object.defineProperty(TinyYolov2Options.prototype, "inputSize", {
get: function () { return this._inputSize; },
enumerable: true,
configurable: true
});
Object.defineProperty(TinyYolov2Options.prototype, "scoreThreshold", {
get: function () { return this._scoreThreshold; },
enumerable: true,
configurable: true
});
return TinyYolov2Options;
}());
//# sourceMappingURL=TinyYolov2Options.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/TinyYolov2Base.js
var TinyYolov2Base_TinyYolov2Base = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(TinyYolov2Base, _super);
function TinyYolov2Base(config) {
var _this = _super.call(this, 'TinyYolov2') || this;
validateConfig(config);
_this._config = config;
return _this;
}
Object.defineProperty(TinyYolov2Base.prototype, "config", {
get: function () {
return this._config;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TinyYolov2Base.prototype, "withClassScores", {
get: function () {
return this.config.withClassScores || this.config.classes.length > 1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TinyYolov2Base.prototype, "boxEncodingSize", {
get: function () {
return 5 + (this.withClassScores ? this.config.classes.length : 0);
},
enumerable: true,
configurable: true
});
TinyYolov2Base.prototype.runTinyYolov2 = function (x, params) {
var out = convWithBatchNorm_convWithBatchNorm(x, params.conv0);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = convWithBatchNorm_convWithBatchNorm(out, params.conv1);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = convWithBatchNorm_convWithBatchNorm(out, params.conv2);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = convWithBatchNorm_convWithBatchNorm(out, params.conv3);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = convWithBatchNorm_convWithBatchNorm(out, params.conv4);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = convWithBatchNorm_convWithBatchNorm(out, params.conv5);
out = tf_core_esm["maxPool"](out, [2, 2], [1, 1], 'same');
out = convWithBatchNorm_convWithBatchNorm(out, params.conv6);
out = convWithBatchNorm_convWithBatchNorm(out, params.conv7);
return convLayer_convLayer(out, params.conv8, 'valid', false);
};
TinyYolov2Base.prototype.runMobilenet = function (x, params) {
var out = this.config.isFirstLayerConv2d
? leaky_leaky(convLayer_convLayer(x, params.conv0, 'valid', false))
: tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(x, params.conv0);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv1);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv2);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv3);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv4);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv5);
out = tf_core_esm["maxPool"](out, [2, 2], [1, 1], 'same');
out = params.conv6 ? tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv6) : out;
out = params.conv7 ? tinyYolov2_depthwiseSeparableConv_depthwiseSeparableConv(out, params.conv7) : out;
return convLayer_convLayer(out, params.conv8, 'valid', false);
};
TinyYolov2Base.prototype.forwardInput = function (input, inputSize) {
var _this = this;
var params = this.params;
if (!params) {
throw new Error('TinyYolov2 - load model before inference');
}
return tf_core_esm["tidy"](function () {
var batchTensor = input.toBatchTensor(inputSize, false).toFloat();
batchTensor = _this.config.meanRgb
? normalize_normalize(batchTensor, _this.config.meanRgb)
: batchTensor;
batchTensor = batchTensor.div(tf_core_esm["scalar"](256));
return _this.config.withSeparableConvs
? _this.runMobilenet(batchTensor, params)
: _this.runTinyYolov2(batchTensor, params);
});
};
TinyYolov2Base.prototype.forward = function (input, inputSize) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [4 /*yield*/, _a.apply(this, [_b.sent(), inputSize])];
case 2: return [2 /*return*/, _b.sent()];
}
});
});
};
TinyYolov2Base.prototype.detect = function (input, forwardParams) {
if (forwardParams === void 0) { forwardParams = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a, inputSize, scoreThreshold, netInput, out, out0, inputDimensions, results, boxes, scores, classScores, classNames, indices, detections;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = new TinyYolov2Options(forwardParams), inputSize = _a.inputSize, scoreThreshold = _a.scoreThreshold;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1:
netInput = _b.sent();
return [4 /*yield*/, this.forwardInput(netInput, inputSize)];
case 2:
out = _b.sent();
out0 = tf_core_esm["tidy"](function () { return tf_core_esm["unstack"](out)[0].expandDims(); });
inputDimensions = {
width: netInput.getInputWidth(0),
height: netInput.getInputHeight(0)
};
return [4 /*yield*/, this.extractBoxes(out0, netInput.getReshapedInputDimensions(0), scoreThreshold)];
case 3:
results = _b.sent();
out.dispose();
out0.dispose();
boxes = results.map(function (res) { return res.box; });
scores = results.map(function (res) { return res.score; });
classScores = results.map(function (res) { return res.classScore; });
classNames = results.map(function (res) { return _this.config.classes[res.label]; });
indices = nonMaxSuppression_nonMaxSuppression(boxes.map(function (box) { return box.rescale(inputSize); }), scores, this.config.iouThreshold, true);
detections = indices.map(function (idx) {
return new ObjectDetection_ObjectDetection(scores[idx], classScores[idx], classNames[idx], boxes[idx], inputDimensions);
});
return [2 /*return*/, detections];
}
});
});
};
TinyYolov2Base.prototype.getDefaultModelName = function () {
return '';
};
TinyYolov2Base.prototype.extractParamsFromWeigthMap = function (weightMap) {
return tinyYolov2_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap, this.config);
};
TinyYolov2Base.prototype.extractParams = function (weights) {
var filterSizes = this.config.filterSizes || TinyYolov2Base.DEFAULT_FILTER_SIZES;
var numFilters = filterSizes ? filterSizes.length : undefined;
if (numFilters !== 7 && numFilters !== 8 && numFilters !== 9) {
throw new Error("TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found " + numFilters + " filterSizes in config");
}
return tinyYolov2_extractParams_extractParams(weights, this.config, this.boxEncodingSize, filterSizes);
};
TinyYolov2Base.prototype.extractBoxes = function (outputTensor, inputBlobDimensions, scoreThreshold) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var width, height, inputSize, correctionFactorX, correctionFactorY, numCells, numBoxes, _a, boxesTensor, scoresTensor, classScoresTensor, results, scoresData, boxesData, row, col, anchor, score, ctX, ctY, width_1, height_1, x, y, pos, _b, classScore, label, _c;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_d) {
switch (_d.label) {
case 0:
width = inputBlobDimensions.width, height = inputBlobDimensions.height;
inputSize = Math.max(width, height);
correctionFactorX = inputSize / width;
correctionFactorY = inputSize / height;
numCells = outputTensor.shape[1];
numBoxes = this.config.anchors.length;
_a = tf_core_esm["tidy"](function () {
var reshaped = outputTensor.reshape([numCells, numCells, numBoxes, _this.boxEncodingSize]);
var boxes = reshaped.slice([0, 0, 0, 0], [numCells, numCells, numBoxes, 4]);
var scores = reshaped.slice([0, 0, 0, 4], [numCells, numCells, numBoxes, 1]);
var classScores = _this.withClassScores
? tf_core_esm["softmax"](reshaped.slice([0, 0, 0, 5], [numCells, numCells, numBoxes, _this.config.classes.length]), 3)
: tf_core_esm["scalar"](0);
return [boxes, scores, classScores];
}), boxesTensor = _a[0], scoresTensor = _a[1], classScoresTensor = _a[2];
results = [];
return [4 /*yield*/, scoresTensor.array()];
case 1:
scoresData = _d.sent();
return [4 /*yield*/, boxesTensor.array()];
case 2:
boxesData = _d.sent();
row = 0;
_d.label = 3;
case 3:
if (!(row < numCells)) return [3 /*break*/, 12];
col = 0;
_d.label = 4;
case 4:
if (!(col < numCells)) return [3 /*break*/, 11];
anchor = 0;
_d.label = 5;
case 5:
if (!(anchor < numBoxes)) return [3 /*break*/, 10];
score = sigmoid(scoresData[row][col][anchor][0]);
if (!(!scoreThreshold || score > scoreThreshold)) return [3 /*break*/, 9];
ctX = ((col + sigmoid(boxesData[row][col][anchor][0])) / numCells) * correctionFactorX;
ctY = ((row + sigmoid(boxesData[row][col][anchor][1])) / numCells) * correctionFactorY;
width_1 = ((Math.exp(boxesData[row][col][anchor][2]) * this.config.anchors[anchor].x) / numCells) * correctionFactorX;
height_1 = ((Math.exp(boxesData[row][col][anchor][3]) * this.config.anchors[anchor].y) / numCells) * correctionFactorY;
x = (ctX - (width_1 / 2));
y = (ctY - (height_1 / 2));
pos = { row: row, col: col, anchor: anchor };
if (!this.withClassScores) return [3 /*break*/, 7];
return [4 /*yield*/, this.extractPredictedClass(classScoresTensor, pos)];
case 6:
_c = _d.sent();
return [3 /*break*/, 8];
case 7:
_c = { classScore: 1, label: 0 };
_d.label = 8;
case 8:
_b = _c, classScore = _b.classScore, label = _b.label;
results.push(Object(tslib_es6["a" /* __assign */])({ box: new BoundingBox_BoundingBox(x, y, x + width_1, y + height_1), score: score, classScore: score * classScore, label: label }, pos));
_d.label = 9;
case 9:
anchor++;
return [3 /*break*/, 5];
case 10:
col++;
return [3 /*break*/, 4];
case 11:
row++;
return [3 /*break*/, 3];
case 12:
boxesTensor.dispose();
scoresTensor.dispose();
classScoresTensor.dispose();
return [2 /*return*/, results];
}
});
});
};
TinyYolov2Base.prototype.extractPredictedClass = function (classesTensor, pos) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var row, col, anchor, classesData;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
row = pos.row, col = pos.col, anchor = pos.anchor;
return [4 /*yield*/, classesTensor.array()];
case 1:
classesData = _a.sent();
return [2 /*return*/, Array(this.config.classes.length).fill(0)
.map(function (_, i) { return classesData[row][col][anchor][i]; })
.map(function (classScore, label) { return ({
classScore: classScore,
label: label
}); })
.reduce(function (max, curr) { return max.classScore > curr.classScore ? max : curr; })];
}
});
});
};
TinyYolov2Base.DEFAULT_FILTER_SIZES = [
3, 16, 32, 64, 128, 256, 512, 1024, 1024
];
return TinyYolov2Base;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=TinyYolov2Base.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/TinyYolov2.js
var TinyYolov2_TinyYolov2 = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(TinyYolov2, _super);
function TinyYolov2(withSeparableConvs) {
if (withSeparableConvs === void 0) { withSeparableConvs = true; }
var _this = this;
var config = Object.assign({}, {
withSeparableConvs: withSeparableConvs,
iouThreshold: const_IOU_THRESHOLD,
classes: ['face']
}, withSeparableConvs
? {
anchors: const_BOX_ANCHORS_SEPARABLE,
meanRgb: const_MEAN_RGB_SEPARABLE
}
: {
anchors: const_BOX_ANCHORS,
withClassScores: true
});
_this = _super.call(this, config) || this;
return _this;
}
Object.defineProperty(TinyYolov2.prototype, "withSeparableConvs", {
get: function () {
return this.config.withSeparableConvs;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TinyYolov2.prototype, "anchors", {
get: function () {
return this.config.anchors;
},
enumerable: true,
configurable: true
});
TinyYolov2.prototype.locateFaces = function (input, forwardParams) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var objectDetections;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.detect(input, forwardParams)];
case 1:
objectDetections = _a.sent();
return [2 /*return*/, objectDetections.map(function (det) { return new FaceDetection_FaceDetection(det.score, det.relativeBox, { width: det.imageWidth, height: det.imageHeight }); })];
}
});
});
};
TinyYolov2.prototype.getDefaultModelName = function () {
return this.withSeparableConvs ? const_DEFAULT_MODEL_NAME_SEPARABLE_CONV : const_DEFAULT_MODEL_NAME;
};
TinyYolov2.prototype.extractParamsFromWeigthMap = function (weightMap) {
return _super.prototype.extractParamsFromWeigthMap.call(this, weightMap);
};
return TinyYolov2;
}(TinyYolov2Base_TinyYolov2Base));
//# sourceMappingURL=TinyYolov2.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyYolov2/index.js
function tinyYolov2_createTinyYolov2(weights, withSeparableConvs) {
if (withSeparableConvs === void 0) { withSeparableConvs = true; }
var net = new TinyYolov2_TinyYolov2(withSeparableConvs);
net.extractWeights(weights);
return net;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyFaceDetector/TinyFaceDetectorOptions.js
var TinyFaceDetectorOptions_TinyFaceDetectorOptions = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(TinyFaceDetectorOptions, _super);
function TinyFaceDetectorOptions() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._name = 'TinyFaceDetectorOptions';
return _this;
}
return TinyFaceDetectorOptions;
}(TinyYolov2Options));
//# sourceMappingURL=TinyFaceDetectorOptions.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/ComposableTask.js
var ComposableTask_ComposableTask = /** @class */ (function () {
function ComposableTask() {
}
ComposableTask.prototype.then = function (onfulfilled) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = onfulfilled;
return [4 /*yield*/, this.run()];
case 1: return [2 /*return*/, _a.apply(void 0, [_b.sent()])];
}
});
});
};
ComposableTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
throw new Error('ComposableTask - run is not implemented');
});
});
};
return ComposableTask;
}());
//# sourceMappingURL=ComposableTask.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/extractFacesAndComputeResults.js
function extractFacesAndComputeResults_extractAllFacesAndComputeResults(parentResults, input, computeResults, extractedFaces, getRectForAlignment) {
if (getRectForAlignment === void 0) { getRectForAlignment = function (_a) {
var alignedRect = _a.alignedRect;
return alignedRect;
}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var faceBoxes, faces, _a, _b, results;
return Object(tslib_es6["d" /* __generator */])(this, function (_c) {
switch (_c.label) {
case 0:
faceBoxes = parentResults.map(function (parentResult) {
return WithFaceLandmarks_isWithFaceLandmarks(parentResult)
? getRectForAlignment(parentResult)
: parentResult.detection;
});
_a = extractedFaces;
if (_a) return [3 /*break*/, 5];
if (!(input instanceof tf_core_esm["Tensor"])) return [3 /*break*/, 2];
return [4 /*yield*/, extractFaceTensors_extractFaceTensors(input, faceBoxes)];
case 1:
_b = _c.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, extractFaces_extractFaces(input, faceBoxes)];
case 3:
_b = _c.sent();
_c.label = 4;
case 4:
_a = (_b);
_c.label = 5;
case 5:
faces = _a;
return [4 /*yield*/, computeResults(faces)];
case 6:
results = _c.sent();
faces.forEach(function (f) { return f instanceof tf_core_esm["Tensor"] && f.dispose(); });
return [2 /*return*/, results];
}
});
});
}
function extractFacesAndComputeResults_extractSingleFaceAndComputeResult(parentResult, input, computeResult, extractedFaces, getRectForAlignment) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
return [2 /*return*/, extractFacesAndComputeResults_extractAllFacesAndComputeResults([parentResult], input, function (faces) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () { return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
return [2 /*return*/, computeResult(faces[0])];
}); }); }, extractedFaces, getRectForAlignment)];
});
});
}
//# sourceMappingURL=extractFacesAndComputeResults.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/bgrToRgbTensor.js
function bgrToRgbTensor_bgrToRgbTensor(tensor) {
return tf_core_esm["tidy"](function () { return tf_core_esm["stack"](tf_core_esm["unstack"](tensor, 3).reverse(), 3); });
}
//# sourceMappingURL=bgrToRgbTensor.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/config.js
var CELL_STRIDE = 2;
var CELL_SIZE = 12;
//# sourceMappingURL=config.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/extractParams.js
function mtcnn_extractParams_extractorsFactory(extractWeights, paramMappings) {
var extractConvParams = extractConvParamsFactory_extractConvParamsFactory(extractWeights, paramMappings);
var extractFCParams = extractFCParamsFactory_extractFCParamsFactory(extractWeights, paramMappings);
function extractPReluParams(size, paramPath) {
var alpha = tf_core_esm["tensor1d"](extractWeights(size));
paramMappings.push({ paramPath: paramPath });
return alpha;
}
function extractSharedParams(numFilters, mappedPrefix, isRnet) {
if (isRnet === void 0) { isRnet = false; }
var conv1 = extractConvParams(numFilters[0], numFilters[1], 3, mappedPrefix + "/conv1");
var prelu1_alpha = extractPReluParams(numFilters[1], mappedPrefix + "/prelu1_alpha");
var conv2 = extractConvParams(numFilters[1], numFilters[2], 3, mappedPrefix + "/conv2");
var prelu2_alpha = extractPReluParams(numFilters[2], mappedPrefix + "/prelu2_alpha");
var conv3 = extractConvParams(numFilters[2], numFilters[3], isRnet ? 2 : 3, mappedPrefix + "/conv3");
var prelu3_alpha = extractPReluParams(numFilters[3], mappedPrefix + "/prelu3_alpha");
return { conv1: conv1, prelu1_alpha: prelu1_alpha, conv2: conv2, prelu2_alpha: prelu2_alpha, conv3: conv3, prelu3_alpha: prelu3_alpha };
}
function extractPNetParams() {
var sharedParams = extractSharedParams([3, 10, 16, 32], 'pnet');
var conv4_1 = extractConvParams(32, 2, 1, 'pnet/conv4_1');
var conv4_2 = extractConvParams(32, 4, 1, 'pnet/conv4_2');
return Object(tslib_es6["a" /* __assign */])(Object(tslib_es6["a" /* __assign */])({}, sharedParams), { conv4_1: conv4_1, conv4_2: conv4_2 });
}
function extractRNetParams() {
var sharedParams = extractSharedParams([3, 28, 48, 64], 'rnet', true);
var fc1 = extractFCParams(576, 128, 'rnet/fc1');
var prelu4_alpha = extractPReluParams(128, 'rnet/prelu4_alpha');
var fc2_1 = extractFCParams(128, 2, 'rnet/fc2_1');
var fc2_2 = extractFCParams(128, 4, 'rnet/fc2_2');
return Object(tslib_es6["a" /* __assign */])(Object(tslib_es6["a" /* __assign */])({}, sharedParams), { fc1: fc1, prelu4_alpha: prelu4_alpha, fc2_1: fc2_1, fc2_2: fc2_2 });
}
function extractONetParams() {
var sharedParams = extractSharedParams([3, 32, 64, 64], 'onet');
var conv4 = extractConvParams(64, 128, 2, 'onet/conv4');
var prelu4_alpha = extractPReluParams(128, 'onet/prelu4_alpha');
var fc1 = extractFCParams(1152, 256, 'onet/fc1');
var prelu5_alpha = extractPReluParams(256, 'onet/prelu5_alpha');
var fc2_1 = extractFCParams(256, 2, 'onet/fc2_1');
var fc2_2 = extractFCParams(256, 4, 'onet/fc2_2');
var fc2_3 = extractFCParams(256, 10, 'onet/fc2_3');
return Object(tslib_es6["a" /* __assign */])(Object(tslib_es6["a" /* __assign */])({}, sharedParams), { conv4: conv4, prelu4_alpha: prelu4_alpha, fc1: fc1, prelu5_alpha: prelu5_alpha, fc2_1: fc2_1, fc2_2: fc2_2, fc2_3: fc2_3 });
}
return {
extractPNetParams: extractPNetParams,
extractRNetParams: extractRNetParams,
extractONetParams: extractONetParams
};
}
function mtcnn_extractParams_extractParams(weights) {
var _a = extractWeightsFactory(weights), extractWeights = _a.extractWeights, getRemainingWeights = _a.getRemainingWeights;
var paramMappings = [];
var _b = mtcnn_extractParams_extractorsFactory(extractWeights, paramMappings), extractPNetParams = _b.extractPNetParams, extractRNetParams = _b.extractRNetParams, extractONetParams = _b.extractONetParams;
var pnet = extractPNetParams();
var rnet = extractRNetParams();
var onet = extractONetParams();
if (getRemainingWeights().length !== 0) {
throw new Error("weights remaing after extract: " + getRemainingWeights().length);
}
return { params: { pnet: pnet, rnet: rnet, onet: onet }, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParams.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/extractParamsFromWeigthMap.js
function mtcnn_extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings) {
var extractWeightEntry = extractWeightEntryFactory_extractWeightEntryFactory(weightMap, paramMappings);
function extractConvParams(prefix) {
var filters = extractWeightEntry(prefix + "/weights", 4, prefix + "/filters");
var bias = extractWeightEntry(prefix + "/bias", 1);
return { filters: filters, bias: bias };
}
function extractFCParams(prefix) {
var weights = extractWeightEntry(prefix + "/weights", 2);
var bias = extractWeightEntry(prefix + "/bias", 1);
return { weights: weights, bias: bias };
}
function extractPReluParams(paramPath) {
return extractWeightEntry(paramPath, 1);
}
function extractSharedParams(prefix) {
var conv1 = extractConvParams(prefix + "/conv1");
var prelu1_alpha = extractPReluParams(prefix + "/prelu1_alpha");
var conv2 = extractConvParams(prefix + "/conv2");
var prelu2_alpha = extractPReluParams(prefix + "/prelu2_alpha");
var conv3 = extractConvParams(prefix + "/conv3");
var prelu3_alpha = extractPReluParams(prefix + "/prelu3_alpha");
return { conv1: conv1, prelu1_alpha: prelu1_alpha, conv2: conv2, prelu2_alpha: prelu2_alpha, conv3: conv3, prelu3_alpha: prelu3_alpha };
}
function extractPNetParams() {
var sharedParams = extractSharedParams('pnet');
var conv4_1 = extractConvParams('pnet/conv4_1');
var conv4_2 = extractConvParams('pnet/conv4_2');
return Object(tslib_es6["a" /* __assign */])(Object(tslib_es6["a" /* __assign */])({}, sharedParams), { conv4_1: conv4_1, conv4_2: conv4_2 });
}
function extractRNetParams() {
var sharedParams = extractSharedParams('rnet');
var fc1 = extractFCParams('rnet/fc1');
var prelu4_alpha = extractPReluParams('rnet/prelu4_alpha');
var fc2_1 = extractFCParams('rnet/fc2_1');
var fc2_2 = extractFCParams('rnet/fc2_2');
return Object(tslib_es6["a" /* __assign */])(Object(tslib_es6["a" /* __assign */])({}, sharedParams), { fc1: fc1, prelu4_alpha: prelu4_alpha, fc2_1: fc2_1, fc2_2: fc2_2 });
}
function extractONetParams() {
var sharedParams = extractSharedParams('onet');
var conv4 = extractConvParams('onet/conv4');
var prelu4_alpha = extractPReluParams('onet/prelu4_alpha');
var fc1 = extractFCParams('onet/fc1');
var prelu5_alpha = extractPReluParams('onet/prelu5_alpha');
var fc2_1 = extractFCParams('onet/fc2_1');
var fc2_2 = extractFCParams('onet/fc2_2');
var fc2_3 = extractFCParams('onet/fc2_3');
return Object(tslib_es6["a" /* __assign */])(Object(tslib_es6["a" /* __assign */])({}, sharedParams), { conv4: conv4, prelu4_alpha: prelu4_alpha, fc1: fc1, prelu5_alpha: prelu5_alpha, fc2_1: fc2_1, fc2_2: fc2_2, fc2_3: fc2_3 });
}
return {
extractPNetParams: extractPNetParams,
extractRNetParams: extractRNetParams,
extractONetParams: extractONetParams
};
}
function mtcnn_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap) {
var paramMappings = [];
var _a = mtcnn_extractParamsFromWeigthMap_extractorsFactory(weightMap, paramMappings), extractPNetParams = _a.extractPNetParams, extractRNetParams = _a.extractRNetParams, extractONetParams = _a.extractONetParams;
var pnet = extractPNetParams();
var rnet = extractRNetParams();
var onet = extractONetParams();
disposeUnusedWeightTensors(weightMap, paramMappings);
return { params: { pnet: pnet, rnet: rnet, onet: onet }, paramMappings: paramMappings };
}
//# sourceMappingURL=extractParamsFromWeigthMap.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/getSizesForScale.js
function getSizesForScale(scale, _a) {
var height = _a[0], width = _a[1];
return {
height: Math.floor(height * scale),
width: Math.floor(width * scale)
};
}
//# sourceMappingURL=getSizesForScale.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/pyramidDown.js
function pyramidDown_pyramidDown(minFaceSize, scaleFactor, dims) {
var height = dims[0], width = dims[1];
var m = CELL_SIZE / minFaceSize;
var scales = [];
var minLayer = Math.min(height, width) * m;
var exp = 0;
while (minLayer >= 12) {
scales.push(m * Math.pow(scaleFactor, exp));
minLayer = minLayer * scaleFactor;
exp += 1;
}
return scales;
}
//# sourceMappingURL=pyramidDown.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/MtcnnBox.js
var MtcnnBox_MtcnnBox = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(MtcnnBox, _super);
function MtcnnBox(left, top, right, bottom) {
return _super.call(this, { left: left, top: top, right: right, bottom: bottom }, true) || this;
}
return MtcnnBox;
}(Box_Box));
//# sourceMappingURL=MtcnnBox.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/normalize.js
function mtcnn_normalize_normalize(x) {
return tf_core_esm["tidy"](function () { return tf_core_esm["mul"](tf_core_esm["sub"](x, tf_core_esm["scalar"](127.5)), tf_core_esm["scalar"](0.0078125)); });
}
//# sourceMappingURL=normalize.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/prelu.js
function prelu_prelu(x, alpha) {
return tf_core_esm["tidy"](function () {
return tf_core_esm["add"](tf_core_esm["relu"](x), tf_core_esm["mul"](alpha, tf_core_esm["neg"](tf_core_esm["relu"](tf_core_esm["neg"](x)))));
});
}
//# sourceMappingURL=prelu.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/sharedLayers.js
function sharedLayers_sharedLayer(x, params, isPnet) {
if (isPnet === void 0) { isPnet = false; }
return tf_core_esm["tidy"](function () {
var out = convLayer_convLayer(x, params.conv1, 'valid');
out = prelu_prelu(out, params.prelu1_alpha);
out = tf_core_esm["maxPool"](out, isPnet ? [2, 2] : [3, 3], [2, 2], 'same');
out = convLayer_convLayer(out, params.conv2, 'valid');
out = prelu_prelu(out, params.prelu2_alpha);
out = isPnet ? out : tf_core_esm["maxPool"](out, [3, 3], [2, 2], 'valid');
out = convLayer_convLayer(out, params.conv3, 'valid');
out = prelu_prelu(out, params.prelu3_alpha);
return out;
});
}
//# sourceMappingURL=sharedLayers.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/PNet.js
function PNet_PNet(x, params) {
return tf_core_esm["tidy"](function () {
var out = sharedLayers_sharedLayer(x, params, true);
var conv = convLayer_convLayer(out, params.conv4_1, 'valid');
var max = tf_core_esm["expandDims"](tf_core_esm["max"](conv, 3), 3);
var prob = tf_core_esm["softmax"](tf_core_esm["sub"](conv, max), 3);
var regions = convLayer_convLayer(out, params.conv4_2, 'valid');
return { prob: prob, regions: regions };
});
}
//# sourceMappingURL=PNet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/stage1.js
function stage1_rescaleAndNormalize(x, scale) {
return tf_core_esm["tidy"](function () {
var _a = getSizesForScale(scale, x.shape.slice(1)), height = _a.height, width = _a.width;
var resized = tf_core_esm["image"].resizeBilinear(x, [height, width]);
var normalized = mtcnn_normalize_normalize(resized);
return tf_core_esm["transpose"](normalized, [0, 2, 1, 3]);
});
}
function stage1_extractBoundingBoxes(scoresTensor, regionsTensor, scale, scoreThreshold) {
// TODO: fix this!, maybe better to use tf.gather here
var indices = [];
var scoresData = scoresTensor.arraySync();
for (var y = 0; y < scoresTensor.shape[0]; y++) {
for (var x = 0; x < scoresTensor.shape[1]; x++) {
if (scoresData[y][x] >= scoreThreshold) {
indices.push(new Point(x, y));
}
}
}
var boundingBoxes = indices.map(function (idx) {
var cell = new BoundingBox_BoundingBox(Math.round((idx.y * CELL_STRIDE + 1) / scale), Math.round((idx.x * CELL_STRIDE + 1) / scale), Math.round((idx.y * CELL_STRIDE + CELL_SIZE) / scale), Math.round((idx.x * CELL_STRIDE + CELL_SIZE) / scale));
var score = scoresData[idx.y][idx.x];
var regionsData = regionsTensor.arraySync();
var region = new MtcnnBox_MtcnnBox(regionsData[idx.y][idx.x][0], regionsData[idx.y][idx.x][1], regionsData[idx.y][idx.x][2], regionsData[idx.y][idx.x][3]);
return {
cell: cell,
score: score,
region: region
};
});
return boundingBoxes;
}
function stage1_stage1(imgTensor, scales, scoreThreshold, params, stats) {
stats.stage1 = [];
var pnetOutputs = scales.map(function (scale) { return tf_core_esm["tidy"](function () {
var statsForScale = { scale: scale };
var resized = stage1_rescaleAndNormalize(imgTensor, scale);
var ts = Date.now();
var _a = PNet_PNet(resized, params), prob = _a.prob, regions = _a.regions;
statsForScale.pnet = Date.now() - ts;
var scoresTensor = tf_core_esm["unstack"](tf_core_esm["unstack"](prob, 3)[1])[0];
var regionsTensor = tf_core_esm["unstack"](regions)[0];
return {
scoresTensor: scoresTensor,
regionsTensor: regionsTensor,
scale: scale,
statsForScale: statsForScale
};
}); });
var boxesForScale = pnetOutputs.map(function (_a) {
var scoresTensor = _a.scoresTensor, regionsTensor = _a.regionsTensor, scale = _a.scale, statsForScale = _a.statsForScale;
var boundingBoxes = stage1_extractBoundingBoxes(scoresTensor, regionsTensor, scale, scoreThreshold);
scoresTensor.dispose();
regionsTensor.dispose();
if (!boundingBoxes.length) {
stats.stage1.push(statsForScale);
return [];
}
var ts = Date.now();
var indices = nonMaxSuppression_nonMaxSuppression(boundingBoxes.map(function (bbox) { return bbox.cell; }), boundingBoxes.map(function (bbox) { return bbox.score; }), 0.5);
statsForScale.nms = Date.now() - ts;
statsForScale.numBoxes = indices.length;
stats.stage1.push(statsForScale);
return indices.map(function (boxIdx) { return boundingBoxes[boxIdx]; });
});
var allBoxes = boxesForScale.reduce(function (all, boxes) { return all.concat(boxes); }, []);
var finalBoxes = [];
var finalScores = [];
if (allBoxes.length > 0) {
var ts = Date.now();
var indices = nonMaxSuppression_nonMaxSuppression(allBoxes.map(function (bbox) { return bbox.cell; }), allBoxes.map(function (bbox) { return bbox.score; }), 0.7);
stats.stage1_nms = Date.now() - ts;
finalScores = indices.map(function (idx) { return allBoxes[idx].score; });
finalBoxes = indices
.map(function (idx) { return allBoxes[idx]; })
.map(function (_a) {
var cell = _a.cell, region = _a.region;
return new BoundingBox_BoundingBox(cell.left + (region.left * cell.width), cell.top + (region.top * cell.height), cell.right + (region.right * cell.width), cell.bottom + (region.bottom * cell.height)).toSquare().round();
});
}
return {
boxes: finalBoxes,
scores: finalScores
};
}
//# sourceMappingURL=stage1.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/extractImagePatches.js
function extractImagePatches_extractImagePatches(img, boxes, _a) {
var width = _a.width, height = _a.height;
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var imgCtx, bitmaps, imagePatchesDatas;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
imgCtx = getContext2dOrThrow_getContext2dOrThrow(img);
return [4 /*yield*/, Promise.all(boxes.map(function (box) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
var _a, y, ey, x, ex, fromX, fromY, imgData;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
_a = box.padAtBorders(img.height, img.width), y = _a.y, ey = _a.ey, x = _a.x, ex = _a.ex;
fromX = x - 1;
fromY = y - 1;
imgData = imgCtx.getImageData(fromX, fromY, (ex - fromX), (ey - fromY));
return [2 /*return*/, env_env.isNodejs() ? createCanvas_createCanvasFromMedia(imgData) : createImageBitmap(imgData)];
});
}); }))];
case 1:
bitmaps = _b.sent();
imagePatchesDatas = [];
bitmaps.forEach(function (bmp) {
var patch = createCanvas_createCanvas({ width: width, height: height });
var patchCtx = getContext2dOrThrow_getContext2dOrThrow(patch);
patchCtx.drawImage(bmp, 0, 0, width, height);
var data = patchCtx.getImageData(0, 0, width, height).data;
var currData = [];
// RGBA -> BGR
for (var i = 0; i < data.length; i += 4) {
currData.push(data[i + 2]);
currData.push(data[i + 1]);
currData.push(data[i]);
}
imagePatchesDatas.push(currData);
});
return [2 /*return*/, imagePatchesDatas.map(function (data) {
var t = tf_core_esm["tidy"](function () {
var imagePatchTensor = tf_core_esm["transpose"](tf_core_esm["tensor4d"](data, [1, width, height, 3]), [0, 2, 1, 3]).toFloat();
return mtcnn_normalize_normalize(imagePatchTensor);
});
return t;
})];
}
});
});
}
//# sourceMappingURL=extractImagePatches.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/RNet.js
function RNet_RNet(x, params) {
return tf_core_esm["tidy"](function () {
var convOut = sharedLayers_sharedLayer(x, params);
var vectorized = tf_core_esm["reshape"](convOut, [convOut.shape[0], params.fc1.weights.shape[0]]);
var fc1 = fullyConnectedLayer_fullyConnectedLayer(vectorized, params.fc1);
var prelu4 = prelu_prelu(fc1, params.prelu4_alpha);
var fc2_1 = fullyConnectedLayer_fullyConnectedLayer(prelu4, params.fc2_1);
var max = tf_core_esm["expandDims"](tf_core_esm["max"](fc2_1, 1), 1);
var prob = tf_core_esm["softmax"](tf_core_esm["sub"](fc2_1, max), 1);
var regions = fullyConnectedLayer_fullyConnectedLayer(prelu4, params.fc2_2);
var scores = tf_core_esm["unstack"](prob, 1)[1];
return { scores: scores, regions: regions };
});
}
//# sourceMappingURL=RNet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/stage2.js
function stage2_stage2(img, inputBoxes, scoreThreshold, params, stats) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var ts, rnetInputs, rnetOuts, scoresTensor, scores, _a, _b, indices, filteredBoxes, filteredScores, finalBoxes, finalScores, indicesNms, regions_1;
return Object(tslib_es6["d" /* __generator */])(this, function (_c) {
switch (_c.label) {
case 0:
ts = Date.now();
return [4 /*yield*/, extractImagePatches_extractImagePatches(img, inputBoxes, { width: 24, height: 24 })];
case 1:
rnetInputs = _c.sent();
stats.stage2_extractImagePatches = Date.now() - ts;
ts = Date.now();
rnetOuts = rnetInputs.map(function (rnetInput) {
var out = RNet_RNet(rnetInput, params);
rnetInput.dispose();
return out;
});
stats.stage2_rnet = Date.now() - ts;
scoresTensor = rnetOuts.length > 1
? tf_core_esm["concat"](rnetOuts.map(function (out) { return out.scores; }))
: rnetOuts[0].scores;
_b = (_a = Array).from;
return [4 /*yield*/, scoresTensor.data()];
case 2:
scores = _b.apply(_a, [_c.sent()]);
scoresTensor.dispose();
indices = scores
.map(function (score, idx) { return ({ score: score, idx: idx }); })
.filter(function (c) { return c.score > scoreThreshold; })
.map(function (_a) {
var idx = _a.idx;
return idx;
});
filteredBoxes = indices.map(function (idx) { return inputBoxes[idx]; });
filteredScores = indices.map(function (idx) { return scores[idx]; });
finalBoxes = [];
finalScores = [];
if (filteredBoxes.length > 0) {
ts = Date.now();
indicesNms = nonMaxSuppression_nonMaxSuppression(filteredBoxes, filteredScores, 0.7);
stats.stage2_nms = Date.now() - ts;
regions_1 = indicesNms.map(function (idx) {
var regionsData = rnetOuts[indices[idx]].regions.arraySync();
return new MtcnnBox_MtcnnBox(regionsData[0][0], regionsData[0][1], regionsData[0][2], regionsData[0][3]);
});
finalScores = indicesNms.map(function (idx) { return filteredScores[idx]; });
finalBoxes = indicesNms.map(function (idx, i) { return filteredBoxes[idx].calibrate(regions_1[i]); });
}
rnetOuts.forEach(function (t) {
t.regions.dispose();
t.scores.dispose();
});
return [2 /*return*/, {
boxes: finalBoxes,
scores: finalScores
}];
}
});
});
}
//# sourceMappingURL=stage2.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/ONet.js
function ONet_ONet(x, params) {
return tf_core_esm["tidy"](function () {
var out = sharedLayers_sharedLayer(x, params);
out = tf_core_esm["maxPool"](out, [2, 2], [2, 2], 'same');
out = convLayer_convLayer(out, params.conv4, 'valid');
out = prelu_prelu(out, params.prelu4_alpha);
var vectorized = tf_core_esm["reshape"](out, [out.shape[0], params.fc1.weights.shape[0]]);
var fc1 = fullyConnectedLayer_fullyConnectedLayer(vectorized, params.fc1);
var prelu5 = prelu_prelu(fc1, params.prelu5_alpha);
var fc2_1 = fullyConnectedLayer_fullyConnectedLayer(prelu5, params.fc2_1);
var max = tf_core_esm["expandDims"](tf_core_esm["max"](fc2_1, 1), 1);
var prob = tf_core_esm["softmax"](tf_core_esm["sub"](fc2_1, max), 1);
var regions = fullyConnectedLayer_fullyConnectedLayer(prelu5, params.fc2_2);
var points = fullyConnectedLayer_fullyConnectedLayer(prelu5, params.fc2_3);
var scores = tf_core_esm["unstack"](prob, 1)[1];
return { scores: scores, regions: regions, points: points };
});
}
//# sourceMappingURL=ONet.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/stage3.js
function stage3_stage3(img, inputBoxes, scoreThreshold, params, stats) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var ts, onetInputs, onetOuts, scoresTensor, scores, _a, _b, indices, filteredRegions, filteredBoxes, filteredScores, finalBoxes, finalScores, points, indicesNms;
return Object(tslib_es6["d" /* __generator */])(this, function (_c) {
switch (_c.label) {
case 0:
ts = Date.now();
return [4 /*yield*/, extractImagePatches_extractImagePatches(img, inputBoxes, { width: 48, height: 48 })];
case 1:
onetInputs = _c.sent();
stats.stage3_extractImagePatches = Date.now() - ts;
ts = Date.now();
onetOuts = onetInputs.map(function (onetInput) {
var out = ONet_ONet(onetInput, params);
onetInput.dispose();
return out;
});
stats.stage3_onet = Date.now() - ts;
scoresTensor = onetOuts.length > 1
? tf_core_esm["concat"](onetOuts.map(function (out) { return out.scores; }))
: onetOuts[0].scores;
_b = (_a = Array).from;
return [4 /*yield*/, scoresTensor.data()];
case 2:
scores = _b.apply(_a, [_c.sent()]);
scoresTensor.dispose();
indices = scores
.map(function (score, idx) { return ({ score: score, idx: idx }); })
.filter(function (c) { return c.score > scoreThreshold; })
.map(function (_a) {
var idx = _a.idx;
return idx;
});
filteredRegions = indices.map(function (idx) {
var regionsData = onetOuts[idx].regions.arraySync();
return new MtcnnBox_MtcnnBox(regionsData[0][0], regionsData[0][1], regionsData[0][2], regionsData[0][3]);
});
filteredBoxes = indices
.map(function (idx, i) { return inputBoxes[idx].calibrate(filteredRegions[i]); });
filteredScores = indices.map(function (idx) { return scores[idx]; });
finalBoxes = [];
finalScores = [];
points = [];
if (filteredBoxes.length > 0) {
ts = Date.now();
indicesNms = nonMaxSuppression_nonMaxSuppression(filteredBoxes, filteredScores, 0.7, false);
stats.stage3_nms = Date.now() - ts;
finalBoxes = indicesNms.map(function (idx) { return filteredBoxes[idx]; });
finalScores = indicesNms.map(function (idx) { return filteredScores[idx]; });
points = indicesNms.map(function (idx, i) {
return Array(5).fill(0).map(function (_, ptIdx) {
var pointsData = onetOuts[idx].points.arraySync();
return new Point(((pointsData[0][ptIdx] * (finalBoxes[i].width + 1)) + finalBoxes[i].left), ((pointsData[0][ptIdx + 5] * (finalBoxes[i].height + 1)) + finalBoxes[i].top));
});
});
}
onetOuts.forEach(function (t) {
t.regions.dispose();
t.scores.dispose();
t.points.dispose();
});
return [2 /*return*/, {
boxes: finalBoxes,
scores: finalScores,
points: points
}];
}
});
});
}
//# sourceMappingURL=stage3.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/Mtcnn.js
var Mtcnn_Mtcnn = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(Mtcnn, _super);
function Mtcnn() {
return _super.call(this, 'Mtcnn') || this;
}
Mtcnn.prototype.load = function (weightsOrUrl) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
console.warn('mtcnn is deprecated and will be removed soon');
return [2 /*return*/, _super.prototype.load.call(this, weightsOrUrl)];
});
});
};
Mtcnn.prototype.loadFromDisk = function (filePath) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
console.warn('mtcnn is deprecated and will be removed soon');
return [2 /*return*/, _super.prototype.loadFromDisk.call(this, filePath)];
});
});
};
Mtcnn.prototype.forwardInput = function (input, forwardParams) {
if (forwardParams === void 0) { forwardParams = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var params, inputCanvas, stats, tsTotal, imgTensor, onReturn, _a, height, width, _b, minFaceSize, scaleFactor, maxNumScales, scoreThresholds, scaleSteps, scales, ts, out1, out2, out3, results;
return Object(tslib_es6["d" /* __generator */])(this, function (_c) {
switch (_c.label) {
case 0:
params = this.params;
if (!params) {
throw new Error('Mtcnn - load model before inference');
}
inputCanvas = input.canvases[0];
if (!inputCanvas) {
throw new Error('Mtcnn - inputCanvas is not defined, note that passing tensors into Mtcnn.forwardInput is not supported yet.');
}
stats = {};
tsTotal = Date.now();
imgTensor = tf_core_esm["tidy"](function () {
return bgrToRgbTensor_bgrToRgbTensor(tf_core_esm["expandDims"](tf_core_esm["browser"].fromPixels(inputCanvas)).toFloat());
});
onReturn = function (results) {
// dispose tensors on return
imgTensor.dispose();
stats.total = Date.now() - tsTotal;
return results;
};
_a = imgTensor.shape.slice(1), height = _a[0], width = _a[1];
_b = new MtcnnOptions(forwardParams), minFaceSize = _b.minFaceSize, scaleFactor = _b.scaleFactor, maxNumScales = _b.maxNumScales, scoreThresholds = _b.scoreThresholds, scaleSteps = _b.scaleSteps;
scales = (scaleSteps || pyramidDown_pyramidDown(minFaceSize, scaleFactor, [height, width]))
.filter(function (scale) {
var sizes = getSizesForScale(scale, [height, width]);
return Math.min(sizes.width, sizes.height) > CELL_SIZE;
})
.slice(0, maxNumScales);
stats.scales = scales;
stats.pyramid = scales.map(function (scale) { return getSizesForScale(scale, [height, width]); });
ts = Date.now();
return [4 /*yield*/, stage1_stage1(imgTensor, scales, scoreThresholds[0], params.pnet, stats)];
case 1:
out1 = _c.sent();
stats.total_stage1 = Date.now() - ts;
if (!out1.boxes.length) {
return [2 /*return*/, onReturn({ results: [], stats: stats })];
}
stats.stage2_numInputBoxes = out1.boxes.length;
// using the inputCanvas to extract and resize the image patches, since it is faster
// than doing this on the gpu
ts = Date.now();
return [4 /*yield*/, stage2_stage2(inputCanvas, out1.boxes, scoreThresholds[1], params.rnet, stats)];
case 2:
out2 = _c.sent();
stats.total_stage2 = Date.now() - ts;
if (!out2.boxes.length) {
return [2 /*return*/, onReturn({ results: [], stats: stats })];
}
stats.stage3_numInputBoxes = out2.boxes.length;
ts = Date.now();
return [4 /*yield*/, stage3_stage3(inputCanvas, out2.boxes, scoreThresholds[2], params.onet, stats)];
case 3:
out3 = _c.sent();
stats.total_stage3 = Date.now() - ts;
results = out3.boxes.map(function (box, idx) { return WithFaceLandmarks_extendWithFaceLandmarks(WithFaceDetection_extendWithFaceDetection({}, new FaceDetection_FaceDetection(out3.scores[idx], new Rect_Rect(box.left / width, box.top / height, box.width / width, box.height / height), {
height: height,
width: width
})), new FaceLandmarks5_FaceLandmarks5(out3.points[idx].map(function (pt) { return pt.sub(new Point(box.left, box.top)).div(new Point(box.width, box.height)); }), { width: box.width, height: box.height })); });
return [2 /*return*/, onReturn({ results: results, stats: stats })];
}
});
});
};
Mtcnn.prototype.forward = function (input, forwardParams) {
if (forwardParams === void 0) { forwardParams = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [4 /*yield*/, _a.apply(this, [_b.sent(),
forwardParams])];
case 2: return [2 /*return*/, (_b.sent()).results];
}
});
});
};
Mtcnn.prototype.forwardWithStats = function (input, forwardParams) {
if (forwardParams === void 0) { forwardParams = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this.forwardInput;
return [4 /*yield*/, toNetInput_toNetInput(input)];
case 1: return [2 /*return*/, _a.apply(this, [_b.sent(),
forwardParams])];
}
});
});
};
Mtcnn.prototype.getDefaultModelName = function () {
return 'mtcnn_model';
};
Mtcnn.prototype.extractParamsFromWeigthMap = function (weightMap) {
return mtcnn_extractParamsFromWeigthMap_extractParamsFromWeigthMap(weightMap);
};
Mtcnn.prototype.extractParams = function (weights) {
return mtcnn_extractParams_extractParams(weights);
};
return Mtcnn;
}(NeuralNetwork_NeuralNetwork));
//# sourceMappingURL=Mtcnn.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyFaceDetector/const.js
var tinyFaceDetector_const_IOU_THRESHOLD = 0.4;
var tinyFaceDetector_const_BOX_ANCHORS = [
new Point(1.603231, 2.094468),
new Point(6.041143, 7.080126),
new Point(2.882459, 3.518061),
new Point(4.266906, 5.178857),
new Point(9.041765, 10.66308)
];
var const_MEAN_RGB = [117.001, 114.697, 97.404];
//# sourceMappingURL=const.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyFaceDetector/TinyFaceDetector.js
var TinyFaceDetector_TinyFaceDetector = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(TinyFaceDetector, _super);
function TinyFaceDetector() {
var _this = this;
var config = {
withSeparableConvs: true,
iouThreshold: tinyFaceDetector_const_IOU_THRESHOLD,
classes: ['face'],
anchors: tinyFaceDetector_const_BOX_ANCHORS,
meanRgb: const_MEAN_RGB,
isFirstLayerConv2d: true,
filterSizes: [3, 16, 32, 64, 128, 256, 512]
};
_this = _super.call(this, config) || this;
return _this;
}
Object.defineProperty(TinyFaceDetector.prototype, "anchors", {
get: function () {
return this.config.anchors;
},
enumerable: true,
configurable: true
});
TinyFaceDetector.prototype.locateFaces = function (input, forwardParams) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var objectDetections;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.detect(input, forwardParams)];
case 1:
objectDetections = _a.sent();
return [2 /*return*/, objectDetections.map(function (det) { return new FaceDetection_FaceDetection(det.score, det.relativeBox, { width: det.imageWidth, height: det.imageHeight }); })];
}
});
});
};
TinyFaceDetector.prototype.getDefaultModelName = function () {
return 'tiny_face_detector_model';
};
TinyFaceDetector.prototype.extractParamsFromWeigthMap = function (weightMap) {
return _super.prototype.extractParamsFromWeigthMap.call(this, weightMap);
};
return TinyFaceDetector;
}(TinyYolov2Base_TinyYolov2Base));
//# sourceMappingURL=TinyFaceDetector.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/nets.js
var nets_nets = {
ssdMobilenetv1: new SsdMobilenetv1_SsdMobilenetv1(),
tinyFaceDetector: new TinyFaceDetector_TinyFaceDetector(),
tinyYolov2: new TinyYolov2_TinyYolov2(),
mtcnn: new Mtcnn_Mtcnn(),
faceLandmark68Net: new FaceLandmark68Net_FaceLandmark68Net(),
faceLandmark68TinyNet: new FaceLandmark68TinyNet_FaceLandmark68TinyNet(),
faceRecognitionNet: new FaceRecognitionNet_FaceRecognitionNet(),
faceExpressionNet: new FaceExpressionNet_FaceExpressionNet(),
ageGenderNet: new AgeGenderNet_AgeGenderNet()
};
/**
* Attempts to detect all faces in an image using SSD Mobilenetv1 Network.
*
* @param input The input image.
* @param options (optional, default: see SsdMobilenetv1Options constructor for default parameters).
* @returns Bounding box of each face with score.
*/
var nets_ssdMobilenetv1 = function (input, options) {
return nets_nets.ssdMobilenetv1.locateFaces(input, options);
};
/**
* Attempts to detect all faces in an image using the Tiny Face Detector.
*
* @param input The input image.
* @param options (optional, default: see TinyFaceDetectorOptions constructor for default parameters).
* @returns Bounding box of each face with score.
*/
var nets_tinyFaceDetector = function (input, options) {
return nets_nets.tinyFaceDetector.locateFaces(input, options);
};
/**
* Attempts to detect all faces in an image using the Tiny Yolov2 Network.
*
* @param input The input image.
* @param options (optional, default: see TinyYolov2Options constructor for default parameters).
* @returns Bounding box of each face with score.
*/
var nets_tinyYolov2 = function (input, options) {
return nets_nets.tinyYolov2.locateFaces(input, options);
};
/**
* Attempts to detect all faces in an image and the 5 point face landmarks
* of each detected face using the MTCNN Network.
*
* @param input The input image.
* @param options (optional, default: see MtcnnOptions constructor for default parameters).
* @returns Bounding box of each face with score and 5 point face landmarks.
*/
var nets_mtcnn = function (input, options) {
return nets_nets.mtcnn.forward(input, options);
};
/**
* Detects the 68 point face landmark positions of the face shown in an image.
*
* @param inputs The face image extracted from the bounding box of a face. Can
* also be an array of input images, which will be batch processed.
* @returns 68 point face landmarks or array thereof in case of batch input.
*/
var nets_detectFaceLandmarks = function (input) {
return nets_nets.faceLandmark68Net.detectLandmarks(input);
};
/**
* Detects the 68 point face landmark positions of the face shown in an image
* using a tinier version of the 68 point face landmark model, which is slightly
* faster at inference, but also slightly less accurate.
*
* @param inputs The face image extracted from the bounding box of a face. Can
* also be an array of input images, which will be batch processed.
* @returns 68 point face landmarks or array thereof in case of batch input.
*/
var nets_detectFaceLandmarksTiny = function (input) {
return nets_nets.faceLandmark68TinyNet.detectLandmarks(input);
};
/**
* Computes a 128 entry vector (face descriptor / face embeddings) from the face shown in an image,
* which uniquely represents the features of that persons face. The computed face descriptor can
* be used to measure the similarity between faces, by computing the euclidean distance of two
* face descriptors.
*
* @param inputs The face image extracted from the aligned bounding box of a face. Can
* also be an array of input images, which will be batch processed.
* @returns Face descriptor with 128 entries or array thereof in case of batch input.
*/
var nets_computeFaceDescriptor = function (input) {
return nets_nets.faceRecognitionNet.computeFaceDescriptor(input);
};
/**
* Recognizes the facial expressions from a face image.
*
* @param inputs The face image extracted from the bounding box of a face. Can
* also be an array of input images, which will be batch processed.
* @returns Facial expressions with corresponding probabilities or array thereof in case of batch input.
*/
var nets_recognizeFaceExpressions = function (input) {
return nets_nets.faceExpressionNet.predictExpressions(input);
};
/**
* Predicts age and gender from a face image.
*
* @param inputs The face image extracted from the bounding box of a face. Can
* also be an array of input images, which will be batch processed.
* @returns Predictions with age, gender and gender probability or array thereof in case of batch input.
*/
var nets_predictAgeAndGender = function (input) {
return nets_nets.ageGenderNet.predictAgeAndGender(input);
};
var nets_loadSsdMobilenetv1Model = function (url) { return nets_nets.ssdMobilenetv1.load(url); };
var nets_loadTinyFaceDetectorModel = function (url) { return nets_nets.tinyFaceDetector.load(url); };
var nets_loadMtcnnModel = function (url) { return nets_nets.mtcnn.load(url); };
var nets_loadTinyYolov2Model = function (url) { return nets_nets.tinyYolov2.load(url); };
var nets_loadFaceLandmarkModel = function (url) { return nets_nets.faceLandmark68Net.load(url); };
var nets_loadFaceLandmarkTinyModel = function (url) { return nets_nets.faceLandmark68TinyNet.load(url); };
var nets_loadFaceRecognitionModel = function (url) { return nets_nets.faceRecognitionNet.load(url); };
var nets_loadFaceExpressionModel = function (url) { return nets_nets.faceExpressionNet.load(url); };
var nets_loadAgeGenderModel = function (url) { return nets_nets.ageGenderNet.load(url); };
// backward compatibility
var nets_loadFaceDetectionModel = nets_loadSsdMobilenetv1Model;
var nets_locateFaces = nets_ssdMobilenetv1;
var nets_detectLandmarks = nets_detectFaceLandmarks;
//# sourceMappingURL=nets.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/PredictFaceExpressionsTask.js
var PredictFaceExpressionsTask_PredictFaceExpressionsTaskBase = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictFaceExpressionsTaskBase, _super);
function PredictFaceExpressionsTaskBase(parentTask, input, extractedFaces) {
var _this = _super.call(this) || this;
_this.parentTask = parentTask;
_this.input = input;
_this.extractedFaces = extractedFaces;
return _this;
}
return PredictFaceExpressionsTaskBase;
}(ComposableTask_ComposableTask));
var PredictFaceExpressionsTask_PredictAllFaceExpressionsTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictAllFaceExpressionsTask, _super);
function PredictAllFaceExpressionsTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictAllFaceExpressionsTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResults, faceExpressionsByFace;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResults = _a.sent();
return [4 /*yield*/, extractFacesAndComputeResults_extractAllFacesAndComputeResults(parentResults, this.input, function (faces) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(faces.map(function (face) { return nets_nets.faceExpressionNet.predictExpressions(face); }))];
case 1: return [2 /*return*/, _a.sent()];
}
});
}); }, this.extractedFaces)];
case 2:
faceExpressionsByFace = _a.sent();
return [2 /*return*/, parentResults.map(function (parentResult, i) { return WithFaceExpressions_extendWithFaceExpressions(parentResult, faceExpressionsByFace[i]); })];
}
});
});
};
PredictAllFaceExpressionsTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictAllAgeAndGenderTask(this, this.input);
};
return PredictAllFaceExpressionsTask;
}(PredictFaceExpressionsTask_PredictFaceExpressionsTaskBase));
var PredictFaceExpressionsTask_PredictSingleFaceExpressionsTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictSingleFaceExpressionsTask, _super);
function PredictSingleFaceExpressionsTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictSingleFaceExpressionsTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResult, faceExpressions;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResult = _a.sent();
if (!parentResult) {
return [2 /*return*/];
}
return [4 /*yield*/, extractFacesAndComputeResults_extractSingleFaceAndComputeResult(parentResult, this.input, function (face) { return nets_nets.faceExpressionNet.predictExpressions(face); }, this.extractedFaces)];
case 2:
faceExpressions = _a.sent();
return [2 /*return*/, WithFaceExpressions_extendWithFaceExpressions(parentResult, faceExpressions)];
}
});
});
};
PredictSingleFaceExpressionsTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictSingleAgeAndGenderTask(this, this.input);
};
return PredictSingleFaceExpressionsTask;
}(PredictFaceExpressionsTask_PredictFaceExpressionsTaskBase));
var PredictFaceExpressionsTask_PredictAllFaceExpressionsWithFaceAlignmentTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictAllFaceExpressionsWithFaceAlignmentTask, _super);
function PredictAllFaceExpressionsWithFaceAlignmentTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictAllFaceExpressionsWithFaceAlignmentTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictAllAgeAndGenderWithFaceAlignmentTask(this, this.input);
};
PredictAllFaceExpressionsWithFaceAlignmentTask.prototype.withFaceDescriptors = function () {
return new ComputeFaceDescriptorsTasks_ComputeAllFaceDescriptorsTask(this, this.input);
};
return PredictAllFaceExpressionsWithFaceAlignmentTask;
}(PredictFaceExpressionsTask_PredictAllFaceExpressionsTask));
var PredictFaceExpressionsTask_PredictSingleFaceExpressionsWithFaceAlignmentTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictSingleFaceExpressionsWithFaceAlignmentTask, _super);
function PredictSingleFaceExpressionsWithFaceAlignmentTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictSingleFaceExpressionsWithFaceAlignmentTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictSingleAgeAndGenderWithFaceAlignmentTask(this, this.input);
};
PredictSingleFaceExpressionsWithFaceAlignmentTask.prototype.withFaceDescriptor = function () {
return new ComputeFaceDescriptorsTasks_ComputeSingleFaceDescriptorTask(this, this.input);
};
return PredictSingleFaceExpressionsWithFaceAlignmentTask;
}(PredictFaceExpressionsTask_PredictSingleFaceExpressionsTask));
//# sourceMappingURL=PredictFaceExpressionsTask.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/PredictAgeAndGenderTask.js
var PredictAgeAndGenderTask_PredictAgeAndGenderTaskBase = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictAgeAndGenderTaskBase, _super);
function PredictAgeAndGenderTaskBase(parentTask, input, extractedFaces) {
var _this = _super.call(this) || this;
_this.parentTask = parentTask;
_this.input = input;
_this.extractedFaces = extractedFaces;
return _this;
}
return PredictAgeAndGenderTaskBase;
}(ComposableTask_ComposableTask));
var PredictAgeAndGenderTask_PredictAllAgeAndGenderTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictAllAgeAndGenderTask, _super);
function PredictAllAgeAndGenderTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictAllAgeAndGenderTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResults, ageAndGenderByFace;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResults = _a.sent();
return [4 /*yield*/, extractFacesAndComputeResults_extractAllFacesAndComputeResults(parentResults, this.input, function (faces) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, Promise.all(faces.map(function (face) { return nets_nets.ageGenderNet.predictAgeAndGender(face); }))];
case 1: return [2 /*return*/, _a.sent()];
}
});
}); }, this.extractedFaces)];
case 2:
ageAndGenderByFace = _a.sent();
return [2 /*return*/, parentResults.map(function (parentResult, i) {
var _a = ageAndGenderByFace[i], age = _a.age, gender = _a.gender, genderProbability = _a.genderProbability;
return extendWithAge(WithGender_extendWithGender(parentResult, gender, genderProbability), age);
})];
}
});
});
};
PredictAllAgeAndGenderTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictAllFaceExpressionsTask(this, this.input);
};
return PredictAllAgeAndGenderTask;
}(PredictAgeAndGenderTask_PredictAgeAndGenderTaskBase));
var PredictAgeAndGenderTask_PredictSingleAgeAndGenderTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictSingleAgeAndGenderTask, _super);
function PredictSingleAgeAndGenderTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictSingleAgeAndGenderTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResult, _a, age, gender, genderProbability;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResult = _b.sent();
if (!parentResult) {
return [2 /*return*/];
}
return [4 /*yield*/, extractFacesAndComputeResults_extractSingleFaceAndComputeResult(parentResult, this.input, function (face) { return nets_nets.ageGenderNet.predictAgeAndGender(face); }, this.extractedFaces)];
case 2:
_a = _b.sent(), age = _a.age, gender = _a.gender, genderProbability = _a.genderProbability;
return [2 /*return*/, extendWithAge(WithGender_extendWithGender(parentResult, gender, genderProbability), age)];
}
});
});
};
PredictSingleAgeAndGenderTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictSingleFaceExpressionsTask(this, this.input);
};
return PredictSingleAgeAndGenderTask;
}(PredictAgeAndGenderTask_PredictAgeAndGenderTaskBase));
var PredictAgeAndGenderTask_PredictAllAgeAndGenderWithFaceAlignmentTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictAllAgeAndGenderWithFaceAlignmentTask, _super);
function PredictAllAgeAndGenderWithFaceAlignmentTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictAllAgeAndGenderWithFaceAlignmentTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictAllFaceExpressionsWithFaceAlignmentTask(this, this.input);
};
PredictAllAgeAndGenderWithFaceAlignmentTask.prototype.withFaceDescriptors = function () {
return new ComputeFaceDescriptorsTasks_ComputeAllFaceDescriptorsTask(this, this.input);
};
return PredictAllAgeAndGenderWithFaceAlignmentTask;
}(PredictAgeAndGenderTask_PredictAllAgeAndGenderTask));
var PredictAgeAndGenderTask_PredictSingleAgeAndGenderWithFaceAlignmentTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(PredictSingleAgeAndGenderWithFaceAlignmentTask, _super);
function PredictSingleAgeAndGenderWithFaceAlignmentTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
PredictSingleAgeAndGenderWithFaceAlignmentTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictSingleFaceExpressionsWithFaceAlignmentTask(this, this.input);
};
PredictSingleAgeAndGenderWithFaceAlignmentTask.prototype.withFaceDescriptor = function () {
return new ComputeFaceDescriptorsTasks_ComputeSingleFaceDescriptorTask(this, this.input);
};
return PredictSingleAgeAndGenderWithFaceAlignmentTask;
}(PredictAgeAndGenderTask_PredictSingleAgeAndGenderTask));
//# sourceMappingURL=PredictAgeAndGenderTask.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/ComputeFaceDescriptorsTasks.js
var ComputeFaceDescriptorsTasks_ComputeFaceDescriptorsTaskBase = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(ComputeFaceDescriptorsTaskBase, _super);
function ComputeFaceDescriptorsTaskBase(parentTask, input) {
var _this = _super.call(this) || this;
_this.parentTask = parentTask;
_this.input = input;
return _this;
}
return ComputeFaceDescriptorsTaskBase;
}(ComposableTask_ComposableTask));
var ComputeFaceDescriptorsTasks_ComputeAllFaceDescriptorsTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(ComputeAllFaceDescriptorsTask, _super);
function ComputeAllFaceDescriptorsTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
ComputeAllFaceDescriptorsTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResults, descriptors;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResults = _a.sent();
return [4 /*yield*/, extractFacesAndComputeResults_extractAllFacesAndComputeResults(parentResults, this.input, function (faces) { return Promise.all(faces.map(function (face) {
return nets_nets.faceRecognitionNet.computeFaceDescriptor(face);
})); }, null, function (parentResult) { return parentResult.landmarks.align(null, { useDlibAlignment: true }); })];
case 2:
descriptors = _a.sent();
return [2 /*return*/, descriptors.map(function (descriptor, i) { return extendWithFaceDescriptor(parentResults[i], descriptor); })];
}
});
});
};
ComputeAllFaceDescriptorsTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictAllFaceExpressionsWithFaceAlignmentTask(this, this.input);
};
ComputeAllFaceDescriptorsTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictAllAgeAndGenderWithFaceAlignmentTask(this, this.input);
};
return ComputeAllFaceDescriptorsTask;
}(ComputeFaceDescriptorsTasks_ComputeFaceDescriptorsTaskBase));
var ComputeFaceDescriptorsTasks_ComputeSingleFaceDescriptorTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(ComputeSingleFaceDescriptorTask, _super);
function ComputeSingleFaceDescriptorTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
ComputeSingleFaceDescriptorTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResult, descriptor;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResult = _a.sent();
if (!parentResult) {
return [2 /*return*/];
}
return [4 /*yield*/, extractFacesAndComputeResults_extractSingleFaceAndComputeResult(parentResult, this.input, function (face) { return nets_nets.faceRecognitionNet.computeFaceDescriptor(face); }, null, function (parentResult) { return parentResult.landmarks.align(null, { useDlibAlignment: true }); })];
case 2:
descriptor = _a.sent();
return [2 /*return*/, extendWithFaceDescriptor(parentResult, descriptor)];
}
});
});
};
ComputeSingleFaceDescriptorTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictSingleFaceExpressionsWithFaceAlignmentTask(this, this.input);
};
ComputeSingleFaceDescriptorTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictSingleAgeAndGenderWithFaceAlignmentTask(this, this.input);
};
return ComputeSingleFaceDescriptorTask;
}(ComputeFaceDescriptorsTasks_ComputeFaceDescriptorsTaskBase));
//# sourceMappingURL=ComputeFaceDescriptorsTasks.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/DetectFaceLandmarksTasks.js
var DetectFaceLandmarksTasks_DetectFaceLandmarksTaskBase = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(DetectFaceLandmarksTaskBase, _super);
function DetectFaceLandmarksTaskBase(parentTask, input, useTinyLandmarkNet) {
var _this = _super.call(this) || this;
_this.parentTask = parentTask;
_this.input = input;
_this.useTinyLandmarkNet = useTinyLandmarkNet;
return _this;
}
Object.defineProperty(DetectFaceLandmarksTaskBase.prototype, "landmarkNet", {
get: function () {
return this.useTinyLandmarkNet
? nets_nets.faceLandmark68TinyNet
: nets_nets.faceLandmark68Net;
},
enumerable: true,
configurable: true
});
return DetectFaceLandmarksTaskBase;
}(ComposableTask_ComposableTask));
var DetectFaceLandmarksTasks_DetectAllFaceLandmarksTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(DetectAllFaceLandmarksTask, _super);
function DetectAllFaceLandmarksTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
DetectAllFaceLandmarksTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResults, detections, faces, _a, faceLandmarksByFace;
var _this = this;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResults = _b.sent();
detections = parentResults.map(function (res) { return res.detection; });
if (!(this.input instanceof tf_core_esm["Tensor"])) return [3 /*break*/, 3];
return [4 /*yield*/, extractFaceTensors_extractFaceTensors(this.input, detections)];
case 2:
_a = _b.sent();
return [3 /*break*/, 5];
case 3: return [4 /*yield*/, extractFaces_extractFaces(this.input, detections)];
case 4:
_a = _b.sent();
_b.label = 5;
case 5:
faces = _a;
return [4 /*yield*/, Promise.all(faces.map(function (face) { return _this.landmarkNet.detectLandmarks(face); }))];
case 6:
faceLandmarksByFace = _b.sent();
faces.forEach(function (f) { return f instanceof tf_core_esm["Tensor"] && f.dispose(); });
return [2 /*return*/, parentResults.map(function (parentResult, i) {
return WithFaceLandmarks_extendWithFaceLandmarks(parentResult, faceLandmarksByFace[i]);
})];
}
});
});
};
DetectAllFaceLandmarksTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictAllFaceExpressionsWithFaceAlignmentTask(this, this.input);
};
DetectAllFaceLandmarksTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictAllAgeAndGenderWithFaceAlignmentTask(this, this.input);
};
DetectAllFaceLandmarksTask.prototype.withFaceDescriptors = function () {
return new ComputeFaceDescriptorsTasks_ComputeAllFaceDescriptorsTask(this, this.input);
};
return DetectAllFaceLandmarksTask;
}(DetectFaceLandmarksTasks_DetectFaceLandmarksTaskBase));
var DetectFaceLandmarksTasks_DetectSingleFaceLandmarksTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(DetectSingleFaceLandmarksTask, _super);
function DetectSingleFaceLandmarksTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
DetectSingleFaceLandmarksTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var parentResult, detection, faces, _a, landmarks;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.parentTask];
case 1:
parentResult = _b.sent();
if (!parentResult) {
return [2 /*return*/];
}
detection = parentResult.detection;
if (!(this.input instanceof tf_core_esm["Tensor"])) return [3 /*break*/, 3];
return [4 /*yield*/, extractFaceTensors_extractFaceTensors(this.input, [detection])];
case 2:
_a = _b.sent();
return [3 /*break*/, 5];
case 3: return [4 /*yield*/, extractFaces_extractFaces(this.input, [detection])];
case 4:
_a = _b.sent();
_b.label = 5;
case 5:
faces = _a;
return [4 /*yield*/, this.landmarkNet.detectLandmarks(faces[0])];
case 6:
landmarks = _b.sent();
faces.forEach(function (f) { return f instanceof tf_core_esm["Tensor"] && f.dispose(); });
return [2 /*return*/, WithFaceLandmarks_extendWithFaceLandmarks(parentResult, landmarks)];
}
});
});
};
DetectSingleFaceLandmarksTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictSingleFaceExpressionsWithFaceAlignmentTask(this, this.input);
};
DetectSingleFaceLandmarksTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictSingleAgeAndGenderWithFaceAlignmentTask(this, this.input);
};
DetectSingleFaceLandmarksTask.prototype.withFaceDescriptor = function () {
return new ComputeFaceDescriptorsTasks_ComputeSingleFaceDescriptorTask(this, this.input);
};
return DetectSingleFaceLandmarksTask;
}(DetectFaceLandmarksTasks_DetectFaceLandmarksTaskBase));
//# sourceMappingURL=DetectFaceLandmarksTasks.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/DetectFacesTasks.js
var DetectFacesTasks_DetectFacesTaskBase = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(DetectFacesTaskBase, _super);
function DetectFacesTaskBase(input, options) {
if (options === void 0) { options = new SsdMobilenetv1Options(); }
var _this = _super.call(this) || this;
_this.input = input;
_this.options = options;
return _this;
}
return DetectFacesTaskBase;
}(ComposableTask_ComposableTask));
var DetectFacesTasks_DetectAllFacesTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(DetectAllFacesTask, _super);
function DetectAllFacesTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
DetectAllFacesTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var _a, input, options, faceDetectionFunction;
return Object(tslib_es6["d" /* __generator */])(this, function (_b) {
switch (_b.label) {
case 0:
_a = this, input = _a.input, options = _a.options;
if (!(options instanceof MtcnnOptions)) return [3 /*break*/, 2];
return [4 /*yield*/, nets_nets.mtcnn.forward(input, options)];
case 1: return [2 /*return*/, (_b.sent())
.map(function (result) { return result.detection; })];
case 2:
faceDetectionFunction = options instanceof TinyFaceDetectorOptions_TinyFaceDetectorOptions
? function (input) { return nets_nets.tinyFaceDetector.locateFaces(input, options); }
: (options instanceof SsdMobilenetv1Options
? function (input) { return nets_nets.ssdMobilenetv1.locateFaces(input, options); }
: (options instanceof TinyYolov2Options
? function (input) { return nets_nets.tinyYolov2.locateFaces(input, options); }
: null));
if (!faceDetectionFunction) {
throw new Error('detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options');
}
return [2 /*return*/, faceDetectionFunction(input)];
}
});
});
};
DetectAllFacesTask.prototype.runAndExtendWithFaceDetections = function () {
var _this = this;
return new Promise(function (res) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
var detections;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.run()];
case 1:
detections = _a.sent();
return [2 /*return*/, res(detections.map(function (detection) { return WithFaceDetection_extendWithFaceDetection({}, detection); }))];
}
});
}); });
};
DetectAllFacesTask.prototype.withFaceLandmarks = function (useTinyLandmarkNet) {
if (useTinyLandmarkNet === void 0) { useTinyLandmarkNet = false; }
return new DetectFaceLandmarksTasks_DetectAllFaceLandmarksTask(this.runAndExtendWithFaceDetections(), this.input, useTinyLandmarkNet);
};
DetectAllFacesTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictAllFaceExpressionsTask(this.runAndExtendWithFaceDetections(), this.input);
};
DetectAllFacesTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictAllAgeAndGenderTask(this.runAndExtendWithFaceDetections(), this.input);
};
return DetectAllFacesTask;
}(DetectFacesTasks_DetectFacesTaskBase));
var DetectFacesTasks_DetectSingleFaceTask = /** @class */ (function (_super) {
Object(tslib_es6["c" /* __extends */])(DetectSingleFaceTask, _super);
function DetectSingleFaceTask() {
return _super !== null && _super.apply(this, arguments) || this;
}
DetectSingleFaceTask.prototype.run = function () {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
var faceDetections, faceDetectionWithHighestScore;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new DetectFacesTasks_DetectAllFacesTask(this.input, this.options)];
case 1:
faceDetections = _a.sent();
faceDetectionWithHighestScore = faceDetections[0];
faceDetections.forEach(function (faceDetection) {
if (faceDetection.score > faceDetectionWithHighestScore.score) {
faceDetectionWithHighestScore = faceDetection;
}
});
return [2 /*return*/, faceDetectionWithHighestScore];
}
});
});
};
DetectSingleFaceTask.prototype.runAndExtendWithFaceDetection = function () {
var _this = this;
return new Promise(function (res) { return Object(tslib_es6["b" /* __awaiter */])(_this, void 0, void 0, function () {
var detection;
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.run()];
case 1:
detection = _a.sent();
return [2 /*return*/, res(detection ? WithFaceDetection_extendWithFaceDetection({}, detection) : undefined)];
}
});
}); });
};
DetectSingleFaceTask.prototype.withFaceLandmarks = function (useTinyLandmarkNet) {
if (useTinyLandmarkNet === void 0) { useTinyLandmarkNet = false; }
return new DetectFaceLandmarksTasks_DetectSingleFaceLandmarksTask(this.runAndExtendWithFaceDetection(), this.input, useTinyLandmarkNet);
};
DetectSingleFaceTask.prototype.withFaceExpressions = function () {
return new PredictFaceExpressionsTask_PredictSingleFaceExpressionsTask(this.runAndExtendWithFaceDetection(), this.input);
};
DetectSingleFaceTask.prototype.withAgeAndGender = function () {
return new PredictAgeAndGenderTask_PredictSingleAgeAndGenderTask(this.runAndExtendWithFaceDetection(), this.input);
};
return DetectSingleFaceTask;
}(DetectFacesTasks_DetectFacesTaskBase));
//# sourceMappingURL=DetectFacesTasks.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/detectFaces.js
function detectFaces_detectSingleFace(input, options) {
if (options === void 0) { options = new SsdMobilenetv1Options(); }
return new DetectFacesTasks_DetectSingleFaceTask(input, options);
}
function detectFaces_detectAllFaces(input, options) {
if (options === void 0) { options = new SsdMobilenetv1Options(); }
return new DetectFacesTasks_DetectAllFacesTask(input, options);
}
//# sourceMappingURL=detectFaces.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/allFaces.js
// export allFaces API for backward compatibility
function allFaces_allFacesSsdMobilenetv1(input, minConfidence) {
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
console.warn('allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead');
return [4 /*yield*/, detectFaces_detectAllFaces(input, new SsdMobilenetv1Options(minConfidence ? { minConfidence: minConfidence } : {}))
.withFaceLandmarks()
.withFaceDescriptors()];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
}
function allFaces_allFacesTinyYolov2(input, forwardParams) {
if (forwardParams === void 0) { forwardParams = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
console.warn('allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead');
return [4 /*yield*/, detectFaces_detectAllFaces(input, new TinyYolov2Options(forwardParams))
.withFaceLandmarks()
.withFaceDescriptors()];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
}
function allFaces_allFacesMtcnn(input, forwardParams) {
if (forwardParams === void 0) { forwardParams = {}; }
return Object(tslib_es6["b" /* __awaiter */])(this, void 0, void 0, function () {
return Object(tslib_es6["d" /* __generator */])(this, function (_a) {
switch (_a.label) {
case 0:
console.warn('allFacesMtcnn is deprecated and will be removed soon, use the high level api instead');
return [4 /*yield*/, detectFaces_detectAllFaces(input, new MtcnnOptions(forwardParams))
.withFaceLandmarks()
.withFaceDescriptors()];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
}
var allFaces_allFaces = allFaces_allFacesSsdMobilenetv1;
//# sourceMappingURL=allFaces.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/euclideanDistance.js
function euclideanDistance(arr1, arr2) {
if (arr1.length !== arr2.length)
throw new Error('euclideanDistance: arr1.length !== arr2.length');
var desc1 = Array.from(arr1);
var desc2 = Array.from(arr2);
return Math.sqrt(desc1
.map(function (val, i) { return val - desc2[i]; })
.reduce(function (res, diff) { return res + Math.pow(diff, 2); }, 0));
}
//# sourceMappingURL=euclideanDistance.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/FaceMatcher.js
var FaceMatcher_FaceMatcher = /** @class */ (function () {
function FaceMatcher(inputs, distanceThreshold) {
if (distanceThreshold === void 0) { distanceThreshold = 0.6; }
this._distanceThreshold = distanceThreshold;
var inputArray = Array.isArray(inputs) ? inputs : [inputs];
if (!inputArray.length) {
throw new Error("FaceRecognizer.constructor - expected atleast one input");
}
var count = 1;
var createUniqueLabel = function () { return "person " + count++; };
this._labeledDescriptors = inputArray.map(function (desc) {
if (desc instanceof LabeledFaceDescriptors) {
return desc;
}
if (desc instanceof Float32Array) {
return new LabeledFaceDescriptors(createUniqueLabel(), [desc]);
}
if (desc.descriptor && desc.descriptor instanceof Float32Array) {
return new LabeledFaceDescriptors(createUniqueLabel(), [desc.descriptor]);
}
throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>");
});
}
Object.defineProperty(FaceMatcher.prototype, "labeledDescriptors", {
get: function () { return this._labeledDescriptors; },
enumerable: true,
configurable: true
});
Object.defineProperty(FaceMatcher.prototype, "distanceThreshold", {
get: function () { return this._distanceThreshold; },
enumerable: true,
configurable: true
});
FaceMatcher.prototype.computeMeanDistance = function (queryDescriptor, descriptors) {
return descriptors
.map(function (d) { return euclideanDistance(d, queryDescriptor); })
.reduce(function (d1, d2) { return d1 + d2; }, 0)
/ (descriptors.length || 1);
};
FaceMatcher.prototype.matchDescriptor = function (queryDescriptor) {
var _this = this;
return this.labeledDescriptors
.map(function (_a) {
var descriptors = _a.descriptors, label = _a.label;
return new FaceMatch_FaceMatch(label, _this.computeMeanDistance(queryDescriptor, descriptors));
})
.reduce(function (best, curr) { return best.distance < curr.distance ? best : curr; });
};
FaceMatcher.prototype.findBestMatch = function (queryDescriptor) {
var bestMatch = this.matchDescriptor(queryDescriptor);
return bestMatch.distance < this.distanceThreshold
? bestMatch
: new FaceMatch_FaceMatch('unknown', bestMatch.distance);
};
FaceMatcher.prototype.toJSON = function () {
return {
distanceThreshold: this.distanceThreshold,
labeledDescriptors: this.labeledDescriptors.map(function (ld) { return ld.toJSON(); })
};
};
FaceMatcher.fromJSON = function (json) {
var labeledDescriptors = json.labeledDescriptors
.map(function (ld) { return LabeledFaceDescriptors.fromJSON(ld); });
return new FaceMatcher(labeledDescriptors, json.distanceThreshold);
};
return FaceMatcher;
}());
//# sourceMappingURL=FaceMatcher.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/globalApi/index.js
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/mtcnn/index.js
function mtcnn_createMtcnn(weights) {
var net = new Mtcnn_Mtcnn();
net.extractWeights(weights);
return net;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/tinyFaceDetector/index.js
function tinyFaceDetector_createTinyFaceDetector(weights) {
var net = new TinyFaceDetector_TinyFaceDetector();
net.extractWeights(weights);
return net;
}
//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/resizeResults.js
function resizeResults_resizeResults(results, dimensions) {
var _a = new Dimensions_Dimensions(dimensions.width, dimensions.height), width = _a.width, height = _a.height;
if (width <= 0 || height <= 0) {
throw new Error("resizeResults - invalid dimensions: " + JSON.stringify({ width: width, height: height }));
}
if (Array.isArray(results)) {
return results.map(function (obj) { return resizeResults_resizeResults(obj, { width: width, height: height }); });
}
if (WithFaceLandmarks_isWithFaceLandmarks(results)) {
var resizedDetection = results.detection.forSize(width, height);
var resizedLandmarks = results.unshiftedLandmarks.forSize(resizedDetection.box.width, resizedDetection.box.height);
return WithFaceLandmarks_extendWithFaceLandmarks(WithFaceDetection_extendWithFaceDetection(results, resizedDetection), resizedLandmarks);
}
if (WithFaceDetection_isWithFaceDetection(results)) {
return WithFaceDetection_extendWithFaceDetection(results, results.detection.forSize(width, height));
}
if (results instanceof FaceLandmarks_FaceLandmarks || results instanceof FaceDetection_FaceDetection) {
return results.forSize(width, height);
}
return results;
}
//# sourceMappingURL=resizeResults.js.map
// CONCATENATED MODULE: ./node_modules/face-api.js/build/es6/index.js
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "draw", function() { return draw_namespaceObject; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "utils", function() { return utils_namespaceObject; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tf", function() { return tf_core_esm; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "AgeGenderNet", function() { return AgeGenderNet_AgeGenderNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Gender", function() { return Gender; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return BoundingBox_BoundingBox; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Box", function() { return Box_Box; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Dimensions", function() { return Dimensions_Dimensions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceDetection", function() { return FaceDetection_FaceDetection; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceLandmarks", function() { return FaceLandmarks_FaceLandmarks; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceLandmarks5", function() { return FaceLandmarks5_FaceLandmarks5; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceLandmarks68", function() { return FaceLandmarks68_FaceLandmarks68; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceMatch", function() { return FaceMatch_FaceMatch; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "LabeledBox", function() { return LabeledBox_LabeledBox; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "LabeledFaceDescriptors", function() { return LabeledFaceDescriptors; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ObjectDetection", function() { return ObjectDetection_ObjectDetection; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Point", function() { return Point; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "PredictedBox", function() { return PredictedBox_PredictedBox; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Rect", function() { return Rect_Rect; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "awaitMediaLoaded", function() { return awaitMediaLoaded_awaitMediaLoaded; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "bufferToImage", function() { return bufferToImage_bufferToImage; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createCanvas", function() { return createCanvas_createCanvas; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createCanvasFromMedia", function() { return createCanvas_createCanvasFromMedia; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extractFaces", function() { return extractFaces_extractFaces; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extractFaceTensors", function() { return extractFaceTensors_extractFaceTensors; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fetchImage", function() { return fetchImage_fetchImage; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fetchJson", function() { return fetchJson_fetchJson; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fetchNetWeights", function() { return fetchNetWeights_fetchNetWeights; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "fetchOrThrow", function() { return fetchOrThrow_fetchOrThrow; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "getContext2dOrThrow", function() { return getContext2dOrThrow_getContext2dOrThrow; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "getMediaDimensions", function() { return getMediaDimensions_getMediaDimensions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "imageTensorToCanvas", function() { return imageTensorToCanvas_imageTensorToCanvas; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "imageToSquare", function() { return imageToSquare_imageToSquare; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isMediaElement", function() { return isMediaElement_isMediaElement; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isMediaLoaded", function() { return isMediaLoaded_isMediaLoaded; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadWeightMap", function() { return loadWeightMap_loadWeightMap; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "matchDimensions", function() { return matchDimensions_matchDimensions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "NetInput", function() { return NetInput_NetInput; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "resolveInput", function() { return resolveInput_resolveInput; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "toNetInput", function() { return toNetInput_toNetInput; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "env", function() { return env_env; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceExpressionNet", function() { return FaceExpressionNet_FaceExpressionNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FACE_EXPRESSION_LABELS", function() { return FACE_EXPRESSION_LABELS; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceExpressions", function() { return FaceExpressions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceLandmarkNet", function() { return faceLandmarkNet_FaceLandmarkNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceLandmark68Net", function() { return FaceLandmark68Net_FaceLandmark68Net; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceLandmark68TinyNet", function() { return FaceLandmark68TinyNet_FaceLandmark68TinyNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createFaceRecognitionNet", function() { return faceRecognitionNet_createFaceRecognitionNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceRecognitionNet", function() { return FaceRecognitionNet_FaceRecognitionNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extendWithFaceDescriptor", function() { return extendWithFaceDescriptor; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isWithFaceDetection", function() { return WithFaceDetection_isWithFaceDetection; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extendWithFaceDetection", function() { return WithFaceDetection_extendWithFaceDetection; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isWithFaceExpressions", function() { return WithFaceExpressions_isWithFaceExpressions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extendWithFaceExpressions", function() { return WithFaceExpressions_extendWithFaceExpressions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isWithFaceLandmarks", function() { return WithFaceLandmarks_isWithFaceLandmarks; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extendWithFaceLandmarks", function() { return WithFaceLandmarks_extendWithFaceLandmarks; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isWithAge", function() { return isWithAge; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extendWithAge", function() { return extendWithAge; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "isWithGender", function() { return WithGender_isWithGender; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "extendWithGender", function() { return WithGender_extendWithGender; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "allFacesSsdMobilenetv1", function() { return allFaces_allFacesSsdMobilenetv1; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "allFacesTinyYolov2", function() { return allFaces_allFacesTinyYolov2; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "allFacesMtcnn", function() { return allFaces_allFacesMtcnn; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "allFaces", function() { return allFaces_allFaces; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ComposableTask", function() { return ComposableTask_ComposableTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ComputeFaceDescriptorsTaskBase", function() { return ComputeFaceDescriptorsTasks_ComputeFaceDescriptorsTaskBase; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ComputeAllFaceDescriptorsTask", function() { return ComputeFaceDescriptorsTasks_ComputeAllFaceDescriptorsTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ComputeSingleFaceDescriptorTask", function() { return ComputeFaceDescriptorsTasks_ComputeSingleFaceDescriptorTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "detectSingleFace", function() { return detectFaces_detectSingleFace; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "detectAllFaces", function() { return detectFaces_detectAllFaces; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DetectFacesTaskBase", function() { return DetectFacesTasks_DetectFacesTaskBase; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DetectAllFacesTask", function() { return DetectFacesTasks_DetectAllFacesTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DetectSingleFaceTask", function() { return DetectFacesTasks_DetectSingleFaceTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DetectFaceLandmarksTaskBase", function() { return DetectFaceLandmarksTasks_DetectFaceLandmarksTaskBase; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DetectAllFaceLandmarksTask", function() { return DetectFaceLandmarksTasks_DetectAllFaceLandmarksTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "DetectSingleFaceLandmarksTask", function() { return DetectFaceLandmarksTasks_DetectSingleFaceLandmarksTask; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceMatcher", function() { return FaceMatcher_FaceMatcher; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "nets", function() { return nets_nets; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "ssdMobilenetv1", function() { return nets_ssdMobilenetv1; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tinyFaceDetector", function() { return nets_tinyFaceDetector; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "tinyYolov2", function() { return nets_tinyYolov2; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "mtcnn", function() { return nets_mtcnn; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "detectFaceLandmarks", function() { return nets_detectFaceLandmarks; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "detectFaceLandmarksTiny", function() { return nets_detectFaceLandmarksTiny; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "computeFaceDescriptor", function() { return nets_computeFaceDescriptor; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "recognizeFaceExpressions", function() { return nets_recognizeFaceExpressions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "predictAgeAndGender", function() { return nets_predictAgeAndGender; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadSsdMobilenetv1Model", function() { return nets_loadSsdMobilenetv1Model; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadTinyFaceDetectorModel", function() { return nets_loadTinyFaceDetectorModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadMtcnnModel", function() { return nets_loadMtcnnModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadTinyYolov2Model", function() { return nets_loadTinyYolov2Model; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadFaceLandmarkModel", function() { return nets_loadFaceLandmarkModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadFaceLandmarkTinyModel", function() { return nets_loadFaceLandmarkTinyModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadFaceRecognitionModel", function() { return nets_loadFaceRecognitionModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadFaceExpressionModel", function() { return nets_loadFaceExpressionModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadAgeGenderModel", function() { return nets_loadAgeGenderModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "loadFaceDetectionModel", function() { return nets_loadFaceDetectionModel; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "locateFaces", function() { return nets_locateFaces; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "detectLandmarks", function() { return nets_detectLandmarks; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createMtcnn", function() { return mtcnn_createMtcnn; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Mtcnn", function() { return Mtcnn_Mtcnn; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "MtcnnOptions", function() { return MtcnnOptions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "sigmoid", function() { return sigmoid; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "inverseSigmoid", function() { return inverseSigmoid; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "iou", function() { return iou; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "minBbox", function() { return minBbox_minBbox; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "nonMaxSuppression", function() { return nonMaxSuppression_nonMaxSuppression; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "normalize", function() { return normalize_normalize; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "padToSquare", function() { return padToSquare_padToSquare; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "shuffleArray", function() { return shuffleArray; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createSsdMobilenetv1", function() { return ssdMobilenetv1_createSsdMobilenetv1; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createFaceDetectionNet", function() { return ssdMobilenetv1_createFaceDetectionNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "FaceDetectionNet", function() { return ssdMobilenetv1_FaceDetectionNet; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "SsdMobilenetv1", function() { return SsdMobilenetv1_SsdMobilenetv1; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "SsdMobilenetv1Options", function() { return SsdMobilenetv1Options; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createTinyFaceDetector", function() { return tinyFaceDetector_createTinyFaceDetector; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "TinyFaceDetector", function() { return TinyFaceDetector_TinyFaceDetector; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "TinyFaceDetectorOptions", function() { return TinyFaceDetectorOptions_TinyFaceDetectorOptions; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "TinyYolov2", function() { return TinyYolov2_TinyYolov2; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "createTinyYolov2", function() { return tinyYolov2_createTinyYolov2; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "TinyYolov2SizeType", function() { return TinyYolov2SizeType; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "TinyYolov2Options", function() { return TinyYolov2Options; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "validateConfig", function() { return validateConfig; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "euclideanDistance", function() { return euclideanDistance; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "NeuralNetwork", function() { return NeuralNetwork_NeuralNetwork; });
/* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "resizeResults", function() { return resizeResults_resizeResults; });
//# sourceMappingURL=index.js.map
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getImageData = exports.getRobin = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var getRobin = exports.getRobin = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var img;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
img = new Image();
img.crossOrigin = "";
img.src = "https://cdn.jsdelivr.net/gh/ml5js/ml5-library@development/assets/bird.jpg";
_context.next = 5;
return new _promise2.default(function (resolve) {
img.onload = resolve;
});
case 5:
return _context.abrupt("return", img);
case 6:
case "end":
return _context.stop();
}
}
}, _callee, undefined);
}));
return function getRobin() {
return _ref.apply(this, arguments);
};
}();
var getImageData = exports.getImageData = function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
var arr, i, img;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
arr = new Uint8ClampedArray(20000);
// Iterate through every pixel
for (i = 0; i < arr.length; i += 4) {
arr[i + 0] = 0; // R value
arr[i + 1] = 190; // G value
arr[i + 2] = 0; // B value
arr[i + 3] = 255; // A value
}
// Initialize a new ImageData object
img = new ImageData(arr, 200);
return _context2.abrupt("return", img);
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2, undefined);
}));
return function getImageData() {
return _ref2.apply(this, arguments);
};
}();
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _package = __webpack_require__(201);
exports.default = function () {
console.log('\n\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\n\uD83C\uDF1F Thank you for using ml5.js v' + _package.version + ' \uD83C\uDF1F\n\nPlease read our community statement to ensure \nthat the use of this software reflects the values \nof the ml5.js community:\n\u21B3 https://ml5js.org/about\n\nReporting: \n\u21B3 https://github.com/ml5js/ml5-library/issues\n\u21B3 Email: info@ml5js.org \n\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08\uD83C\uDF08');
};
/***/ }),
/* 293 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HandPose", function() { return HandPose; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
function getBoxSize(t){return[Math.abs(t.endPoint[0]-t.startPoint[0]),Math.abs(t.endPoint[1]-t.startPoint[1])]}function getBoxCenter(t){return[t.startPoint[0]+(t.endPoint[0]-t.startPoint[0])/2,t.startPoint[1]+(t.endPoint[1]-t.startPoint[1])/2]}function cutBoxFromImageAndResize(t,n,e){const o=n.shape[1],s=n.shape[2],i=[[t.startPoint[1]/o,t.startPoint[0]/s,t.endPoint[1]/o,t.endPoint[0]/s]];return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].cropAndResize(n,i,[0],e)}function scaleBoxCoordinates(t,n){return{startPoint:[t.startPoint[0]*n[0],t.startPoint[1]*n[1]],endPoint:[t.endPoint[0]*n[0],t.endPoint[1]*n[1]],palmLandmarks:t.palmLandmarks.map(t=>{return[t[0]*n[0],t[1]*n[1]]})}}function enlargeBox(t,n=1.5){const e=getBoxCenter(t),o=getBoxSize(t),s=[n*o[0]/2,n*o[1]/2];return{startPoint:[e[0]-s[0],e[1]-s[1]],endPoint:[e[0]+s[0],e[1]+s[1]],palmLandmarks:t.palmLandmarks}}function squarifyBox(t){const n=getBoxCenter(t),e=getBoxSize(t),o=Math.max(...e)/2;return{startPoint:[n[0]-o,n[1]-o],endPoint:[n[0]+o,n[1]+o],palmLandmarks:t.palmLandmarks}}function shiftBox(t,n){const e=[t.endPoint[0]-t.startPoint[0],t.endPoint[1]-t.startPoint[1]],o=[e[0]*n[0],e[1]*n[1]];return{startPoint:[t.startPoint[0]+o[0],t.startPoint[1]+o[1]],endPoint:[t.endPoint[0]+o[0],t.endPoint[1]+o[1]],palmLandmarks:t.palmLandmarks}}class HandDetector{constructor(t,n,e,o,s,i){this.model=t,this.width=n,this.height=e,this.iouThreshold=s,this.scoreThreshold=i,this.anchors=o.map(t=>[t.x_center,t.y_center]),this.anchorsTensor=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(this.anchors),this.inputSizeTensor=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([n,e]),this.doubleInputSizeTensor=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([2*n,2*e])}normalizeBoxes(t){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(t,[0,0],[-1,2]),e=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(t,[0,2],[-1,2]),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(n,this.inputSizeTensor),this.anchorsTensor),s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(e,this.doubleInputSizeTensor),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(o,s),this.inputSizeTensor),r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(o,s),this.inputSizeTensor);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([i,r],1)})}normalizeLandmarks(t,n){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const e=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(t.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[n]);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(e,this.inputSizeTensor)})}getBoundingBoxes(t){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(t,.5),2),e=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("WEBGL_PACK_DEPTHWISECONV");Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().set("WEBGL_PACK_DEPTHWISECONV",!0);const o=this.model.predict(n).squeeze();Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().set("WEBGL_PACK_DEPTHWISECONV",e);const s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sigmoid"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(o,[0,0],[-1,1])).squeeze(),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(o,[0,1],[-1,4]),r=this.normalizeBoxes(i),a=console.warn;console.warn=(()=>{});const d=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].nonMaxSuppression(r,s,1,this.iouThreshold,this.scoreThreshold).arraySync();if(console.warn=a,0===d.length)return null;const u=d[0],c=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(r,[u,0],[1,-1]),h=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(o,[u,5],[1,14]);return{boxes:c,palmLandmarks:this.normalizeLandmarks(h,u).reshape([-1,2])}})}estimateHandBounds(t){const n=t.shape[1],e=t.shape[2],o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>t.resizeBilinear([this.width,this.height]).div(255)),s=this.getBoundingBoxes(o);if(null===s)return o.dispose(),null;const i=s.boxes.arraySync(),r=i[0].slice(0,2),a=i[0].slice(2,4),d=s.palmLandmarks.arraySync();return o.dispose(),s.boxes.dispose(),s.palmLandmarks.dispose(),scaleBoxCoordinates({startPoint:r,endPoint:a,palmLandmarks:d},[e/this.width,n/this.height])}}const MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]};function rotate(t,n,e,o){const s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend"])(),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["buffer"])(t.shape,t.dtype),[r,a,d,u]=t.shape,c=d*("number"==typeof o?o:o[0]),h=a*("number"==typeof o?o:o[1]),l=Math.sin(-n),m=Math.cos(-n),p=s.readSync(t.dataId);for(let t=0;t<r;t++)for(let n=0;n<a;n++)for(let o=0;o<d;o++)for(let s=0;s<u;s++){const f=[r,n,o,s],_=f[2],P=f[1];let g=(_-c)*m-(P-h)*l,M=(_-c)*l+(P-h)*m;g=Math.round(g+c),M=Math.round(M+h);let T=e;if("number"!=typeof e&&(T=3===s?255:e[s]),g>=0&&g<d&&M>=0&&M<a){T=p[t*d*a*u+M*(d*u)+g*u+s]}const I=t*d*a*u+n*(d*u)+o*u+s;i.values[I]=T}return i.toTensor()}function rotate$1(t,n,e,o){const s=t.shape,i=s[1],r=s[2],a=Math.sin(n),d=Math.cos(n),u=Math.floor(r*("number"==typeof o?o:o[0])),c=Math.floor(i*("number"==typeof o?o:o[1]));let h="";const l={variableNames:["Image"],outputShape:s,userCode:`\n void main() {\n ivec4 coords = getOutputCoords();\n int x = coords[2];\n int y = coords[1];\n int coordX = int(float(x - ${u}) * ${d} -\n float(y - ${c}) * ${a});\n int coordY = int(float(x - ${u}) * ${a} +\n float(y - ${c}) * ${d});\n coordX = int(coordX + ${u});\n coordY = int(coordY + ${c});\n\n ${h="number"==typeof e?`float outputValue = ${e.toFixed(2)};`:`\n vec3 fill = vec3(${e.join(",")});\n float outputValue = fill[coords[3]];`}\n\n if(coordX > 0 && coordX < ${r} && coordY > 0 && coordY < ${i}) {\n outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n }\n\n setOutput(outputValue);\n }`};return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["backend"])().compileAndRun(l,[t])}function normalizeRadians(t){return t-2*Math.PI*Math.floor((t+Math.PI)/(2*Math.PI))}function computeRotation(t,n){return normalizeRadians(Math.PI/2-Math.atan2(-(n[1]-t[1]),n[0]-t[0]))}const buildTranslationMatrix=(t,n)=>[[1,0,t],[0,1,n],[0,0,1]];function dot(t,n){let e=0;for(let o=0;o<t.length;o++)e+=t[o]*n[o];return e}function getColumnFrom2DArr(t,n){const e=[];for(let o=0;o<t.length;o++)e.push(t[o][n]);return e}function multiplyTransformMatrices(t,n){const e=[],o=t.length;for(let s=0;s<o;s++){e.push([]);for(let i=0;i<o;i++)e[s].push(dot(t[s],getColumnFrom2DArr(n,i)))}return e}function buildRotationMatrix(t,n){const e=Math.cos(t),o=Math.sin(t),s=[[e,-o,0],[o,e,0],[0,0,1]];return multiplyTransformMatrices(multiplyTransformMatrices(buildTranslationMatrix(n[0],n[1]),s),buildTranslationMatrix(-n[0],-n[1]))}function invertTransformMatrix(t){const n=[[t[0][0],t[1][0]],[t[0][1],t[1][1]]],e=[t[0][2],t[1][2]],o=[-dot(n[0],e),-dot(n[1],e)];return[n[0].concat(o[0]),n[1].concat(o[1]),[0,0,1]]}function rotatePoint(t,n){return[dot(t,n[0]),dot(t,n[1])]}const UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD=.8,PALM_BOX_SHIFT_VECTOR=[0,-.4],PALM_BOX_ENLARGE_FACTOR=3,HAND_BOX_SHIFT_VECTOR=[0,-.1],HAND_BOX_ENLARGE_FACTOR=1.65,PALM_LANDMARK_IDS=[0,5,9,13,17,1,2],PALM_LANDMARKS_INDEX_OF_PALM_BASE=0,PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE=2;class HandPipeline{constructor(t,n,e,o,s,i){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=t,this.meshDetector=n,this.maxContinuousChecks=s,this.detectionConfidence=i,this.meshWidth=e,this.meshHeight=o,this.maxHandsNumber=1}getBoxForPalmLandmarks(t,n){const e=t.map(t=>{return rotatePoint([...t,1],n)});return enlargeBox(squarifyBox(shiftBox(this.calculateLandmarksBoundingBox(e),PALM_BOX_SHIFT_VECTOR)),PALM_BOX_ENLARGE_FACTOR)}getBoxForHandLandmarks(t){const n=enlargeBox(squarifyBox(shiftBox(this.calculateLandmarksBoundingBox(t),HAND_BOX_SHIFT_VECTOR)),HAND_BOX_ENLARGE_FACTOR),e=[];for(let n=0;n<PALM_LANDMARK_IDS.length;n++)e.push(t[PALM_LANDMARK_IDS[n]].slice(0,2));return n.palmLandmarks=e,n}transformRawCoords(t,n,e,o){const s=getBoxSize(n),i=[s[0]/this.meshWidth,s[1]/this.meshHeight],r=t.map(t=>[i[0]*(t[0]-this.meshWidth/2),i[1]*(t[1]-this.meshHeight/2),t[2]]),a=buildRotationMatrix(e,[0,0]),d=r.map(t=>{return[...rotatePoint(t,a),t[2]]}),u=invertTransformMatrix(o),c=[...getBoxCenter(n),1],h=[dot(c,u[0]),dot(c,u[1])];return d.map(t=>[t[0]+h[0],t[1]+h[1],t[2]])}async estimateHand(t){const n=this.shouldUpdateRegionsOfInterest();if(!0===n){const n=this.boundingBoxDetector.estimateHandBounds(t);if(null===n)return t.dispose(),this.regionsOfInterest=[],null;this.updateRegionsOfInterest(n,!0),this.runsWithoutHandDetector=0}else this.runsWithoutHandDetector++;const e=this.regionsOfInterest[0],o=computeRotation(e.palmLandmarks[PALM_LANDMARKS_INDEX_OF_PALM_BASE],e.palmLandmarks[PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE]),s=getBoxCenter(e),i=[s[0]/t.shape[2],s[1]/t.shape[1]];let r;const a=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["getBackend"])();if("webgl"===a)r=rotate$1(t,o,0,i);else{if("cpu"!==a)throw new Error(`Handpose is not yet supported by the ${a} `+"backend - rotation kernel is not defined.");r=rotate(t,o,0,i)}const d=buildRotationMatrix(-o,s);let u;const c=cutBoxFromImageAndResize(u=!0===n?this.getBoxForPalmLandmarks(e.palmLandmarks,d):e,r,[this.meshWidth,this.meshHeight]),h=c.div(255);c.dispose(),r.dispose();const l=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("WEBGL_PACK_DEPTHWISECONV");Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().set("WEBGL_PACK_DEPTHWISECONV",!0);const[m,p]=this.meshDetector.predict(h);Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().set("WEBGL_PACK_DEPTHWISECONV",l),h.dispose();const f=m.dataSync()[0];if(m.dispose(),f<this.detectionConfidence)return p.dispose(),this.regionsOfInterest=[],null;const _=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["reshape"])(p,[-1,3]),P=_.arraySync();p.dispose(),_.dispose();const g=this.transformRawCoords(P,u,o,d),M=this.getBoxForHandLandmarks(g);return this.updateRegionsOfInterest(M,!1),{landmarks:g,handInViewConfidence:f,boundingBox:{topLeft:M.startPoint,bottomRight:M.endPoint}}}calculateLandmarksBoundingBox(t){const n=t.map(t=>t[0]),e=t.map(t=>t[1]);return{startPoint:[Math.min(...n),Math.min(...e)],endPoint:[Math.max(...n),Math.max(...e)]}}updateRegionsOfInterest(t,n){if(n)this.regionsOfInterest=[t];else{const n=this.regionsOfInterest[0];let e=0;if(null!=n&&null!=n.startPoint){const[o,s]=t.startPoint,[i,r]=t.endPoint,[a,d]=n.startPoint,[u,c]=n.endPoint,h=Math.max(o,a),l=Math.max(s,d),m=(Math.min(i,u)-h)*(Math.min(r,c)-l);e=m/((i-o)*(r-s)+(u-a)*(c-s)-m)}this.regionsOfInterest[0]=e>UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD?n:t}}shouldUpdateRegionsOfInterest(){return this.regionsOfInterest.length!==this.maxHandsNumber||this.runsWithoutHandDetector>=this.maxContinuousChecks}}async function loadHandDetectorModel(){return Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])("https://tfhub.dev/mediapipe/tfjs-model/handdetector/1/default/1",{fromTFHub:!0})}const MESH_MODEL_INPUT_WIDTH=256,MESH_MODEL_INPUT_HEIGHT=256;async function loadHandPoseModel(){return Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])("https://tfhub.dev/mediapipe/tfjs-model/handskeleton/1/default/1",{fromTFHub:!0})}async function loadAnchors(){return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].fetch("https://tfhub.dev/mediapipe/tfjs-model/handskeleton/1/default/1/anchors.json?tfjs-format=file").then(t=>t.json())}async function load({maxContinuousChecks:t=1/0,detectionConfidence:n=.8,iouThreshold:e=.3,scoreThreshold:o=.5}={}){const[s,i,r]=await Promise.all([loadAnchors(),loadHandDetectorModel(),loadHandPoseModel()]),a=new HandDetector(i,MESH_MODEL_INPUT_WIDTH,MESH_MODEL_INPUT_HEIGHT,s,e,o),d=new HandPipeline(a,r,MESH_MODEL_INPUT_WIDTH,MESH_MODEL_INPUT_HEIGHT,t,n);return new HandPose(d)}function getInputTensorDimensions(t){return t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?[t.shape[0],t.shape[1]]:[t.height,t.width]}function flipHandHorizontal(t,n){const{handInViewConfidence:e,landmarks:o,boundingBox:s}=t;return{handInViewConfidence:e,landmarks:o.map(t=>[n-1-t[0],t[1],t[2]]),boundingBox:{topLeft:[n-1-s.topLeft[0],s.topLeft[1]],bottomRight:[n-1-s.bottomRight[0],s.bottomRight[1]]}}}class HandPose{constructor(t){this.pipeline=t}static getAnnotations(){return MESH_ANNOTATIONS}async estimateHands(t,n=!1){const[,e]=getInputTensorDimensions(t),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>(t instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]||(t=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(t)),t.toFloat().expandDims(0))),s=await this.pipeline.estimateHand(o);if(o.dispose(),null===s)return[];let i=s;!0===n&&(i=flipHandHorizontal(s,e));const r={};for(const t of Object.keys(MESH_ANNOTATIONS))r[t]=MESH_ANNOTATIONS[t].map(t=>i.landmarks[t]);return[{handInViewConfidence:i.handInViewConfidence,boundingBox:i.boundingBox,landmarks:i.landmarks,annotations:r}]}}
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _getPrototypeOf = __webpack_require__(98);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(97);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(96);
var _inherits3 = _interopRequireDefault(_inherits2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _handpose = __webpack_require__(293);
var handposeCore = _interopRequireWildcard(_handpose);
var _events = __webpack_require__(141);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2020 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
* Handpose: Palm detector and hand-skeleton finger tracking in the browser
* Ported and integrated from all the hard work by: https://github.com/tensorflow/tfjs-models/tree/master/handpose
*/
var Handpose = function (_EventEmitter) {
(0, _inherits3.default)(Handpose, _EventEmitter);
/**
* Create Handpose.
* @param {HTMLVideoElement} video - An HTMLVideoElement.
* @param {object} options - An object with options.
* @param {function} callback - A callback to be called when the model is ready.
*/
function Handpose(video, options, callback) {
(0, _classCallCheck3.default)(this, Handpose);
var _this = (0, _possibleConstructorReturn3.default)(this, (Handpose.__proto__ || (0, _getPrototypeOf2.default)(Handpose)).call(this));
_this.video = video;
_this.model = null;
_this.modelReady = false;
_this.config = options;
_this.ready = (0, _callcallback2.default)(_this.loadModel(), callback);
return _this;
}
/**
* Load the model and set it to this.model
* @return {this} the Handpose model.
*/
(0, _createClass3.default)(Handpose, [{
key: "loadModel",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this2 = this;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return handposeCore.load(this.config);
case 2:
this.model = _context.sent;
this.modelReady = true;
if (!(this.video && this.video.readyState === 0)) {
_context.next = 7;
break;
}
_context.next = 7;
return new _promise2.default(function (resolve) {
_this2.video.onloadeddata = function () {
resolve();
};
});
case 7:
this.predict();
return _context.abrupt("return", this);
case 9:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Load the model and set it to this.model
* @return {this} the Handpose model.
*/
}, {
key: "predict",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputOr, callback) {
var _this3 = this;
var input, flipHorizontal, predictions, result;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
input = this.getInput(inputOr);
if (input) {
_context2.next = 3;
break;
}
return _context2.abrupt("return", []);
case 3:
flipHorizontal = this.config.flipHorizontal;
_context2.next = 6;
return this.model.estimateHands(input, flipHorizontal);
case 6:
predictions = _context2.sent;
result = predictions;
this.emit("predict", result);
if (!this.video) {
_context2.next = 11;
break;
}
return _context2.abrupt("return", tf.nextFrame().then(function () {
return _this3.predict();
}));
case 11:
if (typeof callback === "function") {
callback(result);
}
return _context2.abrupt("return", result);
case 13:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function predict(_x, _x2) {
return _ref2.apply(this, arguments);
}
return predict;
}()
}, {
key: "getInput",
value: function getInput(inputOr) {
var input = void 0;
if (inputOr instanceof HTMLImageElement || inputOr instanceof HTMLVideoElement || inputOr instanceof HTMLCanvasElement || inputOr instanceof ImageData) {
input = inputOr;
} else if ((typeof inputOr === "undefined" ? "undefined" : (0, _typeof3.default)(inputOr)) === "object" && (inputOr.elt instanceof HTMLImageElement || inputOr.elt instanceof HTMLVideoElement || inputOr.elt instanceof ImageData)) {
input = inputOr.elt; // Handle p5.js image and video
} else if ((typeof inputOr === "undefined" ? "undefined" : (0, _typeof3.default)(inputOr)) === "object" && inputOr.canvas instanceof HTMLCanvasElement) {
input = inputOr.canvas; // Handle p5.js image
} else {
input = this.video;
}
return input;
}
}]);
return Handpose;
}(_events.EventEmitter);
var handpose = function handpose(videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object" && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object") {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === "function") {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object") {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === "function") {
callback = optionsOrCallback;
}
var instance = new Handpose(video, options, callback);
return callback ? instance : instance.ready;
};
exports.default = handpose;
/***/ }),
/* 295 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FaceMesh", function() { return FaceMesh; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
const disposeBox=e=>{e.startEndTensor.dispose(),e.startPoint.dispose(),e.endPoint.dispose()},createBox=e=>({startEndTensor:e,startPoint:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(e,[0,0],[-1,2]),endPoint:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(e,[0,2],[-1,2])}),scaleBox=(e,t)=>{const s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(e.startPoint,t),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(e.endPoint,t),n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([s,o],1);return createBox(n)},ANCHORS_CONFIG={strides:[8,16],anchors:[2,6]},NUM_LANDMARKS=6;function generateAnchors(e,t,s){const o=[];for(let n=0;n<s.strides.length;n++){const i=s.strides[n],r=Math.floor((t+i-1)/i),a=Math.floor((e+i-1)/i),c=s.anchors[n];for(let e=0;e<r;e++){const t=i*(e+.5);for(let e=0;e<a;e++){const s=i*(e+.5);for(let e=0;e<c;e++)o.push([s,t])}}}return o}function decodeBounds(e,t,s){const o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(e,[0,1],[-1,2]),n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(o,t),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(e,[0,3],[-1,2]),r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(i,s),a=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(n,s),c=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(r,2),l=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(a,c),d=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(a,c),h=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(l,s),u=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(d,s);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([h,u],1)}function getInputTensorDimensions(e){return e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?[e.shape[0],e.shape[1]]:[e.height,e.width]}function flipFaceHorizontal(e,t){let s,o,n;if(e.topLeft instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]&&e.bottomRight instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]){const[i,r]=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(t-1,e.topLeft.slice(0,1)),e.topLeft.slice(1,1)]),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(t-1,e.bottomRight.slice(0,1)),e.bottomRight.slice(1,1)])]);s=i,o=r,null!=e.landmarks&&(n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([t-1,0]),e.landmarks),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([1,-1]);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(s,o)}))}else{const[i,r]=e.topLeft,[a,c]=e.bottomRight;s=[t-1-i,r],o=[t-1-a,c],null!=e.landmarks&&(n=e.landmarks.map(e=>[t-1-e[0],e[1]]))}const i={topLeft:s,bottomRight:o};return null!=n&&(i.landmarks=n),null!=e.probability&&(i.probability=e.probability instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?e.probability.clone():e.probability),i}function scaleBoxFromPrediction(e,t){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{let s;return s=e.hasOwnProperty("box")?e.box:e,scaleBox(s,t).startEndTensor.squeeze()})}class BlazeFaceModel{constructor(e,t,s,o,n,i){this.blazeFaceModel=e,this.width=t,this.height=s,this.maxFaces=o,this.anchorsData=generateAnchors(t,s,ANCHORS_CONFIG),this.anchors=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(this.anchorsData),this.inputSizeData=[t,s],this.inputSize=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([t,s]),this.iouThreshold=n,this.scoreThreshold=i}async getBoundingBoxes(e,t,s=!0){const[o,n,i]=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const t=e.resizeBilinear([this.width,this.height]),s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(t.div(255),.5),2),o=this.blazeFaceModel.predict(s).squeeze(),n=decodeBounds(o,this.anchors,this.inputSize),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(o,[0,0],[-1,1]);return[o,n,Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sigmoid"])(i).squeeze()]}),r=console.warn;console.warn=(()=>{});const a=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].nonMaxSuppression(n,i,this.maxFaces,this.iouThreshold,this.scoreThreshold);console.warn=r;const c=await a.array();a.dispose();let l=c.map(e=>Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(n,[e,0],[1,-1]));t||(l=await Promise.all(l.map(async e=>{const t=await e.array();return e.dispose(),t})));const d=e.shape[1],h=e.shape[2];let u;u=t?Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])([h,d],this.inputSize):[h/this.inputSizeData[0],d/this.inputSizeData[1]];const p=[];for(let e=0;e<l.length;e++){const n=l[e],r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const r=createBox(n instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?n:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(n));if(!s)return r;const a=c[e];let l;return l=t?this.anchors.slice([a,0],[1,2]):this.anchorsData[a],{box:r,landmarks:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(o,[a,NUM_LANDMARKS-1],[1,-1]).squeeze().reshape([NUM_LANDMARKS,-1]),probability:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(i,[a],[1]),anchor:l}});p.push(r)}return n.dispose(),i.dispose(),o.dispose(),{boxes:p,scaleFactor:u}}async estimateFaces(e,t=!1,s=!1,o=!0){const[,n]=getInputTensorDimensions(e),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>(e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]||(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(e)),e.toFloat().expandDims(0))),{boxes:r,scaleFactor:a}=await this.getBoundingBoxes(i,t,o);return i.dispose(),t?r.map(e=>{const t=scaleBoxFromPrediction(e,a);let i={topLeft:t.slice([0],[2]),bottomRight:t.slice([2],[2])};if(o){const{landmarks:t,probability:s,anchor:o}=e,n=t.add(o).mul(a);i.landmarks=n,i.probability=s}return s&&(i=flipFaceHorizontal(i,n)),i}):Promise.all(r.map(async e=>{const t=scaleBoxFromPrediction(e,a);let i;if(o){const[s,o,n]=await Promise.all([e.landmarks,t,e.probability].map(async e=>e.array())),r=e.anchor,[c,l]=a,d=s.map(e=>[(e[0]+r[0])*c,(e[1]+r[1])*l]);i={topLeft:o.slice(0,2),bottomRight:o.slice(2),landmarks:d,probability:n},disposeBox(e.box),e.landmarks.dispose(),e.probability.dispose()}else{const e=await t.array();i={topLeft:e.slice(0,2),bottomRight:e.slice(2)}}return t.dispose(),s&&(i=flipFaceHorizontal(i,n)),i}))}}const BLAZEFACE_MODEL_URL="https://tfhub.dev/tensorflow/tfjs-model/blazeface/1/default/1";async function load({maxFaces:e=10,inputWidth:t=128,inputHeight:s=128,iouThreshold:o=.3,scoreThreshold:n=.75}={}){const i=await Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])(BLAZEFACE_MODEL_URL,{fromTFHub:!0});return new BlazeFaceModel(i,t,s,e,o,n)}const MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]};function disposeBox$1(e){null!=e&&null!=e.startPoint&&(e.startEndTensor.dispose(),e.startPoint.dispose(),e.endPoint.dispose())}function createBox$1(e,t,s){return{startEndTensor:e,startPoint:null!=t?t:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(e,[0,0],[-1,2]),endPoint:null!=s?s:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice"])(e,[0,2],[-1,2])}}function scaleBoxCoordinates(e,t){const s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(e.startPoint,t),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(e.endPoint,t);return createBox$1(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([s,o],1))}function getBoxSize(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const t=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(e.endPoint,e.startPoint);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["abs"])(t)})}function getBoxCenter(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const t=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(e.endPoint,e.startPoint),2);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(e.startPoint,t)})}function cutBoxFromImageAndResize(e,t,s){const o=t.shape[1],n=t.shape[2],i=e.startEndTensor;return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const e=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([i.slice([0,1],[-1,1]),i.slice([0,0],[-1,1]),i.slice([0,3],[-1,1]),i.slice([0,2],[-1,1])],0),r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(e.transpose(),[o,n,o,n]);return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["image"].cropAndResize(t,r,[0],s)})}function enlargeBox(e,t=1.5){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const s=getBoxCenter(e),o=getBoxSize(e),n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(o,2),t),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(s,n),r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["add"])(s,n);return createBox$1(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat2d"])([i,r],1),i,r)})}const LANDMARKS_COUNT=468,UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD=.25;class Pipeline{constructor(e,t,s,o,n,i){this.regionsOfInterest=[],this.runsWithoutFaceDetector=0,this.boundingBoxDetector=e,this.meshDetector=t,this.meshWidth=s,this.meshHeight=o,this.maxContinuousChecks=n,this.maxFaces=i}async predict(e){if(this.shouldUpdateRegionsOfInterest()){const t=!0,s=!1,{boxes:o,scaleFactor:n}=await this.boundingBoxDetector.getBoundingBoxes(e,t,s);if(0===o.length)return n.dispose(),this.clearAllRegionsOfInterest(),null;const i=o.map(e=>enlargeBox(scaleBoxCoordinates(e,n)));o.forEach(disposeBox$1),this.updateRegionsOfInterest(i),this.runsWithoutFaceDetector=0}else this.runsWithoutFaceDetector++;return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>this.regionsOfInterest.map((t,s)=>{const o=cutBoxFromImageAndResize(t,e,[this.meshHeight,this.meshWidth]).div(255),[,n,i]=this.meshDetector.predict(o),r=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["reshape"])(i,[-1,3]),a=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(getBoxSize(t),[this.meshWidth,this.meshHeight]),c=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["mul"])(r,a.concat(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])([1],[1,1]),1)).add(t.startPoint.concat(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])([0],[1,1]),1)),l=this.calculateLandmarksBoundingBox(c);return disposeBox$1(this.regionsOfInterest[s]),this.regionsOfInterest[s]=l,{coords:r,scaledCoords:c,box:l,flag:n.squeeze()}}))}updateRegionsOfInterest(e){for(let t=0;t<e.length;t++){const s=e[t],o=this.regionsOfInterest[t];let n=0;if(o&&o.startPoint){const[e,t,i,r]=s.startEndTensor.arraySync()[0],[a,c,l,d]=o.startEndTensor.arraySync()[0],h=Math.max(e,a),u=Math.max(t,c),p=(Math.min(i,l)-h)*(Math.min(r,d)-u);n=p/((i-e)*(r-t)+(l-a)*(d-t)-p)}n>UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD?disposeBox$1(s):(this.regionsOfInterest[t]=s,disposeBox$1(o))}for(let t=e.length;t<this.regionsOfInterest.length;t++)disposeBox$1(this.regionsOfInterest[t]);this.regionsOfInterest=this.regionsOfInterest.slice(0,e.length)}clearRegionOfInterest(e){null!=this.regionsOfInterest[e]&&(disposeBox$1(this.regionsOfInterest[e]),this.regionsOfInterest=[...this.regionsOfInterest.slice(0,e),...this.regionsOfInterest.slice(e+1)])}clearAllRegionsOfInterest(){for(let e=0;e<this.regionsOfInterest.length;e++)disposeBox$1(this.regionsOfInterest[e]);this.regionsOfInterest=[]}shouldUpdateRegionsOfInterest(){const e=this.regionsOfInterest.length,t=0===e;return 1===this.maxFaces||t?t:e!==this.maxFaces&&this.runsWithoutFaceDetector>=this.maxContinuousChecks}calculateLandmarksBoundingBox(e){const t=e.slice([0,0],[LANDMARKS_COUNT,1]),s=e.slice([0,1],[LANDMARKS_COUNT,1]);return enlargeBox(createBox$1(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["stack"])([t.min(),s.min(),t.max(),s.max()]).expandDims(0)))}}const UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]],FACEMESH_GRAPHMODEL_PATH="https://tfhub.dev/mediapipe/tfjs-model/facemesh/1/default/1",MESH_MODEL_INPUT_WIDTH=192,MESH_MODEL_INPUT_HEIGHT=192;async function load$1({maxContinuousChecks:e=5,detectionConfidence:t=.9,maxFaces:s=10,iouThreshold:o=.3,scoreThreshold:n=.75}={}){const[i,r]=await Promise.all([loadDetectorModel(s,o,n),loadMeshModel()]);return new FaceMesh(i,r,e,t,s)}async function loadDetectorModel(e,t,s){return load({maxFaces:e,iouThreshold:t,scoreThreshold:s})}async function loadMeshModel(){return Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])(FACEMESH_GRAPHMODEL_PATH,{fromTFHub:!0})}function getInputTensorDimensions$1(e){return e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?[e.shape[0],e.shape[1]]:[e.height,e.width]}function flipFaceHorizontal$1(e,t){if(e.mesh instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]){const[s,o,n,i]=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>{const s=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([t-1,0,0]),o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])([1,-1,1]);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>[Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(t-1,e.boundingBox.topLeft.slice(0,1)),e.boundingBox.topLeft.slice(1,1)]),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(t-1,e.boundingBox.bottomRight.slice(0,1)),e.boundingBox.bottomRight.slice(1,1)]),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(s,e.mesh).mul(o),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(s,e.scaledMesh).mul(o)])});return Object.assign({},e,{boundingBox:{topLeft:s,bottomRight:o},mesh:n,scaledMesh:i})}return Object.assign({},e,{boundingBox:{topLeft:[t-1-e.boundingBox.topLeft[0],e.boundingBox.topLeft[1]],bottomRight:[t-1-e.boundingBox.bottomRight[0],e.boundingBox.bottomRight[1]]},mesh:e.mesh.map(e=>{const s=e.slice(0);return s[0]=t-1-e[0],s}),scaledMesh:e.scaledMesh.map(e=>{const s=e.slice(0);return s[0]=t-1-e[0],s})})}class FaceMesh{constructor(e,t,s,o,n){this.pipeline=new Pipeline(e,t,MESH_MODEL_INPUT_WIDTH,MESH_MODEL_INPUT_HEIGHT,s,n),this.detectionConfidence=o}static getAnnotations(){return MESH_ANNOTATIONS}static getUVCoords(){return UV_COORDS}async estimateFaces(e,t=!1,s=!1){const[,o]=getInputTensorDimensions$1(e),n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(()=>(e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]||(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(e)),e.toFloat().expandDims(0))),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().get("WEBGL_PACK_DEPTHWISECONV");Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().set("WEBGL_PACK_DEPTHWISECONV",!0);const r=await this.pipeline.predict(n);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["env"])().set("WEBGL_PACK_DEPTHWISECONV",i),n.dispose(),null!=r&&r.length>0?Promise.all(r.map(async(e,n)=>{const{coords:i,scaledCoords:r,box:a,flag:c}=e;let l=[c];t||(l=l.concat([i,r,a.startPoint,a.endPoint]));const d=await Promise.all(l.map(async e=>e.array())),h=d[0];if(c.dispose(),h<this.detectionConfidence&&this.pipeline.clearRegionOfInterest(n),t){const e={faceInViewConfidence:h,mesh:i,scaledMesh:r,boundingBox:{topLeft:a.startPoint.squeeze(),bottomRight:a.endPoint.squeeze()}};return s?flipFaceHorizontal$1(e,o):e}const[u,p,f,m]=d.slice(1);r.dispose(),i.dispose();let g={faceInViewConfidence:h,boundingBox:{topLeft:f,bottomRight:m},mesh:u,scaledMesh:p};s&&(g=flipFaceHorizontal$1(g,o));const b={};for(const e in MESH_ANNOTATIONS)b[e]=MESH_ANNOTATIONS[e].map(e=>g.scaledMesh[e]);return g.annotations=b,g})):[]}}
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _getPrototypeOf = __webpack_require__(98);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(97);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(96);
var _inherits3 = _interopRequireDefault(_inherits2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _facemesh = __webpack_require__(295);
var facemeshCore = _interopRequireWildcard(_facemesh);
var _events = __webpack_require__(141);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2020 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
* Facemesh: Facial landmark detection in the browser
* Ported and integrated from all the hard work by: https://github.com/tensorflow/tfjs-models/tree/master/facemesh
*/
var Facemesh = function (_EventEmitter) {
(0, _inherits3.default)(Facemesh, _EventEmitter);
/**
* Create Facemesh.
* @param {HTMLVideoElement} video - An HTMLVideoElement.
* @param {object} options - An object with options.
* @param {function} callback - A callback to be called when the model is ready.
*/
function Facemesh(video, options, callback) {
(0, _classCallCheck3.default)(this, Facemesh);
var _this = (0, _possibleConstructorReturn3.default)(this, (Facemesh.__proto__ || (0, _getPrototypeOf2.default)(Facemesh)).call(this));
_this.video = video;
_this.model = null;
_this.modelReady = false;
_this.config = options;
_this.ready = (0, _callcallback2.default)(_this.loadModel(), callback);
return _this;
}
/**
* Load the model and set it to this.model
* @return {this} the Facemesh model.
*/
(0, _createClass3.default)(Facemesh, [{
key: "loadModel",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this2 = this;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return facemeshCore.load(this.config);
case 2:
this.model = _context.sent;
this.modelReady = true;
if (!(this.video && this.video.readyState === 0)) {
_context.next = 7;
break;
}
_context.next = 7;
return new _promise2.default(function (resolve) {
_this2.video.onloadeddata = function () {
resolve();
};
});
case 7:
this.predict();
return _context.abrupt("return", this);
case 9:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Load the model and set it to this.model
* @return {this} the Facemesh model.
*/
}, {
key: "predict",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputOr, callback) {
var _this3 = this;
var input, flipHorizontal, predictions, result;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
input = this.getInput(inputOr);
flipHorizontal = this.config.flipHorizontal;
_context2.next = 4;
return this.model.estimateFaces(input, flipHorizontal);
case 4:
predictions = _context2.sent;
result = predictions;
this.emit("predict", result);
if (!this.video) {
_context2.next = 9;
break;
}
return _context2.abrupt("return", tf.nextFrame().then(function () {
return _this3.predict();
}));
case 9:
if (typeof callback === "function") {
callback(result);
}
return _context2.abrupt("return", result);
case 11:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function predict(_x, _x2) {
return _ref2.apply(this, arguments);
}
return predict;
}()
}, {
key: "getInput",
value: function getInput(inputOr) {
var input = void 0;
if (inputOr instanceof HTMLImageElement || inputOr instanceof HTMLVideoElement || inputOr instanceof HTMLCanvasElement || inputOr instanceof ImageData) {
input = inputOr;
} else if ((typeof inputOr === "undefined" ? "undefined" : (0, _typeof3.default)(inputOr)) === "object" && (inputOr.elt instanceof HTMLImageElement || inputOr.elt instanceof HTMLVideoElement || inputOr.elt instanceof ImageData)) {
input = inputOr.elt; // Handle p5.js image and video
} else if ((typeof inputOr === "undefined" ? "undefined" : (0, _typeof3.default)(inputOr)) === "object" && inputOr.canvas instanceof HTMLCanvasElement) {
input = inputOr.canvas; // Handle p5.js image
} else {
input = this.video;
}
return input;
}
}]);
return Facemesh;
}(_events.EventEmitter);
var facemesh = function facemesh(videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object" && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object") {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === "function") {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object") {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === "function") {
callback = optionsOrCallback;
}
var instance = new Facemesh(video, options, callback);
return callback ? instance : instance.ready;
};
exports.default = facemesh;
/***/ }),
/* 297 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadTokenizer", function() { return loadTokenizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniversalSentenceEncoder", function() { return UniversalSentenceEncoder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tokenizer", function() { return Tokenizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20);
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/**
* @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.
* =============================================================================
*/
function __awaiter(e,r,n,t){return new(n||(n=Promise))(function(o,i){function a(e){try{u(t.next(e))}catch(e){i(e)}}function s(e){try{u(t.throw(e))}catch(e){i(e)}}function u(e){e.done?o(e.value):new n(function(r){r(e.value)}).then(a,s)}u((t=t.apply(e,r||[])).next())})}function __generator(e,r){var n,t,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,t&&(o=2&i[0]?t.return:i[0]?t.throw||((o=t.return)&&o.call(t),0):t.next)&&!(o=o.call(t,i[1])).done)return o;switch(t=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,t=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=r.call(e,a)}catch(e){i=[6,e],t=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}var stringToChars=function(e){for(var r=[],n=0,t=e;n<t.length;n++){var o=t[n];r.push(o)}return r},TrieNode=function(){return function(){this.parent=null,this.children={},this.end=!1,this.word=[[],0,0]}}(),Trie=function(){function e(){this.root=new TrieNode}return e.prototype.insert=function(e,r,n){for(var t=this.root,o=stringToChars(e),i=0;i<o.length;i++)t.children[o[i]]||(t.children[o[i]]=new TrieNode,t.children[o[i]].parent=t,t.children[o[i]].word[0]=t.word[0].concat(o[i])),t=t.children[o[i]],i===o.length-1&&(t.end=!0,t.word[1]=r,t.word[2]=n)},e.prototype.commonPrefixSearch=function(e){for(var r=[],n=this.root.children[e[0]],t=0;t<e.length&&n;t++)n.end&&r.push(n.word),n=n.children[e[t+1]];return r.length||r.push([[e[0]],0,0]),r},e}(),separator="▁";function processInput(e){var r=e.normalize("NFKC");return separator+r.replace(/ /g,separator)}var RESERVED_SYMBOLS_COUNT=6,Tokenizer=function(){function e(e){this.vocabulary=e,this.trie=new Trie;for(var r=RESERVED_SYMBOLS_COUNT;r<this.vocabulary.length;r++)this.trie.insert(this.vocabulary[r][0],this.vocabulary[r][1],r)}return e.prototype.encode=function(e){var r=[],n=[],t=[];e=processInput(e);for(var o=stringToChars(e),i=0;i<=o.length;i++)r.push({}),n.push(0),t.push(0);for(i=0;i<o.length;i++)for(var a=this.trie.commonPrefixSearch(o.slice(i)),s=0;s<a.length;s++){var u=a[s],c={key:u[0],score:u[1],index:u[2]};null==r[i+(l=u[0].length)][i]&&(r[i+l][i]=[]),r[i+l][i].push(c)}for(var l=0;l<=o.length;l++)for(var h in r[l]){var f=r[l][h];for(s=0;s<f.length;s++){var d=f[s],p=d.score+t[l-d.key.length];(0===t[l]||p>=t[l])&&(t[l]=p,n[l]=f[s].index)}}for(var v=[],w=n.length-1;w>0;)v.push(n[w]),w-=this.vocabulary[n[w]][0].length;var g=[],_=!1;for(i=0;i<v.length;i++){var y=v[i];_&&0===y||g.push(y),_=0===y}return g.reverse()},e}(),version="1.2.2",BASE_PATH="https://storage.googleapis.com/tfjs-models/savedmodel/universal_sentence_encoder/";function load(){return __awaiter(this,void 0,void 0,function(){var e;return __generator(this,function(r){switch(r.label){case 0:return[4,(e=new UniversalSentenceEncoder).load()];case 1:return r.sent(),[2,e]}})})}function loadTokenizer(e){return __awaiter(this,void 0,void 0,function(){var r;return __generator(this,function(n){switch(n.label){case 0:return[4,loadVocabulary(e)];case 1:return r=n.sent(),[2,new Tokenizer(r)]}})})}function loadVocabulary(e){return void 0===e&&(e=BASE_PATH+"vocab.json"),__awaiter(this,void 0,void 0,function(){return __generator(this,function(r){switch(r.label){case 0:return[4,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["util"].fetch(e)];case 1:return[2,r.sent().json()]}})})}var UniversalSentenceEncoder=function(){function e(){}return e.prototype.loadModel=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return[2,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__[/* loadGraphModel */ "c"])("https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder-lite/1/default/1",{fromTFHub:!0})]})})},e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e,r,n;return __generator(this,function(t){switch(t.label){case 0:return[4,Promise.all([this.loadModel(),loadVocabulary()])];case 1:return e=t.sent(),r=e[0],n=e[1],this.model=r,this.tokenizer=new Tokenizer(n),[2]}})})},e.prototype.embed=function(e){return __awaiter(this,void 0,void 0,function(){var r,n,t,o,i,a,s,u=this;return __generator(this,function(c){switch(c.label){case 0:for("string"==typeof e&&(e=[e]),r=e.map(function(e){return u.tokenizer.encode(e)}),n=r.map(function(e,r){return e.map(function(e,n){return[r,n]})}),t=[],o=0;o<n.length;o++)t=t.concat(n[o]);return i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tensor2d"])(t,[t.length,2],"int32"),a=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tensor1d"])(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["util"].flatten(r),"int32"),[4,this.model.executeAsync({indices:i,values:a})];case 1:return s=c.sent(),i.dispose(),a.dispose(),[2,s]}})})},e}();
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _universalSentenceEncoder = __webpack_require__(297);
var USE = _interopRequireWildcard(_universalSentenceEncoder);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import * as tf from '@tensorflow/tfjs';
var DEFAULTS = {
withTokenizer: false
};
var UniversalSentenceEncoder = function () {
function UniversalSentenceEncoder(options, callback) {
(0, _classCallCheck3.default)(this, UniversalSentenceEncoder);
this.model = null;
this.tokenizer = null;
this.config = {
withTokenizer: options.withTokenizer || DEFAULTS.withTokenizer
};
(0, _callcallback2.default)(this.loadModel(), callback);
}
/**
* load model
*/
(0, _createClass3.default)(UniversalSentenceEncoder, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(this.config.withTokenizer === true)) {
_context.next = 4;
break;
}
_context.next = 3;
return USE.loadTokenizer();
case 3:
this.tokenizer = _context.sent;
case 4:
_context.next = 6;
return USE.load();
case 6:
this.model = _context.sent;
return _context.abrupt('return', this);
case 8:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Encodes a string or array based on the USE
* @param {*} textString
* @param {*} callback
*/
}, {
key: 'predict',
value: function predict(textArray, callback) {
return (0, _callcallback2.default)(this.predictInternal(textArray), callback);
}
}, {
key: 'predictInternal',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(textArray) {
var embeddings, results;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return this.model.embed(textArray);
case 3:
embeddings = _context2.sent;
_context2.next = 6;
return embeddings.array();
case 6:
results = _context2.sent;
embeddings.dispose();
return _context2.abrupt('return', results);
case 11:
_context2.prev = 11;
_context2.t0 = _context2['catch'](0);
console.error(_context2.t0);
return _context2.abrupt('return', _context2.t0);
case 15:
case 'end':
return _context2.stop();
}
}
}, _callee2, this, [[0, 11]]);
}));
function predictInternal(_x) {
return _ref2.apply(this, arguments);
}
return predictInternal;
}()
/**
* Encodes a string based on the loaded tokenizer if the withTokenizer:true
* @param {*} textString
* @param {*} callback
*/
}, {
key: 'encode',
value: function encode(textString, callback) {
return (0, _callcallback2.default)(this.encodeInternal(textString), callback);
}
}, {
key: 'encodeInternal',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(textString) {
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(this.config.withTokenizer === true)) {
_context3.next = 2;
break;
}
return _context3.abrupt('return', this.tokenizer.encode(textString));
case 2:
console.error('withTokenizer must be set to true - please pass "withTokenizer:true" as an option in the constructor');
return _context3.abrupt('return', false);
case 4:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function encodeInternal(_x2) {
return _ref3.apply(this, arguments);
}
return encodeInternal;
}()
}]);
return UniversalSentenceEncoder;
}();
var universalSentenceEncoder = function universalSentenceEncoder(optionsOr, cb) {
var options = (typeof optionsOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOr)) === 'object' ? optionsOr : {};
var callback = typeof optionsOr === 'function' ? optionsOr : cb;
return new UniversalSentenceEncoder(options, callback);
};
exports.default = universalSentenceEncoder;
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _p5Utils = __webpack_require__(83);
var _p5Utils2 = _interopRequireDefault(_p5Utils);
var _imageUtilities = __webpack_require__(46);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
* CartoonGAN: see details about the [paper](http://openaccess.thecvf.com/content_cvpr_2018/papers/Chen_CartoonGAN_Generative_Adversarial_CVPR_2018_paper.pdf)
*/
var IMAGE_SIZE = 256;
var modelPath = {
'hosoda': 'https://raw.githubusercontent.com/leemengtaiwan/tfjs-models/master/cartoongan/tfjs_json_models/hosoda/model.json',
'miyazaki': 'https://raw.githubusercontent.com/Derek-Wds/training_CartoonGAN/master/tfModels/Miyazaki/model.json'
};
var Cartoon = function () {
/**
* Create a CartoonGan model.
* @param {String} modelIdentifier - Required. The name of pre-inluded model or the url path to your model.
* @param {function} callback - Required. A function to run once the model has been loaded.
*/
function Cartoon(options, callback) {
(0, _classCallCheck3.default)(this, Cartoon);
this.config = {
modelUrl: options.modelUrl ? options.modelUrl : modelPath.miyazaki,
returnTensors: options.returnTensors ? options.returnTensors : false
};
this.model = {};
this.ready = false;
this.ready = (0, _callcallback2.default)(this.loadModel(this.config.modelUrl), callback);
}
/* load tfjs model that is converted by tensorflowjs with graph and weights */
(0, _createClass3.default)(Cartoon, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(modelUrl) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return tf.loadGraphModel(modelUrl);
case 2:
this.model = _context.sent;
return _context.abrupt('return', this);
case 4:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel(_x) {
return _ref.apply(this, arguments);
}
return loadModel;
}()
// todo: add p5 image support as input
/**
* generate an img based on input Image.
* @param {HTMLImageElement | HTMLCanvasElement} src the source img you want to transfer.
* @param {function} callback
*/
}, {
key: 'generate',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputOrCallback, cb) {
var imgToPredict, callback;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
imgToPredict = void 0;
callback = cb;
if (!(0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback)) {
_context2.next = 6;
break;
}
imgToPredict = inputOrCallback;
_context2.next = 20;
break;
case 6:
if (!((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === "object" && (0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback.elt))) {
_context2.next = 10;
break;
}
imgToPredict = inputOrCallback.elt; // Handle p5.js image and video.
_context2.next = 20;
break;
case 10:
if (!((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === "object" && (0, _imageUtilities.isInstanceOfSupportedElement)(inputOrCallback.canvas))) {
_context2.next = 14;
break;
}
imgToPredict = inputOrCallback.canvas; // Handle p5.js image and video.
_context2.next = 20;
break;
case 14:
if (!(typeof inputOrCallback === "function")) {
_context2.next = 19;
break;
}
imgToPredict = this.video;
callback = inputOrCallback;
_context2.next = 20;
break;
case 19:
throw new Error('Detection subject not supported');
case 20:
return _context2.abrupt('return', (0, _callcallback2.default)(this.generateInternal(imgToPredict), callback));
case 21:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function generate(_x2, _x3) {
return _ref2.apply(this, arguments);
}
return generate;
}()
}, {
key: 'generateInternal',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(src) {
var img, alpha, res, result;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.ready;
case 2:
_context3.next = 4;
return tf.nextFrame();
case 4:
// adds resizeBilinear to resize image to 256x256 as required by the model
img = tf.browser.fromPixels(src).resizeBilinear([IMAGE_SIZE, IMAGE_SIZE]);
if (!(img.shape[0] !== IMAGE_SIZE || img.shape[1] !== IMAGE_SIZE)) {
_context3.next = 9;
break;
}
throw new Error('Input size should be ' + IMAGE_SIZE + '*' + IMAGE_SIZE + ' but ' + img.shape + ' is found');
case 9:
if (!(img.shape[2] !== 3)) {
_context3.next = 11;
break;
}
throw new Error('Input color channel number should be 3 but ' + img.shape[2] + ' is found');
case 11:
img = img.sub(127.5).div(127.5).reshape([1, IMAGE_SIZE, IMAGE_SIZE, 3]);
alpha = tf.ones([IMAGE_SIZE, IMAGE_SIZE, 1]).tile([1, 1, 1]).mul(255);
res = this.model.predict(img);
res = res.add(1).mul(127.5).reshape([IMAGE_SIZE, IMAGE_SIZE, 3]).floor();
res = res.concat(alpha, 2);
result = this.resultFinalize(res);
if (!this.config.returnTensors) {
_context3.next = 19;
break;
}
return _context3.abrupt('return', result);
case 19:
img.dispose();
res.dispose();
return _context3.abrupt('return', result);
case 22:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function generateInternal(_x4) {
return _ref3.apply(this, arguments);
}
return generateInternal;
}()
/* eslint class-methods-use-this: "off" */
}, {
key: 'resultFinalize',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(res) {
var tensor, raw, blob, image;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
tensor = res;
_context4.next = 3;
return res.data();
case 3:
raw = _context4.sent;
_context4.next = 6;
return _p5Utils2.default.rawToBlob(raw, res.shape[0], res.shape[1]);
case 6:
blob = _context4.sent;
_context4.next = 9;
return _p5Utils2.default.blobToP5Image(blob);
case 9:
image = _context4.sent;
if (!this.config.returnTensors) {
_context4.next = 12;
break;
}
return _context4.abrupt('return', { tensor: tensor, raw: raw, blob: blob, image: image });
case 12:
return _context4.abrupt('return', { raw: raw, blob: blob, image: image });
case 13:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function resultFinalize(_x5) {
return _ref4.apply(this, arguments);
}
return resultFinalize;
}()
}]);
return Cartoon;
}();
var cartoon = function cartoon(optionsOr, cb) {
var options = (typeof optionsOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOr)) === 'object' ? optionsOr : {};
var callback = typeof optionsOr === 'function' ? optionsOr : cb;
if (typeof optionsOr === 'string') {
options.modelUrl = optionsOr;
}
return new Cartoon(options, callback);
};
exports.default = cartoon;
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _values = __webpack_require__(208);
var _values2 = _interopRequireDefault(_values);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
/**
* Read in a csv file from a path to its location.
* @param {string} path
*/
var readCsv = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(path) {
var myCsv, loadedData;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
myCsv = tf.data.csv(path);
_context.next = 3;
return myCsv.toArray();
case 3:
loadedData = _context.sent;
return _context.abrupt('return', loadedData);
case 5:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function readCsv(_x) {
return _ref.apply(this, arguments);
};
}();
/**
* Load and flatten an array of arrays, an array of objects, or a string
* path to a csv.
* @param {string || array || object} inputData
*/
var loadDataset = function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputData) {
var data, dataFlat;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
data = void 0;
if (!(typeof inputData === 'string')) {
_context2.next = 7;
break;
}
_context2.next = 4;
return readCsv(inputData);
case 4:
data = _context2.sent;
_context2.next = 8;
break;
case 7:
data = inputData;
case 8:
dataFlat = data.map(function (d) {
return (0, _values2.default)(d);
});
return _context2.abrupt('return', dataFlat);
case 10:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function loadDataset(_x2) {
return _ref2.apply(this, arguments);
};
}();
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _random = __webpack_require__(198);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
'k': 3,
'maxIter': 5,
'threshold': 0.5
}; // Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint "no-param-reassign": [2, { "props": false }] */
/*
K-Means Algorithm (with Euclidian distance).
*/
var KMeans = function () {
/**
* Create a K-Means.
* @param {String || array || object} dataset - The dataset to cluster.
* @param {options} options - An object describing a model's parameters:
* - k: number of clusters
* - maxIter: Max number of iterations to try before forcing convergence.
* - threshold: Threshold for updated centriod distance before declaring convergence.
* @param {function} callback - Optional. A callback to be called once
* the model has loaded. If no callback is provided, it will return a
* promise that will be resolved once the model has loaded.
*/
function KMeans(dataset, options, callback) {
(0, _classCallCheck3.default)(this, KMeans);
this.config = {
k: options.k || DEFAULTS.k,
maxIter: options.maxIter || DEFAULTS.maxIter,
threshold: options.threshold || DEFAULTS.threshold
};
this.ready = (0, _callcallback2.default)(this.load(dataset), callback);
}
/**
* Load dataset, find initial centroids, and run model.
* @param {string || array || object} dataset
*/
(0, _createClass3.default)(KMeans, [{
key: 'load',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(dataset) {
var _this = this;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return loadDataset(dataset);
case 2:
this.dataset = _context3.sent;
tf.tidy(function () {
_this.dataTensor = tf.tensor2d(_this.dataset);
_this.dataset.forEach(function (d) {
var tensors = tf.tensor1d((0, _values2.default)(d));
d.tensor = tensors;
});
_this.centroids = tf.tensor2d((0, _random.randomSample)(_this.dataset, _this.config.k, false));
_this.fit();
});
return _context3.abrupt('return', this);
case 5:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function load(_x3) {
return _ref3.apply(this, arguments);
}
return load;
}()
/**
* Run K-Means algorithm.
*/
}, {
key: 'fit',
value: function fit() {
this.getClosestCentroids();
this.recenterCentroids();
var centroidDistance = KMeans.getEuclidianDistance(this.centroids, this.centroidsOld);
var iteration = 0;
while (centroidDistance > this.config.threshold && iteration < this.config.maxIter) {
this.getClosestCentroids();
this.recenterCentroids();
centroidDistance = KMeans.getEuclidianDistance(this.centroids, this.centroidsOld);
iteration += 1;
}
}
/**
* Find closest centroids to each observation and store as attribute.
*/
}, {
key: 'getClosestCentroids',
value: function getClosestCentroids() {
var _this2 = this;
// find closest initial tensor
this.dataset.forEach(function (d) {
var minCentroid = _this2.closestCentroid(d.tensor);
d.centroid = minCentroid;
});
}
/**
* Load and flatten an array of arrays, an array of objects, or a string
* path to a csv.
* @param {string || array || object} inputData
*/
}, {
key: 'closestCentroid',
value: function closestCentroid(dataTensor) {
var _this3 = this;
return tf.tidy(function () {
var dist = _this3.centroids.squaredDifference(dataTensor).sum(1).sqrt();
var minCentroid = dist.argMin().arraySync();
return minCentroid;
});
}
/**
* Assing `value` to a cluster.
* @param {array || object} value
*/
}, {
key: 'classify',
value: function classify(value) {
var _this4 = this;
return tf.tidy(function () {
// input must be array or object
var valueTensor = tf.tensor1d((0, _values2.default)(value));
var minCentroid = _this4.closestCentroid(valueTensor);
return minCentroid;
});
}
/**
* Recenter each centroid.
*/
}, {
key: 'recenterCentroids',
value: function recenterCentroids() {
var _this5 = this;
// store previous run's centroids for convergence
// recenter each centroid
var result = tf.tidy(function () {
_this5.centroidsOld = _this5.centroids;
return tf.stack(_this5.centroids.unstack().map(function (centroid, k) {
// subset centroid to its cluster
var centroidK = _this5.dataset.filter(function (d) {
return d.centroid === k;
});
// conver to tensor
var centroidKTensor = centroidK.map(function (d) {
return d.tensor;
});
if (centroidKTensor.length === 0) {
return centroid;
} else if (centroidKTensor.length === 1) {
return centroidKTensor[0];
}
// grab mean for for cluster
var newCentroids = tf.tidy(function () {
return tf.stack(centroidKTensor).mean(0);
});
return newCentroids;
}));
});
this.centroids = result;
}
/**
* Calculate the Euclidian distance between two tensors.
* @param {tf.tensor} tensor1
* @param {tf.tensor} tensor2
*/
}], [{
key: 'getEuclidianDistance',
value: function getEuclidianDistance(tensor1, tensor2) {
// calculate euclidian distance between two arrays
var distTensor = tf.tidy(function () {
var distance = tf.squaredDifference(tensor1, tensor2).sum().sqrt();
return distance.dataSync();
});
return distTensor[0];
}
}]);
return KMeans;
}();
var kmeans = function kmeans(dataset, options, callback) {
return new KMeans(dataset, options, callback);
};
exports.default = kmeans;
/***/ }),
/* 301 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 302 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 303 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign = __webpack_require__(89);
var _assign2 = _interopRequireDefault(_assign);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _faceApi = __webpack_require__(290);
var faceapi = _interopRequireWildcard(_faceApi);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
withLandmarks: true,
withDescriptors: true,
minConfidence: 0.5,
withTinyNet: true,
MODEL_URLS: {
Mobilenetv1Model: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/face-api/models/faceapi/ssd_mobilenetv1_model-weights_manifest.json",
TinyFaceDetectorModel: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/face-api/models/faceapi/tiny_face_detector_model-weights_manifest.json",
FaceLandmarkModel: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/face-api/models/faceapi/face_landmark_68_model-weights_manifest.json",
FaceLandmark68TinyNet: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/face-api/models/faceapi/face_landmark_68_tiny_model-weights_manifest.json",
FaceRecognitionModel: "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/face-api/models/faceapi/face_recognition_model-weights_manifest.json"
}
}; // Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
* FaceApi: real-time face recognition, and landmark detection
* Ported and integrated from all the hard work by: https://github.com/justadudewhohacks/face-api.js?files=1
*/
var FaceApiBase = function () {
/**
* Create FaceApi.
* @param {HTMLVideoElement} video - An HTMLVideoElement.
* @param {object} options - An object with options.
* @param {function} callback - A callback to be called when the model is ready.
*/
function FaceApiBase(video, options, callback) {
(0, _classCallCheck3.default)(this, FaceApiBase);
this.video = video;
this.model = null;
this.modelReady = false;
this.detectorOptions = null;
this.config = {
minConfidence: this.checkUndefined(options.minConfidence, DEFAULTS.minConfidence),
withLandmarks: this.checkUndefined(options.withLandmarks, DEFAULTS.withLandmarks),
withDescriptors: this.checkUndefined(options.withDescriptors, DEFAULTS.withDescriptors),
withTinyNet: this.checkUndefined(options.withTinyNet, DEFAULTS.withTinyNet),
MODEL_URLS: {
Mobilenetv1Model: this.checkUndefined(options.Mobilenetv1Model, DEFAULTS.MODEL_URLS.Mobilenetv1Model),
TinyFaceDetectorModel: this.checkUndefined(options.TinyFaceDetectorModel, DEFAULTS.MODEL_URLS.TinyFaceDetectorModel),
FaceLandmarkModel: this.checkUndefined(options.FaceLandmarkModel, DEFAULTS.MODEL_URLS.FaceLandmarkModel),
FaceLandmark68TinyNet: this.checkUndefined(options.FaceLandmark68TinyNet, DEFAULTS.MODEL_URLS.FaceLandmark68TinyNet),
FaceRecognitionModel: this.checkUndefined(options.FaceRecognitionModel, DEFAULTS.MODEL_URLS.FaceRecognitionModel)
}
};
this.ready = (0, _callcallback2.default)(this.loadModel(), callback);
}
/**
* Load the model and set it to this.model
* @return {this} the BodyPix model.
*/
(0, _createClass3.default)(FaceApiBase, [{
key: "loadModel",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this = this;
var modelOptions, _config$MODEL_URLS, Mobilenetv1Model, TinyFaceDetectorModel, FaceLandmarkModel, FaceRecognitionModel, FaceLandmark68TinyNet;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
modelOptions = ["Mobilenetv1Model", "TinyFaceDetectorModel", "FaceLandmarkModel", "FaceLandmark68TinyNet", "FaceRecognitionModel"];
(0, _keys2.default)(this.config.MODEL_URLS).forEach(function (item) {
if (modelOptions.includes(item)) {
_this.config.MODEL_URLS[item] = _this.getModelPath(_this.config.MODEL_URLS[item]);
}
});
_config$MODEL_URLS = this.config.MODEL_URLS, Mobilenetv1Model = _config$MODEL_URLS.Mobilenetv1Model, TinyFaceDetectorModel = _config$MODEL_URLS.TinyFaceDetectorModel, FaceLandmarkModel = _config$MODEL_URLS.FaceLandmarkModel, FaceRecognitionModel = _config$MODEL_URLS.FaceRecognitionModel, FaceLandmark68TinyNet = _config$MODEL_URLS.FaceLandmark68TinyNet;
this.model = faceapi;
if (this.config.withTinyNet === true) {
this.detectorOptions = new faceapi.TinyFaceDetectorOptions({
minConfidence: this.minConfidence,
inputSize: 512
});
} else {
this.detectorOptions = new faceapi.SsdMobilenetv1Options({
minConfidence: this.minConfidence
});
}
// check which model to load - tiny or normal
if (!(this.config.withTinyNet === true)) {
_context.next = 12;
break;
}
_context.next = 8;
return this.model.loadFaceLandmarkTinyModel(FaceLandmark68TinyNet);
case 8:
_context.next = 10;
return this.model.loadTinyFaceDetectorModel(TinyFaceDetectorModel);
case 10:
_context.next = 16;
break;
case 12:
_context.next = 14;
return this.model.loadFaceLandmarkModel(FaceLandmarkModel);
case 14:
_context.next = 16;
return this.model.loadSsdMobilenetv1Model(Mobilenetv1Model);
case 16:
_context.next = 18;
return this.model.loadFaceRecognitionModel(FaceRecognitionModel);
case 18:
this.modelReady = true;
return _context.abrupt("return", this);
case 20:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* .detect() - classifies multiple features by default
* @param {*} optionsOrCallback
* @param {*} configOrCallback
* @param {*} cb
*/
}, {
key: "detect",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(optionsOrCallback, configOrCallback, cb) {
var imgToClassify, callback, faceApiOptions;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
imgToClassify = this.video;
callback = void 0;
faceApiOptions = this.config;
// Handle the image to predict
if (!(typeof optionsOrCallback === "function")) {
_context2.next = 8;
break;
}
imgToClassify = this.video;
callback = optionsOrCallback;
// clean the following conditional statement up!
_context2.next = 22;
break;
case 8:
if (!(optionsOrCallback instanceof HTMLImageElement || optionsOrCallback instanceof HTMLCanvasElement || optionsOrCallback instanceof HTMLVideoElement || optionsOrCallback instanceof ImageData)) {
_context2.next = 12;
break;
}
imgToClassify = optionsOrCallback;
_context2.next = 22;
break;
case 12:
if (!((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object" && (optionsOrCallback.elt instanceof HTMLImageElement || optionsOrCallback.elt instanceof HTMLCanvasElement || optionsOrCallback.elt instanceof HTMLVideoElement || optionsOrCallback.elt instanceof ImageData))) {
_context2.next = 16;
break;
}
imgToClassify = optionsOrCallback.elt; // Handle p5.js image
_context2.next = 22;
break;
case 16:
if (!((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object" && optionsOrCallback.canvas instanceof HTMLCanvasElement)) {
_context2.next = 20;
break;
}
imgToClassify = optionsOrCallback.canvas; // Handle p5.js image
_context2.next = 22;
break;
case 20:
if (this.video instanceof HTMLVideoElement) {
_context2.next = 22;
break;
}
throw new Error("No input image provided. If you want to classify a video, pass the video element in the constructor. ");
case 22:
if ((typeof configOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(configOrCallback)) === "object") {
faceApiOptions = configOrCallback;
} else if (typeof configOrCallback === "function") {
callback = configOrCallback;
}
if (typeof cb === "function") {
callback = cb;
}
return _context2.abrupt("return", (0, _callcallback2.default)(this.detectInternal(imgToClassify, faceApiOptions), callback));
case 25:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function detect(_x, _x2, _x3) {
return _ref2.apply(this, arguments);
}
return detect;
}()
/**
* Detects multiple internal function
* @param {HTMLImageElement || HTMLVideoElement} imgToClassify
* @param {Object} faceApiOptions
*/
}, {
key: "detectInternal",
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(imgToClassify, faceApiOptions) {
var _this2 = this;
var _config, withLandmarks, withDescriptors, result;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.ready;
case 2:
_context3.next = 4;
return tf.nextFrame();
case 4:
if (!(this.video && this.video.readyState === 0)) {
_context3.next = 7;
break;
}
_context3.next = 7;
return new _promise2.default(function (resolve) {
_this2.video.onloadeddata = function () {
return resolve();
};
});
case 7:
// sets the return options if any are passed in during .detect() or .detectSingle()
this.config = this.setReturnOptions(faceApiOptions);
_config = this.config, withLandmarks = _config.withLandmarks, withDescriptors = _config.withDescriptors;
result = void 0;
if (!withLandmarks) {
_context3.next = 22;
break;
}
if (!withDescriptors) {
_context3.next = 17;
break;
}
_context3.next = 14;
return this.model.detectAllFaces(imgToClassify, this.detectorOptions).withFaceLandmarks(this.config.withTinyNet).withFaceDescriptors();
case 14:
result = _context3.sent;
_context3.next = 20;
break;
case 17:
_context3.next = 19;
return this.model.detectAllFaces(imgToClassify, this.detectorOptions).withFaceLandmarks(this.config.withTinyNet);
case 19:
result = _context3.sent;
case 20:
_context3.next = 31;
break;
case 22:
if (withLandmarks) {
_context3.next = 28;
break;
}
_context3.next = 25;
return this.model.detectAllFaces(imgToClassify);
case 25:
result = _context3.sent;
_context3.next = 31;
break;
case 28:
_context3.next = 30;
return this.model.detectAllFaces(imgToClassify, this.detectorOptions).withFaceLandmarks(this.config.withTinyNet).withFaceDescriptors();
case 30:
result = _context3.sent;
case 31:
// always resize the results to the input image size
result = this.resizeResults(result, imgToClassify.width, imgToClassify.height);
// assign the {parts} object after resizing
result = this.landmarkParts(result);
return _context3.abrupt("return", result);
case 34:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function detectInternal(_x4, _x5) {
return _ref3.apply(this, arguments);
}
return detectInternal;
}()
/**
* .detecSinglet() - classifies a single feature with higher accuracy
* @param {*} optionsOrCallback
* @param {*} configOrCallback
* @param {*} cb
*/
}, {
key: "detectSingle",
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(optionsOrCallback, configOrCallback, cb) {
var imgToClassify, callback, faceApiOptions;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
imgToClassify = this.video;
callback = void 0;
faceApiOptions = this.config;
// Handle the image to predict
if (!(typeof optionsOrCallback === "function")) {
_context4.next = 8;
break;
}
imgToClassify = this.video;
callback = optionsOrCallback;
// clean the following conditional statement up!
_context4.next = 22;
break;
case 8:
if (!(optionsOrCallback instanceof HTMLImageElement || optionsOrCallback instanceof HTMLCanvasElement || optionsOrCallback instanceof HTMLVideoElement || optionsOrCallback instanceof ImageData)) {
_context4.next = 12;
break;
}
imgToClassify = optionsOrCallback;
_context4.next = 22;
break;
case 12:
if (!((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object" && (optionsOrCallback.elt instanceof HTMLImageElement || optionsOrCallback.elt instanceof HTMLCanvasElement || optionsOrCallback.elt instanceof HTMLVideoElement || optionsOrCallback.elt instanceof ImageData))) {
_context4.next = 16;
break;
}
imgToClassify = optionsOrCallback.elt; // Handle p5.js image
_context4.next = 22;
break;
case 16:
if (!((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object" && optionsOrCallback.canvas instanceof HTMLCanvasElement)) {
_context4.next = 20;
break;
}
imgToClassify = optionsOrCallback.canvas; // Handle p5.js image
_context4.next = 22;
break;
case 20:
if (this.video instanceof HTMLVideoElement) {
_context4.next = 22;
break;
}
throw new Error("No input image provided. If you want to classify a video, pass the video element in the constructor. ");
case 22:
if ((typeof configOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(configOrCallback)) === "object") {
faceApiOptions = configOrCallback;
} else if (typeof configOrCallback === "function") {
callback = configOrCallback;
}
if (typeof cb === "function") {
callback = cb;
}
return _context4.abrupt("return", (0, _callcallback2.default)(this.detectSingleInternal(imgToClassify, faceApiOptions), callback));
case 25:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function detectSingle(_x6, _x7, _x8) {
return _ref4.apply(this, arguments);
}
return detectSingle;
}()
/**
* Detects only a single feature
* @param {HTMLImageElement || HTMLVideoElement} imgToClassify
* @param {Object} faceApiOptions
*/
}, {
key: "detectSingleInternal",
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(imgToClassify, faceApiOptions) {
var _this3 = this;
var _config2, withLandmarks, withDescriptors, result;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.ready;
case 2:
_context5.next = 4;
return tf.nextFrame();
case 4:
if (!(this.video && this.video.readyState === 0)) {
_context5.next = 7;
break;
}
_context5.next = 7;
return new _promise2.default(function (resolve) {
_this3.video.onloadeddata = function () {
return resolve();
};
});
case 7:
// sets the return options if any are passed in during .detect() or .detectSingle()
this.config = this.setReturnOptions(faceApiOptions);
_config2 = this.config, withLandmarks = _config2.withLandmarks, withDescriptors = _config2.withDescriptors;
result = void 0;
if (!withLandmarks) {
_context5.next = 22;
break;
}
if (!withDescriptors) {
_context5.next = 17;
break;
}
_context5.next = 14;
return this.model.detectSingleFace(imgToClassify, this.detectorOptions).withFaceLandmarks(this.config.withTinyNet).withFaceDescriptor();
case 14:
result = _context5.sent;
_context5.next = 20;
break;
case 17:
_context5.next = 19;
return this.model.detectSingleFace(imgToClassify, this.detectorOptions).withFaceLandmarks(this.config.withTinyNet);
case 19:
result = _context5.sent;
case 20:
_context5.next = 31;
break;
case 22:
if (withLandmarks) {
_context5.next = 28;
break;
}
_context5.next = 25;
return this.model.detectSingleFace(imgToClassify);
case 25:
result = _context5.sent;
_context5.next = 31;
break;
case 28:
_context5.next = 30;
return this.model.detectSingleFace(imgToClassify, this.detectorOptions).withFaceLandmarks(this.config.withTinyNet).withFaceDescriptor();
case 30:
result = _context5.sent;
case 31:
// always resize the results to the input image size
result = this.resizeResults(result, imgToClassify.width, imgToClassify.height);
// assign the {parts} object after resizing
result = this.landmarkParts(result);
return _context5.abrupt("return", result);
case 34:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function detectSingleInternal(_x9, _x10) {
return _ref5.apply(this, arguments);
}
return detectSingleInternal;
}()
/**
* Check if the given _param is undefined, otherwise return the _default
* @param {*} _param
* @param {*} _default
*/
}, {
key: "checkUndefined",
value: function checkUndefined(_param, _default) {
return _param !== undefined ? _param : _default;
}
/**
* Checks if the given string is an absolute or relative path and returns
* the path to the modelJson
* @param {String} absoluteOrRelativeUrl
*/
}, {
key: "getModelPath",
value: function getModelPath(absoluteOrRelativeUrl) {
var modelJsonPath = this.isAbsoluteURL(absoluteOrRelativeUrl) ? absoluteOrRelativeUrl : window.location.pathname + absoluteOrRelativeUrl;
return modelJsonPath;
}
/**
* Sets the return options for .detect() or .detectSingle() in case any are given
* @param {Object} faceApiOptions
*/
}, {
key: "setReturnOptions",
value: function setReturnOptions(faceApiOptions) {
var _this4 = this;
var output = (0, _assign2.default)({}, this.config);
var options = ["withLandmarks", "withDescriptors"];
options.forEach(function (prop) {
if (faceApiOptions[prop] !== undefined) {
_this4.config[prop] = faceApiOptions[prop];
} else {
output[prop] = _this4.config[prop];
}
});
return output;
}
/**
* Resize results to size of input image
* @param {*} str
*/
}, {
key: "resizeResults",
value: function resizeResults(detections, width, height) {
if (width === undefined || height === undefined) {
throw new Error("width and height must be defined");
}
return this.model.resizeResults(detections, {
width: width,
height: height
});
}
/* eslint class-methods-use-this: "off" */
}, {
key: "isAbsoluteURL",
value: function isAbsoluteURL(str) {
var pattern = new RegExp("^(?:[a-z]+:)?//", "i");
return !!pattern.test(str);
}
/**
* get parts from landmarks
* @param {*} result
*/
}, {
key: "landmarkParts",
value: function landmarkParts(result) {
var output = void 0;
// multiple detections is an array
if (Array.isArray(result) === true) {
output = result.map(function (item) {
// if landmarks exist return parts
var newItem = (0, _assign2.default)({}, item);
if (newItem.landmarks) {
var landmarks = newItem.landmarks;
newItem.parts = {
mouth: landmarks.getMouth(),
nose: landmarks.getNose(),
leftEye: landmarks.getLeftEye(),
leftEyeBrow: landmarks.getLeftEyeBrow(),
rightEye: landmarks.getRightEye(),
rightEyeBrow: landmarks.getRightEyeBrow(),
jawOutline: landmarks.getJawOutline()
};
} else {
newItem.parts = {
mouth: [],
nose: [],
leftEye: [],
leftEyeBrow: [],
rightEye: [],
rightEyeBrow: [],
jawOutline: []
};
}
return newItem;
});
// single detection is an object
} else {
output = (0, _assign2.default)({}, result);
if (output.landmarks) {
var landmarks = result.landmarks;
output.parts = {
mouth: landmarks.getMouth(),
nose: landmarks.getNose(),
leftEye: landmarks.getLeftEye(),
leftEyeBrow: landmarks.getLeftEyeBrow(),
rightEye: landmarks.getRightEye(),
rightEyeBrow: landmarks.getRightEyeBrow()
};
} else {
output.parts = {
mouth: [],
nose: [],
leftEye: [],
leftEyeBrow: [],
rightEye: [],
rightEyeBrow: []
};
}
}
return output;
}
}]);
return FaceApiBase;
}();
var faceApi = function faceApi(videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object" && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object") {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === "function") {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object") {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === "function") {
callback = optionsOrCallback;
}
var instance = new FaceApiBase(video, options, callback);
return callback ? instance : instance.ready;
};
exports.default = faceApi;
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toConsumableArray2 = __webpack_require__(82);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _extends2 = __webpack_require__(90);
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjsVis = __webpack_require__(243);
var tfvis = _interopRequireWildcard(_tfjsVis);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// https://js.tensorflow.org/api_vis/latest/#render.barchart
var NeuralNetworkVis = function () {
function NeuralNetworkVis() {
(0, _classCallCheck3.default)(this, NeuralNetworkVis);
// TODO:
this.config = {
height: 300
};
}
// eslint-disable-next-line class-methods-use-this
(0, _createClass3.default)(NeuralNetworkVis, [{
key: "modelSummary",
value: function modelSummary(_options, _model) {
var options = (0, _extends3.default)({}, _options);
tfvis.show.modelSummary(options, _model);
}
/**
* creates a scatterplot from 1 input variable and 1 output variable
* @param {*} inputLabel
* @param {*} outputLabel
* @param {*} data
*/
}, {
key: "scatterplot",
value: function scatterplot(inputLabel, outputLabel, data) {
var values = data.map(function (item) {
return {
x: item.xs[inputLabel],
y: item.ys[outputLabel]
};
});
var visOptions = {
name: "debug mode"
};
var chartOptions = {
xLabel: "X",
yLabel: "Y",
height: this.config.height
};
tfvis.render.scatterplot(visOptions, values, chartOptions);
}
/**
* creates a scatterplot from all input variables and all output variables
* @param {*} inputLabels
* @param {*} outputLabels
* @param {*} data
*/
}, {
key: "scatterplotAll",
value: function scatterplotAll(inputLabels, outputLabels, data) {
var values = [];
inputLabels.forEach(function (inputLabel) {
outputLabels.forEach(function (outputLabel) {
var val = data.map(function (item) {
return {
x: item.xs[inputLabel],
y: item.ys[outputLabel]
};
});
values = [].concat((0, _toConsumableArray3.default)(values), (0, _toConsumableArray3.default)(val));
});
});
var visOptions = {
name: "debug mode"
};
var chartOptions = {
xLabel: "X",
yLabel: "Y",
height: this.config.height
};
tfvis.render.scatterplot(visOptions, values, chartOptions);
}
/**
* creates a barchart from 1 input label and 1 output label
* @param {*} inputLabel
* @param {*} outputLabel
* @param {*} data
*/
}, {
key: "barchart",
value: function barchart(inputLabel, outputLabel, data) {
var values = data.map(function (item) {
return {
value: item.xs[inputLabel],
index: item.ys[outputLabel]
};
});
var chartOptions = {
xLabel: "label",
yLabel: "value",
height: this.config.height
};
console.log(chartOptions);
// Render to visor
var surface = {
name: "Bar chart"
};
tfvis.render.barchart(surface, values);
}
/**
* create a confusion matrix
* @param {*} inputLabels
* @param {*} outputLabels
* @param {*} data
*/
// confusionMatrix(inputLabels, outputLabels, data) {
// }
/**
* Visualize the training of the neural net
*/
}, {
key: "trainingVis",
value: function trainingVis() {
return tfvis.show.fitCallbacks({
name: "Training Performance"
}, ["loss", "accuracy"], {
height: this.config.height,
callbacks: ["onEpochEnd"]
});
}
}]);
return NeuralNetworkVis;
}(); // import * as tf from '@tensorflow/tfjs';
exports.default = NeuralNetworkVis;
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _stringify = __webpack_require__(99);
var _stringify2 = _interopRequireDefault(_stringify);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _set = __webpack_require__(203);
var _set2 = _interopRequireDefault(_set);
var _defineProperty2 = __webpack_require__(199);
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _toConsumableArray2 = __webpack_require__(82);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _entries = __webpack_require__(200);
var _entries2 = _interopRequireDefault(_entries);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _assign = __webpack_require__(89);
var _assign2 = _interopRequireDefault(_assign);
var _extends2 = __webpack_require__(90);
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _io = __webpack_require__(115);
var _NeuralNetworkUtils = __webpack_require__(197);
var _NeuralNetworkUtils2 = _interopRequireDefault(_NeuralNetworkUtils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NeuralNetworkData = function () {
function NeuralNetworkData() {
(0, _classCallCheck3.default)(this, NeuralNetworkData);
this.meta = {
inputUnits: null, // Number
outputUnits: null, // Number
// objects describing input/output data by property name
inputs: {}, // { name1: {dtype}, name2: {dtype} }
outputs: {}, // { name1: {dtype} }
isNormalized: false // Boolean - keep this in meta for model saving/loading
};
this.isMetadataReady = false;
this.isWarmedUp = false;
this.data = {
raw: [] // array of {xs:{}, ys:{}}
};
// methods
// summarize data
this.createMetadata = this.createMetadata.bind(this);
this.getDataStats = this.getDataStats.bind(this);
this.getInputMetaStats = this.getInputMetaStats.bind(this);
this.getDataUnits = this.getDataUnits.bind(this);
this.getInputMetaUnits = this.getInputMetaUnits.bind(this);
this.getDTypesFromData = this.getDTypesFromData.bind(this);
// add data
this.addData = this.addData.bind(this);
// data conversion
this.convertRawToTensors = this.convertRawToTensors.bind(this);
// data normalization / unnormalization
this.normalizeDataRaw = this.normalizeDataRaw.bind(this);
this.normalizeInputData = this.normalizeInputData.bind(this);
this.normalizeArray = this.normalizeArray.bind(this);
this.unnormalizeArray = this.unnormalizeArray.bind(this);
// one hot
this.applyOneHotEncodingsToDataRaw = this.applyOneHotEncodingsToDataRaw.bind(this);
this.getDataOneHot = this.getDataOneHot.bind(this);
this.getInputMetaOneHot = this.getInputMetaOneHot.bind(this);
this.createOneHotEncodings = this.createOneHotEncodings.bind(this);
// Saving / loading data
this.loadDataFromUrl = this.loadDataFromUrl.bind(this);
this.loadJSON = this.loadJSON.bind(this);
this.loadCSV = this.loadCSV.bind(this);
this.loadBlob = this.loadBlob.bind(this);
this.loadData = this.loadData.bind(this);
this.saveData = this.saveData.bind(this);
this.saveMeta = this.saveMeta.bind(this);
this.loadMeta = this.loadMeta.bind(this);
// data loading helpers
this.findEntries = this.findEntries.bind(this);
this.formatRawData = this.formatRawData.bind(this);
this.csvToJSON = this.csvToJSON.bind(this);
}
/**
* ////////////////////////////////////////////////////////
* Summarize Data
* ////////////////////////////////////////////////////////
*/
/**
* create the metadata from the data
* this covers:
* 1. getting the datatype from the data
* 2. getting the min and max from the data
* 3. getting the oneHot encoded values
* 4. getting the inputShape and outputUnits from the data
* @param {*} dataRaw
* @param {*} inputShape
*/
(0, _createClass3.default)(NeuralNetworkData, [{
key: 'createMetadata',
value: function createMetadata(dataRaw) {
var inputShape = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
// get the data type for each property
this.getDTypesFromData(dataRaw);
// get the stats - min, max
this.getDataStats(dataRaw);
// onehot encode
this.getDataOneHot(dataRaw);
// calculate the input units from the data
this.getDataUnits(dataRaw, inputShape);
this.isMetadataReady = true;
return (0, _extends3.default)({}, this.meta);
}
/*
* ////////////////////////////////////////////////
* data Summary
* ////////////////////////////////////////////////
*/
/**
* get stats about the data
* @param {*} dataRaw
*/
}, {
key: 'getDataStats',
value: function getDataStats(dataRaw) {
var meta = (0, _assign2.default)({}, this.meta);
var inputMeta = this.getInputMetaStats(dataRaw, meta.inputs, 'xs');
var outputMeta = this.getInputMetaStats(dataRaw, meta.outputs, 'ys');
meta.inputs = inputMeta;
meta.outputs = outputMeta;
this.meta = (0, _extends3.default)({}, this.meta, meta);
return meta;
}
/**
* getRawStats
* get back the min and max of each label
* @param {*} dataRaw
* @param {*} inputOrOutputMeta
* @param {*} xsOrYs
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'getInputMetaStats',
value: function getInputMetaStats(dataRaw, inputOrOutputMeta, xsOrYs) {
var inputMeta = (0, _assign2.default)({}, inputOrOutputMeta);
(0, _keys2.default)(inputMeta).forEach(function (k) {
if (inputMeta[k].dtype === 'string') {
inputMeta[k].min = 0;
inputMeta[k].max = 1;
} else if (inputMeta[k].dtype === 'number') {
var dataAsArray = dataRaw.map(function (item) {
return item[xsOrYs][k];
});
inputMeta[k].min = _NeuralNetworkUtils2.default.getMin(dataAsArray);
inputMeta[k].max = _NeuralNetworkUtils2.default.getMax(dataAsArray);
} else if (inputMeta[k].dtype === 'array') {
var _dataAsArray = dataRaw.map(function (item) {
return item[xsOrYs][k];
}).flat();
inputMeta[k].min = _NeuralNetworkUtils2.default.getMin(_dataAsArray);
inputMeta[k].max = _NeuralNetworkUtils2.default.getMax(_dataAsArray);
}
});
return inputMeta;
}
/**
* get the data units, inputshape and output units
* @param {*} dataRaw
*/
}, {
key: 'getDataUnits',
value: function getDataUnits(dataRaw) {
var _arrayShape = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var arrayShape = _arrayShape !== null ? _arrayShape : undefined;
var meta = (0, _assign2.default)({}, this.meta);
// if the data has a shape pass it in
var inputShape = void 0;
if (arrayShape) {
inputShape = arrayShape;
} else {
inputShape = [this.getInputMetaUnits(dataRaw, meta.inputs)].flat();
}
var outputShape = this.getInputMetaUnits(dataRaw, meta.outputs);
meta.inputUnits = inputShape;
meta.outputUnits = outputShape;
this.meta = (0, _extends3.default)({}, this.meta, meta);
return meta;
}
/**
* get input
* @param {*} _inputsMeta
* @param {*} _dataRaw
*/
// eslint-disable-next-line class-methods-use-this, no-unused-vars
}, {
key: 'getInputMetaUnits',
value: function getInputMetaUnits(_dataRaw, _inputsMeta) {
var units = 0;
var inputsMeta = (0, _assign2.default)({}, _inputsMeta);
(0, _entries2.default)(inputsMeta).forEach(function (arr) {
var dtype = arr[1].dtype;
if (dtype === 'number') {
units += 1;
} else if (dtype === 'string') {
var uniqueValues = arr[1].uniqueValues;
var uniqueCount = uniqueValues.length;
units += uniqueCount;
} else if (dtype === 'array') {
// TODO: User must input the shape of the
// image size correctly.
units = [];
}
});
return units;
}
/**
* getDTypesFromData
* gets the data types of the data we're using
* important for handling oneHot
*/
}, {
key: 'getDTypesFromData',
value: function getDTypesFromData(_dataRaw) {
var meta = (0, _extends3.default)({}, this.meta, {
inputs: {},
outputs: {}
});
var sample = _dataRaw[0];
var xs = (0, _keys2.default)(sample.xs);
var ys = (0, _keys2.default)(sample.ys);
xs.forEach(function (prop) {
meta.inputs[prop] = {
dtype: _NeuralNetworkUtils2.default.getDataType(sample.xs[prop])
};
});
ys.forEach(function (prop) {
meta.outputs[prop] = {
dtype: _NeuralNetworkUtils2.default.getDataType(sample.ys[prop])
};
});
// TODO: check if all entries have the same dtype.
// otherwise throw an error
this.meta = meta;
return meta;
}
/**
* ////////////////////////////////////////////////////////
* Add Data
* ////////////////////////////////////////////////////////
*/
/**
* Add Data
* @param {object} xInputObj, {key: value}, key must be the name of the property value must be a String, Number, or Array
* @param {*} yInputObj, {key: value}, key must be the name of the property value must be a String, Number, or Array
*/
}, {
key: 'addData',
value: function addData(xInputObj, yInputObj) {
this.data.raw.push({
xs: xInputObj,
ys: yInputObj
});
}
/**
* ////////////////////////////////////////////////////////
* Tensor handling
* ////////////////////////////////////////////////////////
*/
/**
* convertRawToTensors
* converts array of {xs, ys} to tensors
* @param {*} _dataRaw
* @param {*} meta
*/
// eslint-disable-next-line class-methods-use-this, no-unused-vars
}, {
key: 'convertRawToTensors',
value: function convertRawToTensors(dataRaw) {
var meta = (0, _assign2.default)({}, this.meta);
var dataLength = dataRaw.length;
return tf.tidy(function () {
var inputArr = [];
var outputArr = [];
dataRaw.forEach(function (row) {
// get xs
var xs = (0, _keys2.default)(meta.inputs).map(function (k) {
return row.xs[k];
}).flat();
inputArr.push(xs);
// get ys
var ys = (0, _keys2.default)(meta.outputs).map(function (k) {
return row.ys[k];
}).flat();
outputArr.push(ys);
});
var inputs = tf.tensor(inputArr.flat(), [dataLength].concat((0, _toConsumableArray3.default)(meta.inputUnits)));
var outputs = tf.tensor(outputArr.flat(), [dataLength, meta.outputUnits]);
return {
inputs: inputs,
outputs: outputs
};
});
}
/**
* ////////////////////////////////////////////////////////
* data normalization / unnormalization
* ////////////////////////////////////////////////////////
*/
/**
* normalize the dataRaw input
* @param {*} dataRaw
*/
}, {
key: 'normalizeDataRaw',
value: function normalizeDataRaw(dataRaw) {
var meta = (0, _assign2.default)({}, this.meta);
var normXs = this.normalizeInputData(dataRaw, meta.inputs, 'xs');
var normYs = this.normalizeInputData(dataRaw, meta.outputs, 'ys');
var normalizedData = _NeuralNetworkUtils2.default.zipArrays(normXs, normYs);
return normalizedData;
}
/**
* normalizeRaws
* @param {*} dataRaw
* @param {*} inputOrOutputMeta
* @param {*} xsOrYs
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'normalizeInputData',
value: function normalizeInputData(dataRaw, inputOrOutputMeta, xsOrYs) {
var _this = this;
// the data length
var dataLength = dataRaw.length;
// the copy of the inputs.meta[inputOrOutput]
var inputMeta = (0, _assign2.default)({}, inputOrOutputMeta);
// normalized output object
var normalized = {};
(0, _keys2.default)(inputMeta).forEach(function (k) {
// get the min and max values
var options = {
min: inputMeta[k].min,
max: inputMeta[k].max
};
var dataAsArray = dataRaw.map(function (item) {
return item[xsOrYs][k];
});
// depending on the input type, normalize accordingly
if (inputMeta[k].dtype === 'string') {
options.legend = inputMeta[k].legend;
normalized[k] = _this.normalizeArray(dataAsArray, options);
} else if (inputMeta[k].dtype === 'number') {
normalized[k] = _this.normalizeArray(dataAsArray, options);
} else if (inputMeta[k].dtype === 'array') {
normalized[k] = dataAsArray.map(function (item) {
return _this.normalizeArray(item, options);
});
}
});
// create a normalized version of data.raws
var output = [].concat((0, _toConsumableArray3.default)(new Array(dataLength).fill(null))).map(function (item, idx) {
var row = (0, _defineProperty3.default)({}, xsOrYs, {});
(0, _keys2.default)(inputMeta).forEach(function (k) {
row[xsOrYs][k] = normalized[k][idx];
});
return row;
});
return output;
}
/**
* normalizeArray
* @param {*} _input
* @param {*} _options
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'normalizeArray',
value: function normalizeArray(inputArray, options) {
var min = options.min,
max = options.max;
// if the data are onehot encoded, replace the string
// value with the onehot array
// if none exists, return the given value
if (options.legend) {
var normalized = inputArray.map(function (v) {
return options.legend[v] ? options.legend[v] : v;
});
return normalized;
}
// if the dtype is a number
if (inputArray.every(function (v) {
return typeof v === 'number';
})) {
var _normalized = inputArray.map(function (v) {
return _NeuralNetworkUtils2.default.normalizeValue(v, min, max);
});
return _normalized;
}
// otherwise return the input array
// return inputArray;
throw new Error('error in inputArray of normalizeArray() function');
}
/**
* unNormalizeArray
* @param {*} _input
* @param {*} _options
*/
// eslint-disable-next-line no-unused-vars, class-methods-use-this
}, {
key: 'unnormalizeArray',
value: function unnormalizeArray(inputArray, options) {
var min = options.min,
max = options.max;
// if the data is onehot encoded then remap the
// values from those oneHot arrays
if (options.legend) {
var unnormalized = inputArray.map(function (v) {
var res = void 0;
(0, _entries2.default)(options.legend).forEach(function (item) {
var key = item[0];
var val = item[1];
var matches = v.map(function (num, idx) {
return num === val[idx];
}).every(function (truthy) {
return truthy === true;
});
if (matches) res = key;
});
return res;
});
return unnormalized;
}
// if the dtype is a number
if (inputArray.every(function (v) {
return typeof v === 'number';
})) {
var _unnormalized = inputArray.map(function (v) {
return _NeuralNetworkUtils2.default.unnormalizeValue(v, min, max);
});
return _unnormalized;
}
// otherwise return the input array
// return inputArray;
throw new Error('error in inputArray of normalizeArray() function');
}
/*
* ////////////////////////////////////////////////
* One hot encoding handling
* ////////////////////////////////////////////////
*/
/**
* applyOneHotEncodingsToDataRaw
* does not set this.data.raws
* but rather returns them
* @param {*} _dataRaw
* @param {*} _meta
*/
}, {
key: 'applyOneHotEncodingsToDataRaw',
value: function applyOneHotEncodingsToDataRaw(dataRaw) {
var meta = (0, _assign2.default)({}, this.meta);
var output = dataRaw.map(function (row) {
var xs = (0, _extends3.default)({}, row.xs);
var ys = (0, _extends3.default)({}, row.ys);
// get xs
(0, _keys2.default)(meta.inputs).forEach(function (k) {
if (meta.inputs[k].legend) {
xs[k] = meta.inputs[k].legend[row.xs[k]];
}
});
(0, _keys2.default)(meta.outputs).forEach(function (k) {
if (meta.outputs[k].legend) {
ys[k] = meta.outputs[k].legend[row.ys[k]];
}
});
return {
xs: xs,
ys: ys
};
});
return output;
}
/**
* getDataOneHot
* creates onehot encodings for the input and outputs
* and adds them to the meta info
* @param {*} dataRaw
*/
}, {
key: 'getDataOneHot',
value: function getDataOneHot(dataRaw) {
var meta = (0, _assign2.default)({}, this.meta);
var inputMeta = this.getInputMetaOneHot(dataRaw, meta.inputs, 'xs');
var outputMeta = this.getInputMetaOneHot(dataRaw, meta.outputs, 'ys');
meta.inputs = inputMeta;
meta.outputs = outputMeta;
this.meta = (0, _extends3.default)({}, this.meta, meta);
return meta;
}
/**
* getOneHotMeta
* @param {*} _inputsMeta
* @param {*} _dataRaw
* @param {*} xsOrYs
*/
}, {
key: 'getInputMetaOneHot',
value: function getInputMetaOneHot(_dataRaw, _inputsMeta, xsOrYs) {
var _this2 = this;
var inputsMeta = (0, _assign2.default)({}, _inputsMeta);
(0, _entries2.default)(inputsMeta).forEach(function (arr) {
// the key
var key = arr[0];
// the value
var dtype = arr[1].dtype;
if (dtype === 'string') {
var uniqueVals = [].concat((0, _toConsumableArray3.default)(new _set2.default(_dataRaw.map(function (obj) {
return obj[xsOrYs][key];
}))));
var oneHotMeta = _this2.createOneHotEncodings(uniqueVals);
inputsMeta[key] = (0, _extends3.default)({}, inputsMeta[key], oneHotMeta);
}
});
return inputsMeta;
}
/**
* Returns a legend mapping the
* data values to oneHot encoded values
*/
// eslint-disable-next-line class-methods-use-this, no-unused-vars
}, {
key: 'createOneHotEncodings',
value: function createOneHotEncodings(_uniqueValuesArray) {
return tf.tidy(function () {
var output = {
uniqueValues: _uniqueValuesArray,
legend: {}
};
var uniqueVals = _uniqueValuesArray; // [...new Set(this.data.raw.map(obj => obj.xs[prop]))]
// get back values from 0 to the length of the uniqueVals array
var onehotValues = uniqueVals.map(function (item, idx) {
return idx;
});
// oneHot encode the values in the 1d tensor
var oneHotEncodedValues = tf.oneHot(tf.tensor1d(onehotValues, 'int32'), uniqueVals.length);
// convert them from tensors back out to an array
var oneHotEncodedValuesArray = oneHotEncodedValues.arraySync();
// populate the legend with the key/values
uniqueVals.forEach(function (uVal, uIdx) {
output.legend[uVal] = oneHotEncodedValuesArray[uIdx];
});
return output;
});
}
/**
* ////////////////////////////////////////////////
* saving / loading data
* ////////////////////////////////////////////////
*/
/**
* Loads data from a URL using the appropriate function
* @param {*} dataUrl
* @param {*} inputs
* @param {*} outputs
*/
}, {
key: 'loadDataFromUrl',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(dataUrl, inputs, outputs) {
var result;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
result = void 0;
if (!dataUrl.endsWith('.csv')) {
_context.next = 8;
break;
}
_context.next = 5;
return this.loadCSV(dataUrl, inputs, outputs);
case 5:
result = _context.sent;
_context.next = 21;
break;
case 8:
if (!dataUrl.endsWith('.json')) {
_context.next = 14;
break;
}
_context.next = 11;
return this.loadJSON(dataUrl, inputs, outputs);
case 11:
result = _context.sent;
_context.next = 21;
break;
case 14:
if (!dataUrl.includes('blob')) {
_context.next = 20;
break;
}
_context.next = 17;
return this.loadBlob(dataUrl, inputs, outputs);
case 17:
result = _context.sent;
_context.next = 21;
break;
case 20:
throw new Error('Not a valid data format. Must be csv or json');
case 21:
return _context.abrupt('return', result);
case 24:
_context.prev = 24;
_context.t0 = _context['catch'](0);
console.error(_context.t0);
throw new Error(_context.t0);
case 28:
case 'end':
return _context.stop();
}
}
}, _callee, this, [[0, 24]]);
}));
function loadDataFromUrl(_x3, _x4, _x5) {
return _ref.apply(this, arguments);
}
return loadDataFromUrl;
}()
/**
* loadJSON
* @param {*} _dataUrlOrJson
* @param {*} _inputLabelsArray
* @param {*} _outputLabelsArray
*/
}, {
key: 'loadJSON',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(dataUrlOrJson, inputLabels, outputLabels) {
var json, _ref3, data, result;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
json = void 0;
// handle loading parsedJson
if (!(dataUrlOrJson instanceof Object)) {
_context2.next = 6;
break;
}
json = (0, _assign2.default)({}, dataUrlOrJson);
_context2.next = 11;
break;
case 6:
_context2.next = 8;
return _axios2.default.get(dataUrlOrJson);
case 8:
_ref3 = _context2.sent;
data = _ref3.data;
json = data;
case 11:
// format the data.raw array
result = this.formatRawData(json, inputLabels, outputLabels);
return _context2.abrupt('return', result);
case 15:
_context2.prev = 15;
_context2.t0 = _context2['catch'](0);
console.error('error loading json');
throw new Error(_context2.t0);
case 19:
case 'end':
return _context2.stop();
}
}
}, _callee2, this, [[0, 15]]);
}));
function loadJSON(_x6, _x7, _x8) {
return _ref2.apply(this, arguments);
}
return loadJSON;
}()
/**
* loadCSV
* @param {*} _dataUrl
* @param {*} _inputLabelsArray
* @param {*} _outputLabelsArray
*/
}, {
key: 'loadCSV',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(dataUrl, inputLabels, outputLabels) {
var myCsv, loadedData, json, result;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
myCsv = tf.data.csv(dataUrl);
_context3.next = 4;
return myCsv.toArray();
case 4:
loadedData = _context3.sent;
json = {
entries: loadedData
};
// format the data.raw array
result = this.formatRawData(json, inputLabels, outputLabels);
return _context3.abrupt('return', result);
case 10:
_context3.prev = 10;
_context3.t0 = _context3['catch'](0);
console.error('error loading csv', _context3.t0);
throw new Error(_context3.t0);
case 14:
case 'end':
return _context3.stop();
}
}
}, _callee3, this, [[0, 10]]);
}));
function loadCSV(_x9, _x10, _x11) {
return _ref4.apply(this, arguments);
}
return loadCSV;
}()
/**
* loadBlob
* @param {*} _dataUrlOrJson
* @param {*} _inputLabelsArray
* @param {*} _outputLabelsArray
*/
}, {
key: 'loadBlob',
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(dataUrlOrJson, inputLabels, outputLabels) {
var _ref6, data, text, result, json, _json;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.prev = 0;
_context4.next = 3;
return _axios2.default.get(dataUrlOrJson);
case 3:
_ref6 = _context4.sent;
data = _ref6.data;
text = data; // await data.text();
result = void 0;
if (!_NeuralNetworkUtils2.default.isJsonOrString(text)) {
_context4.next = 14;
break;
}
json = JSON.parse(text);
_context4.next = 11;
return this.loadJSON(json, inputLabels, outputLabels);
case 11:
result = _context4.sent;
_context4.next = 18;
break;
case 14:
_json = this.csvToJSON(text);
_context4.next = 17;
return this.loadJSON(_json, inputLabels, outputLabels);
case 17:
result = _context4.sent;
case 18:
return _context4.abrupt('return', result);
case 21:
_context4.prev = 21;
_context4.t0 = _context4['catch'](0);
console.log('mmm might be passing in a string or something!', _context4.t0);
throw new Error(_context4.t0);
case 25:
case 'end':
return _context4.stop();
}
}
}, _callee4, this, [[0, 21]]);
}));
function loadBlob(_x12, _x13, _x14) {
return _ref5.apply(this, arguments);
}
return loadBlob;
}()
/**
* loadData from fileinput or path
* @param {*} filesOrPath
* @param {*} callback
*/
}, {
key: 'loadData',
value: function () {
var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5() {
var filesOrPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var callback = arguments[1];
var loadedData, file, fr, temp, text;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
loadedData = void 0;
if (!(typeof filesOrPath !== 'string')) {
_context5.next = 16;
break;
}
file = filesOrPath[0];
fr = new FileReader();
fr.readAsText(file);
if (!file.name.includes('.json')) {
_context5.next = 13;
break;
}
_context5.next = 9;
return file.text();
case 9:
temp = _context5.sent;
loadedData = JSON.parse(temp);
_context5.next = 14;
break;
case 13:
console.log('data must be a json object containing an array called "data" or "entries');
case 14:
_context5.next = 21;
break;
case 16:
_context5.next = 18;
return _axios2.default.get(filesOrPath, { responseType: "text" });
case 18:
loadedData = _context5.sent;
text = (0, _stringify2.default)(loadedData.data);
if (_NeuralNetworkUtils2.default.isJsonOrString(text)) {
loadedData = JSON.parse(text);
} else {
console.log('Whoops! something went wrong. Either this kind of data is not supported yet or there is an issue with .loadData');
}
case 21:
this.data.raw = this.findEntries(loadedData);
// check if a data or entries property exists
if (!this.data.raw.length > 0) {
console.log('data must be a json object containing an array called "data" ');
}
if (callback) {
callback();
}
_context5.next = 29;
break;
case 26:
_context5.prev = 26;
_context5.t0 = _context5['catch'](0);
throw new Error(_context5.t0);
case 29:
case 'end':
return _context5.stop();
}
}
}, _callee5, this, [[0, 26]]);
}));
function loadData() {
return _ref7.apply(this, arguments);
}
return loadData;
}()
/**
* saveData
* @param {*} name
*/
}, {
key: 'saveData',
value: function () {
var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(name) {
var today, date, time, datetime, dataName, output;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
today = new Date();
date = String(today.getFullYear()) + '-' + String(today.getMonth() + 1) + '-' + String(today.getDate());
time = String(today.getHours()) + '-' + String(today.getMinutes()) + '-' + String(today.getSeconds());
datetime = date + '_' + time;
dataName = datetime;
if (name) dataName = name;
output = {
data: this.data.raw
};
_context6.next = 9;
return (0, _io.saveBlob)((0, _stringify2.default)(output), dataName + '.json', 'text/plain');
case 9:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function saveData(_x16) {
return _ref8.apply(this, arguments);
}
return saveData;
}()
/**
* Saves metadata of the data
* @param {*} nameOrCb
* @param {*} cb
*/
}, {
key: 'saveMeta',
value: function () {
var _ref9 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(nameOrCb, cb) {
var modelName, callback;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
modelName = void 0;
callback = void 0;
if (typeof nameOrCb === 'function') {
modelName = 'model';
callback = nameOrCb;
} else if (typeof nameOrCb === 'string') {
modelName = nameOrCb;
if (typeof cb === 'function') {
callback = cb;
}
} else {
modelName = 'model';
}
_context7.next = 5;
return (0, _io.saveBlob)((0, _stringify2.default)(this.meta), modelName + '_meta.json', 'text/plain');
case 5:
if (callback) {
callback();
}
case 6:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
function saveMeta(_x17, _x18) {
return _ref9.apply(this, arguments);
}
return saveMeta;
}()
/**
* load a model and metadata
* @param {*} filesOrPath
* @param {*} callback
*/
}, {
key: 'loadMeta',
value: function () {
var _ref10 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee9() {
var _this3 = this;
var filesOrPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var callback = arguments[1];
var files, modelMetadata, _modelMetadata2, metaPath, _modelMetadata3;
return _regenerator2.default.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
if (!(filesOrPath instanceof FileList)) {
_context9.next = 8;
break;
}
_context9.next = 3;
return _promise2.default.all((0, _from2.default)(filesOrPath).map(function () {
var _ref11 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee8(file) {
var _modelMetadata;
return _regenerator2.default.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
if (!(file.name.includes('.json') && !file.name.includes('_meta'))) {
_context8.next = 4;
break;
}
return _context8.abrupt('return', {
name: 'model',
file: file
});
case 4:
if (!(file.name.includes('.json') && file.name.includes('_meta.json'))) {
_context8.next = 11;
break;
}
_context8.next = 7;
return file.text();
case 7:
_modelMetadata = _context8.sent;
return _context8.abrupt('return', {
name: 'metadata',
file: _modelMetadata
});
case 11:
if (!file.name.includes('.bin')) {
_context8.next = 13;
break;
}
return _context8.abrupt('return', {
name: 'weights',
file: file
});
case 13:
return _context8.abrupt('return', {
name: null,
file: null
});
case 14:
case 'end':
return _context8.stop();
}
}
}, _callee8, _this3);
}));
return function (_x20) {
return _ref11.apply(this, arguments);
};
}()));
case 3:
files = _context9.sent;
modelMetadata = JSON.parse(files.find(function (item) {
return item.name === 'metadata';
}).file);
this.meta = modelMetadata;
_context9.next = 23;
break;
case 8:
if (!(filesOrPath instanceof Object)) {
_context9.next = 17;
break;
}
_context9.next = 11;
return _axios2.default.get(filesOrPath.metadata, { responseType: "text" });
case 11:
_modelMetadata2 = _context9.sent;
_modelMetadata2 = (0, _stringify2.default)(_modelMetadata2.data);
_modelMetadata2 = JSON.parse(_modelMetadata2);
this.meta = _modelMetadata2;
_context9.next = 23;
break;
case 17:
metaPath = filesOrPath.substring(0, filesOrPath.lastIndexOf('/')) + '/model_meta.json';
_context9.next = 20;
return _axios2.default.get(metaPath);
case 20:
_modelMetadata3 = _context9.sent;
_modelMetadata3 = _modelMetadata3.data;
this.meta = _modelMetadata3;
case 23:
this.isMetadataReady = true;
this.isWarmedUp = true;
if (callback) {
callback();
}
return _context9.abrupt('return', this.meta);
case 27:
case 'end':
return _context9.stop();
}
}
}, _callee9, this);
}));
function loadMeta() {
return _ref10.apply(this, arguments);
}
return loadMeta;
}()
/*
* ////////////////////////////////////////////////
* data loading helpers
* ////////////////////////////////////////////////
*/
/**
* // TODO: convert ys into strings, if the task is classification
// if (this.config.architecture.task === "classification" && typeof output.ys[prop] !== "string") {
// output.ys[prop] += "";
// }
* formatRawData
* takes a json and set the this.data.raw
* @param {*} json
* @param {Array} inputLabels
* @param {Array} outputLabels
*/
}, {
key: 'formatRawData',
value: function formatRawData(json, inputLabels, outputLabels) {
// Recurse through the json object to find
// an array containing `entries` or `data`
var dataArray = this.findEntries(json);
if (!dataArray.length > 0) {
console.log('your data must be contained in an array in \n\n a property called \'entries\' or \'data\' of your json object');
}
// create an array of json objects [{xs,ys}]
var result = dataArray.map(function (item, idx) {
var output = {
xs: {},
ys: {}
};
inputLabels.forEach(function (k) {
if (item[k] !== undefined) {
output.xs[k] = item[k];
} else {
console.error('the input label ' + k + ' does not exist at row ' + idx);
}
});
outputLabels.forEach(function (k) {
if (item[k] !== undefined) {
output.ys[k] = item[k];
} else {
console.error('the output label ' + k + ' does not exist at row ' + idx);
}
});
return output;
});
// set this.data.raw
this.data.raw = result;
return result;
}
/**
* csvToJSON
* Creates a csv from a string
* @param {*} csv
*/
// via: http://techslides.com/convert-csv-to-json-in-javascript
// eslint-disable-next-line class-methods-use-this
}, {
key: 'csvToJSON',
value: function csvToJSON(csv) {
// split the string by linebreak
var lines = csv.split('\n');
var result = [];
// get the header row as an array
var headers = lines[0].split(',');
// iterate through every row
var _loop = function _loop(i) {
// create a json object for each row
var row = {};
// split the current line into an array
var currentline = lines[i].split(',');
// for each header, create a key/value pair
headers.forEach(function (k, idx) {
row[k] = currentline[idx];
});
// add this to the result array
result.push(row);
};
for (var i = 1; i < lines.length; i += 1) {
_loop(i);
}
return {
entries: result
};
}
/**
* findEntries
* recursively attempt to find the entries
* or data array for the given json object
* @param {*} _data
*/
}, {
key: 'findEntries',
value: function findEntries(_data) {
var _this4 = this;
var parentCopy = (0, _assign2.default)({}, _data);
if (parentCopy.entries && parentCopy.entries instanceof Array) {
return parentCopy.entries;
} else if (parentCopy.data && parentCopy.data instanceof Array) {
return parentCopy.data;
}
var keys = (0, _keys2.default)(parentCopy);
// eslint-disable-next-line consistent-return
keys.forEach(function (k) {
if ((0, _typeof3.default)(parentCopy[k]) === 'object') {
return _this4.findEntries(parentCopy[k]);
}
});
return parentCopy;
}
}]);
return NeuralNetworkData;
}();
exports.default = NeuralNetworkData;
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _stringify = __webpack_require__(99);
var _stringify2 = _interopRequireDefault(_stringify);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _io = __webpack_require__(115);
var _random = __webpack_require__(198);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NeuralNetwork = function () {
function NeuralNetwork() {
(0, _classCallCheck3.default)(this, NeuralNetwork);
// flags
this.isTrained = false;
this.isCompiled = false;
this.isLayered = false;
// the model
this.model = null;
// methods
this.init = this.init.bind(this);
this.createModel = this.createModel.bind(this);
this.addLayer = this.addLayer.bind(this);
this.compile = this.compile.bind(this);
this.setOptimizerFunction = this.setOptimizerFunction.bind(this);
this.train = this.train.bind(this);
this.trainInternal = this.trainInternal.bind(this);
this.predict = this.predict.bind(this);
this.classify = this.classify.bind(this);
this.save = this.save.bind(this);
this.load = this.load.bind(this);
// initialize
this.init();
}
/**
* initialize with create model
*/
(0, _createClass3.default)(NeuralNetwork, [{
key: "init",
value: function init() {
this.createModel();
}
/**
* creates a sequential model
* uses switch/case for potential future where different formats are supported
* @param {*} _type
*/
}, {
key: "createModel",
value: function createModel() {
var _type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "sequential";
switch (_type.toLowerCase()) {
case "sequential":
this.model = tf.sequential();
return this.model;
default:
this.model = tf.sequential();
return this.model;
}
}
/**
* add layer to the model
* if the model has 2 or more layers switch the isLayered flag
* @param {*} _layerOptions
*/
}, {
key: "addLayer",
value: function addLayer(_layerOptions) {
var LAYER_OPTIONS = _layerOptions || {};
this.model.add(LAYER_OPTIONS);
// check if it has at least an input and output layer
if (this.model.layers.length >= 2) {
this.isLayered = true;
}
}
/**
* Compile the model
* if the model is compiled, set the isCompiled flag to true
* @param {*} _modelOptions
*/
}, {
key: "compile",
value: function compile(_modelOptions) {
this.model.compile(_modelOptions);
this.isCompiled = true;
}
/**
* Set the optimizer function given the learning rate
* as a parameter
* @param {*} learningRate
* @param {*} optimizer
*/
}, {
key: "setOptimizerFunction",
value: function setOptimizerFunction(learningRate, optimizer) {
return optimizer.call(this, learningRate);
}
/**
* Calls the trainInternal() and calls the callback when finished
* @param {*} _options
* @param {*} _cb
*/
}, {
key: "train",
value: function train(_options, _cb) {
return (0, _callcallback2.default)(this.trainInternal(_options), _cb);
}
/**
* Train the model
* @param {*} _options
*/
}, {
key: "trainInternal",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(_options) {
var TRAINING_OPTIONS, xs, ys, batchSize, epochs, shuffle, validationSplit, whileTraining;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
TRAINING_OPTIONS = _options;
xs = TRAINING_OPTIONS.inputs;
ys = TRAINING_OPTIONS.outputs;
batchSize = TRAINING_OPTIONS.batchSize, epochs = TRAINING_OPTIONS.epochs, shuffle = TRAINING_OPTIONS.shuffle, validationSplit = TRAINING_OPTIONS.validationSplit, whileTraining = TRAINING_OPTIONS.whileTraining;
_context.next = 6;
return this.model.fit(xs, ys, {
batchSize: batchSize,
epochs: epochs,
shuffle: shuffle,
validationSplit: validationSplit,
callbacks: whileTraining
});
case 6:
xs.dispose();
ys.dispose();
this.isTrained = true;
case 9:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function trainInternal(_x2) {
return _ref.apply(this, arguments);
}
return trainInternal;
}()
/**
* returns the prediction as an array synchronously
* @param {*} _inputs
*/
}, {
key: "predictSync",
value: function predictSync(_inputs) {
var _this = this;
var output = tf.tidy(function () {
return _this.model.predict(_inputs);
});
var result = output.arraySync();
output.dispose();
_inputs.dispose();
return result;
}
/**
* returns the prediction as an array
* @param {*} _inputs
*/
}, {
key: "predict",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(_inputs) {
var _this2 = this;
var output, result;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
output = tf.tidy(function () {
return _this2.model.predict(_inputs);
});
_context2.next = 3;
return output.array();
case 3:
result = _context2.sent;
output.dispose();
_inputs.dispose();
return _context2.abrupt("return", result);
case 7:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function predict(_x3) {
return _ref2.apply(this, arguments);
}
return predict;
}()
/**
* classify is the same as .predict()
* @param {*} _inputs
*/
}, {
key: "classify",
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(_inputs) {
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", this.predict(_inputs));
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function classify(_x4) {
return _ref3.apply(this, arguments);
}
return classify;
}()
/**
* classify is the same as .predict()
* @param {*} _inputs
*/
}, {
key: "classifySync",
value: function classifySync(_inputs) {
return this.predictSync(_inputs);
}
// predictMultiple
// classifyMultiple
// are the same as .predict()
/**
* save the model
* @param {*} nameOrCb
* @param {*} cb
*/
}, {
key: "save",
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(nameOrCb, cb) {
var _this3 = this;
var modelName, callback;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
modelName = void 0;
callback = void 0;
if (typeof nameOrCb === "function") {
modelName = "model";
callback = nameOrCb;
} else if (typeof nameOrCb === "string") {
modelName = nameOrCb;
if (typeof cb === "function") {
callback = cb;
}
} else {
modelName = "model";
}
this.model.save(tf.io.withSaveHandler(function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(data) {
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_this3.weightsManifest = {
modelTopology: data.modelTopology,
weightsManifest: [{
paths: ["./" + modelName + ".weights.bin"],
weights: data.weightSpecs
}]
};
_context4.next = 3;
return (0, _io.saveBlob)(data.weightData, modelName + ".weights.bin", "application/octet-stream");
case 3:
_context4.next = 5;
return (0, _io.saveBlob)((0, _stringify2.default)(_this3.weightsManifest), modelName + ".json", "text/plain");
case 5:
if (callback) {
callback();
}
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4, _this3);
}));
return function (_x7) {
return _ref5.apply(this, arguments);
};
}()));
case 4:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function save(_x5, _x6) {
return _ref4.apply(this, arguments);
}
return save;
}()
/**
* loads the model and weights
* @param {*} filesOrPath
* @param {*} callback
*/
}, {
key: "load",
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7() {
var _this4 = this;
var filesOrPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var callback = arguments[1];
var files, model, weights, modelJsonResult, modelJson, modelJsonFile, weightsBlobResult, weightsBlob, weightsBlobFile;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
if (!(filesOrPath instanceof FileList)) {
_context7.next = 11;
break;
}
_context7.next = 3;
return _promise2.default.all((0, _from2.default)(filesOrPath).map(function () {
var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(file) {
var modelMetadata;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!(file.name.includes(".json") && !file.name.includes("_meta"))) {
_context6.next = 4;
break;
}
return _context6.abrupt("return", { name: "model", file: file });
case 4:
if (!(file.name.includes(".json") && file.name.includes("_meta.json"))) {
_context6.next = 11;
break;
}
_context6.next = 7;
return file.text();
case 7:
modelMetadata = _context6.sent;
return _context6.abrupt("return", { name: "metadata", file: modelMetadata });
case 11:
if (!file.name.includes(".bin")) {
_context6.next = 13;
break;
}
return _context6.abrupt("return", { name: "weights", file: file });
case 13:
return _context6.abrupt("return", { name: null, file: null });
case 14:
case "end":
return _context6.stop();
}
}
}, _callee6, _this4);
}));
return function (_x9) {
return _ref7.apply(this, arguments);
};
}()));
case 3:
files = _context7.sent;
model = files.find(function (item) {
return item.name === "model";
}).file;
weights = files.find(function (item) {
return item.name === "weights";
}).file;
// load the model
_context7.next = 8;
return tf.loadLayersModel(tf.io.browserFiles([model, weights]));
case 8:
this.model = _context7.sent;
_context7.next = 30;
break;
case 11:
if (!(filesOrPath instanceof Object)) {
_context7.next = 27;
break;
}
_context7.next = 14;
return _axios2.default.get(filesOrPath.model, { responseType: 'text' });
case 14:
modelJsonResult = _context7.sent;
modelJson = (0, _stringify2.default)(modelJsonResult.data);
// TODO: browser File() API won't be available in node env
modelJsonFile = new File([modelJson], "model.json", { type: "application/json" });
// load the weights
_context7.next = 19;
return _axios2.default.get(filesOrPath.weights, { responseType: 'blob' });
case 19:
weightsBlobResult = _context7.sent;
weightsBlob = weightsBlobResult.data;
// TODO: browser File() API won't be available in node env
weightsBlobFile = new File([weightsBlob], "model.weights.bin", {
type: "application/macbinary"
});
_context7.next = 24;
return tf.loadLayersModel(tf.io.browserFiles([modelJsonFile, weightsBlobFile]));
case 24:
this.model = _context7.sent;
_context7.next = 30;
break;
case 27:
_context7.next = 29;
return tf.loadLayersModel(filesOrPath);
case 29:
this.model = _context7.sent;
case 30:
this.isCompiled = true;
this.isLayered = true;
this.isTrained = true;
if (callback) {
callback();
}
return _context7.abrupt("return", this.model);
case 35:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function load() {
return _ref6.apply(this, arguments);
}
return load;
}()
/**
* dispose and release the memory for the model
*/
}, {
key: "dispose",
value: function dispose() {
this.model.dispose();
}
// NeuroEvolution Functions
/**
* mutate the weights of a model
* @param {*} rate
* @param {*} mutateFunction
*/
}, {
key: "mutate",
value: function mutate() {
var _this5 = this;
var rate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.1;
var mutateFunction = arguments[1];
tf.tidy(function () {
var weights = _this5.model.getWeights();
var mutatedWeights = [];
for (var i = 0; i < weights.length; i += 1) {
var tensor = weights[i];
var shape = weights[i].shape;
// TODO: Evaluate if this should be sync or not
var values = tensor.dataSync().slice();
for (var j = 0; j < values.length; j += 1) {
if (Math.random() < rate) {
if (mutateFunction) {
values[j] = mutateFunction(values[j]);
} else {
values[j] = Math.min(Math.max(values[j] + (0, _random.randomGaussian)(), -1), 1);
}
}
}
var newTensor = tf.tensor(values, shape);
mutatedWeights[i] = newTensor;
}
_this5.model.setWeights(mutatedWeights);
});
}
/**
* create a new neural network with crossover
* @param {*} other
*/
}, {
key: "crossover",
value: function crossover(other) {
var _this6 = this;
return tf.tidy(function () {
var weightsA = _this6.model.getWeights();
var weightsB = other.model.getWeights();
var childWeights = [];
for (var i = 0; i < weightsA.length; i += 1) {
var tensorA = weightsA[i];
var tensorB = weightsB[i];
var shape = weightsA[i].shape;
// TODO: Evaluate if this should be sync or not
var valuesA = tensorA.dataSync().slice();
var valuesB = tensorB.dataSync().slice();
for (var j = 0; j < valuesA.length; j += 1) {
if (Math.random() < 0.5) {
valuesA[j] = valuesB[j];
}
}
var newTensor = tf.tensor(valuesA, shape);
childWeights[i] = newTensor;
}
_this6.model.setWeights(childWeights);
});
}
}]);
return NeuralNetwork;
}();
exports.default = NeuralNetwork;
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(23);
var $entries = __webpack_require__(207)(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(308);
module.exports = __webpack_require__(18).Object.entries;
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _entries = __webpack_require__(200);
var _entries2 = _interopRequireDefault(_entries);
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _defineProperty2 = __webpack_require__(199);
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _toConsumableArray2 = __webpack_require__(82);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _assign = __webpack_require__(89);
var _assign2 = _interopRequireDefault(_assign);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _extends2 = __webpack_require__(90);
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _NeuralNetwork = __webpack_require__(307);
var _NeuralNetwork2 = _interopRequireDefault(_NeuralNetwork);
var _NeuralNetworkData = __webpack_require__(306);
var _NeuralNetworkData2 = _interopRequireDefault(_NeuralNetworkData);
var _NeuralNetworkVis = __webpack_require__(305);
var _NeuralNetworkVis2 = _interopRequireDefault(_NeuralNetworkVis);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _NeuralNetworkUtils = __webpack_require__(197);
var _NeuralNetworkUtils2 = _interopRequireDefault(_NeuralNetworkUtils);
var _imageUtilities = __webpack_require__(46);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
inputs: [],
outputs: [],
dataUrl: null,
modelUrl: null,
layers: [],
task: null,
debug: false,
learningRate: 0.2,
hiddenUnits: 16,
noTraining: false
};
var DiyNeuralNetwork = function () {
function DiyNeuralNetwork(options, cb) {
(0, _classCallCheck3.default)(this, DiyNeuralNetwork);
this.callback = cb;
this.options = (0, _extends3.default)({}, DEFAULTS, options) || DEFAULTS;
this.neuralNetwork = new _NeuralNetwork2.default();
this.neuralNetworkData = new _NeuralNetworkData2.default();
this.neuralNetworkVis = new _NeuralNetworkVis2.default();
this.data = {
training: []
};
this.ready = false;
// Methods
this.init = this.init.bind(this);
// adding data
this.addData = this.addData.bind(this);
this.loadDataFromUrl = this.loadDataFromUrl.bind(this);
this.loadDataInternal = this.loadDataInternal.bind(this);
// metadata prep
this.createMetaData = this.createMetaData.bind(this);
// data prep and handling
this.prepareForTraining = this.prepareForTraining.bind(this);
this.normalizeData = this.normalizeData.bind(this);
this.normalizeInput = this.normalizeInput.bind(this);
this.searchAndFormat = this.searchAndFormat.bind(this);
this.formatInputItem = this.formatInputItem.bind(this);
this.convertTrainingDataToTensors = this.convertTrainingDataToTensors.bind(this);
this.formatInputsForPrediction = this.formatInputsForPrediction.bind(this);
this.formatInputsForPredictionAll = this.formatInputsForPredictionAll.bind(this);
this.isOneHotEncodedOrNormalized = this.isOneHotEncodedOrNormalized.bind(this);
// model prep
this.train = this.train.bind(this);
this.trainInternal = this.trainInternal.bind(this);
this.addLayer = this.addLayer.bind(this);
this.createNetworkLayers = this.createNetworkLayers.bind(this);
this.addDefaultLayers = this.addDefaultLayers.bind(this);
this.compile = this.compile.bind(this);
// prediction / classification
this.predict = this.predict.bind(this);
this.predictMultiple = this.predictMultiple.bind(this);
this.classify = this.classify.bind(this);
this.classifyMultiple = this.classifyMultiple.bind(this);
this.predictInternal = this.predictInternal.bind(this);
this.classifyInternal = this.classifyInternal.bind(this);
// save / load data
this.saveData = this.saveData.bind(this);
this.loadData = this.loadData.bind(this);
// save / load model
this.save = this.save.bind(this);
this.load = this.load.bind(this);
// release model
this.dispose = this.dispose.bind(this);
// neuroevolution
this.mutate = this.mutate.bind(this);
this.crossover = this.crossover.bind(this);
// Initialize
this.init(this.callback);
}
/**
* ////////////////////////////////////////////////////////////
* Initialization
* ////////////////////////////////////////////////////////////
*/
/**
* init
* @param {*} callback
*/
(0, _createClass3.default)(DiyNeuralNetwork, [{
key: 'init',
value: function init(callback) {
// check if the a static model should be built based on the inputs and output properties
if (this.options.noTraining === true) {
this.createLayersNoTraining();
}
if (this.options.dataUrl !== null) {
this.ready = this.loadDataFromUrl(this.options, callback);
} else if (this.options.modelUrl !== null) {
// will take a URL to model.json, an object, or files array
this.ready = this.load(this.options.modelUrl, callback);
} else {
this.ready = true;
}
}
/**
* createLayersNoTraining
*/
}, {
key: 'createLayersNoTraining',
value: function createLayersNoTraining() {
// Create sample data based on options
var _options2 = this.options,
inputs = _options2.inputs,
outputs = _options2.outputs,
task = _options2.task;
if (task === 'classification') {
for (var i = 0; i < outputs.length; i += 1) {
var inputSample = new Array(inputs).fill(0);
this.addData(inputSample, [outputs[i]]);
}
} else {
var _inputSample = new Array(inputs).fill(0);
var outputSample = new Array(outputs).fill(0);
this.addData(_inputSample, outputSample);
}
this.neuralNetworkData.createMetadata(this.neuralNetworkData.data.raw);
this.addDefaultLayers(this.options.task, this.neuralNetworkData.meta);
}
/**
* copy
*/
}, {
key: 'copy',
value: function copy() {
var _this = this;
var nnCopy = new DiyNeuralNetwork(this.options);
return tf.tidy(function () {
var weights = _this.neuralNetwork.model.getWeights();
var weightCopies = [];
for (var i = 0; i < weights.length; i += 1) {
weightCopies[i] = weights[i].clone();
}
nnCopy.neuralNetwork.model.setWeights(weightCopies);
return nnCopy;
});
}
/**
* ////////////////////////////////////////////////////////////
* Adding Data
* ////////////////////////////////////////////////////////////
*/
/**
* addData
* @param {Array | Object} xInputs
* @param {Array | Object} yInputs
* @param {*} options
*/
}, {
key: 'addData',
value: function addData(xInputs, yInputs) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var _options3 = this.options,
inputs = _options3.inputs,
outputs = _options3.outputs;
// get the input and output labels
// or infer them from the data
var inputLabels = void 0;
var outputLabels = void 0;
if (options !== null) {
// eslint-disable-next-line prefer-destructuring
inputLabels = options.inputLabels;
// eslint-disable-next-line prefer-destructuring
outputLabels = options.outputLabels;
} else if (inputs.length > 0 && outputs.length > 0) {
// if the inputs and outputs labels have been defined
// in the constructor
if (inputs.every(function (item) {
return typeof item === 'string';
})) {
inputLabels = inputs;
}
if (outputs.every(function (item) {
return typeof item === 'string';
})) {
outputLabels = outputs;
}
} else if ((typeof xInputs === 'undefined' ? 'undefined' : (0, _typeof3.default)(xInputs)) === 'object' && (typeof yInputs === 'undefined' ? 'undefined' : (0, _typeof3.default)(yInputs)) === 'object') {
inputLabels = (0, _keys2.default)(xInputs);
outputLabels = (0, _keys2.default)(yInputs);
} else {
inputLabels = _NeuralNetworkUtils2.default.createLabelsFromArrayValues(xInputs, 'input');
outputLabels = _NeuralNetworkUtils2.default.createLabelsFromArrayValues(yInputs, 'output');
}
// Make sure that the inputLabels and outputLabels are arrays
if (!(inputLabels instanceof Array)) {
throw new Error('inputLabels must be an array');
}
if (!(outputLabels instanceof Array)) {
throw new Error('outputLabels must be an array');
}
var formattedInputs = this.searchAndFormat(xInputs);
var xs = _NeuralNetworkUtils2.default.formatDataAsObject(formattedInputs, inputLabels);
var ys = _NeuralNetworkUtils2.default.formatDataAsObject(yInputs, outputLabels);
this.neuralNetworkData.addData(xs, ys);
}
/**
* loadData
* @param {*} options
* @param {*} callback
*/
}, {
key: 'loadDataFromUrl',
value: function loadDataFromUrl(options, callback) {
return (0, _callcallback2.default)(this.loadDataInternal(options), callback);
}
/**
* loadDataInternal
* @param {*} options
*/
}, {
key: 'loadDataInternal',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(options) {
var dataUrl, inputs, outputs, data;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
dataUrl = options.dataUrl, inputs = options.inputs, outputs = options.outputs;
_context.next = 3;
return this.neuralNetworkData.loadDataFromUrl(dataUrl, inputs, outputs);
case 3:
data = _context.sent;
// once the data are loaded, create the metadata
// and prep the data for training
// if the inputs are defined as an array of [img_width, img_height, channels]
this.createMetadata(data);
this.prepareForTraining(data);
case 6:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadDataInternal(_x2) {
return _ref.apply(this, arguments);
}
return loadDataInternal;
}()
/**
* ////////////////////////////////////////////////////////////
* Metadata prep
* ////////////////////////////////////////////////////////////
*/
}, {
key: 'createMetaData',
value: function createMetaData(dataRaw) {
var inputs = this.options.inputs;
var inputShape = void 0;
if (Array.isArray(inputs) && inputs.length > 0) {
inputShape = inputs.every(function (item) {
return typeof item === 'number';
}) && inputs.length > 0 ? inputs : null;
}
this.neuralNetworkData.createMetadata(dataRaw, inputShape);
}
/**
* ////////////////////////////////////////////////////////////
* Data prep and handling
* ////////////////////////////////////////////////////////////
*/
/**
* Prepare data for training by applying oneHot to raw
* @param {*} dataRaw
*/
}, {
key: 'prepareForTraining',
value: function prepareForTraining() {
var _dataRaw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var dataRaw = _dataRaw === null ? this.neuralNetworkData.data.raw : _dataRaw;
var unnormalizedTrainingData = this.neuralNetworkData.applyOneHotEncodingsToDataRaw(dataRaw);
this.data.training = unnormalizedTrainingData;
this.neuralNetworkData.isWarmedUp = true;
return unnormalizedTrainingData;
}
/**
* normalizeData
* @param {*} _dataRaw
* @param {*} _meta
*/
}, {
key: 'normalizeData',
value: function normalizeData() {
var _dataRaw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var dataRaw = _dataRaw === null ? this.neuralNetworkData.data.raw : _dataRaw;
if (!this.neuralNetworkData.isMetadataReady) {
// if the inputs are defined as an array of [img_width, img_height, channels]
this.createMetaData(dataRaw);
}
if (!this.neuralNetworkData.isWarmedUp) {
this.prepareForTraining(dataRaw);
}
var trainingData = this.neuralNetworkData.normalizeDataRaw(dataRaw);
// set this equal to the training data
this.data.training = trainingData;
// set isNormalized to true
this.neuralNetworkData.meta.isNormalized = true;
return trainingData;
}
/**
* normalize the input value
* @param {*} value
* @param {*} _key
* @param {*} _meta
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'normalizeInput',
value: function normalizeInput(value, _key, _meta) {
var key = _key;
var _meta$key = _meta[key],
min = _meta$key.min,
max = _meta$key.max;
return _NeuralNetworkUtils2.default.normalizeValue(value, min, max);
}
/**
* search though the xInputs and format for adding to data.raws
* @param {*} input
*/
}, {
key: 'searchAndFormat',
value: function searchAndFormat(input) {
var _this2 = this;
var formattedInputs = void 0;
if (Array.isArray(input)) {
formattedInputs = input.map(function (item) {
return _this2.formatInputItem(item);
});
} else if ((typeof input === 'undefined' ? 'undefined' : (0, _typeof3.default)(input)) === 'object') {
var newXInputs = (0, _assign2.default)({}, input);
(0, _keys2.default)(input).forEach(function (k) {
var val = input[k];
newXInputs[k] = _this2.formatInputItem(val);
});
formattedInputs = newXInputs;
}
return formattedInputs;
}
/**
* Returns either the original input or a pixelArray[]
* @param {*} input
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'formatInputItem',
value: function formatInputItem(input) {
var imgToPredict = void 0;
var formattedInputs = void 0;
if ((0, _imageUtilities.isInstanceOfSupportedElement)(input)) {
imgToPredict = input;
} else if ((typeof input === 'undefined' ? 'undefined' : (0, _typeof3.default)(input)) === 'object' && (0, _imageUtilities.isInstanceOfSupportedElement)(input.elt)) {
imgToPredict = input.elt; // Handle p5.js image and video.
} else if ((typeof input === 'undefined' ? 'undefined' : (0, _typeof3.default)(input)) === 'object' && (0, _imageUtilities.isInstanceOfSupportedElement)(input.canvas)) {
imgToPredict = input.canvas; // Handle p5.js image and video.
}
if (imgToPredict) {
formattedInputs = (0, _imageUtilities.imgToPixelArray)(imgToPredict);
} else {
formattedInputs = input;
}
return formattedInputs;
}
/**
* convertTrainingDataToTensors
* @param {*} _trainingData
* @param {*} _meta
*/
}, {
key: 'convertTrainingDataToTensors',
value: function convertTrainingDataToTensors() {
var _trainingData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var _meta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var trainingData = _trainingData === null ? this.data.training : _trainingData;
var meta = _meta === null ? this.neuralNetworkData.meta : _meta;
return this.neuralNetworkData.convertRawToTensors(trainingData, meta);
}
/**
* format the inputs for prediction
* this means applying onehot or normalization
* so that the user can use original data units rather
* than having to normalize
* @param {*} _input
* @param {*} meta
* @param {*} inputHeaders
*/
}, {
key: 'formatInputsForPrediction',
value: function formatInputsForPrediction(_input, meta, inputHeaders) {
var _this3 = this;
var inputData = [];
// TODO: check to see if it is a nested array
// to run predict or classify on a batch of data
if (_input instanceof Array) {
inputData = inputHeaders.map(function (prop, idx) {
return _this3.isOneHotEncodedOrNormalized(_input[idx], prop, meta.inputs);
});
} else if (_input instanceof Object) {
// TODO: make sure that the input order is preserved!
inputData = inputHeaders.map(function (prop) {
return _this3.isOneHotEncodedOrNormalized(_input[prop], prop, meta.inputs);
});
}
// inputData = tf.tensor([inputData.flat()])
inputData = inputData.flat();
return inputData;
}
/**
* formatInputsForPredictionAll
* @param {*} _input
* @param {*} meta
* @param {*} inputHeaders
*/
}, {
key: 'formatInputsForPredictionAll',
value: function formatInputsForPredictionAll(_input, meta, inputHeaders) {
var _this4 = this;
var output = void 0;
if (_input instanceof Array) {
if (_input.every(function (item) {
return Array.isArray(item);
})) {
output = _input.map(function (item) {
return _this4.formatInputsForPrediction(item, meta, inputHeaders);
});
return tf.tensor(output, [_input.length, inputHeaders.length]);
}
output = this.formatInputsForPrediction(_input, meta, inputHeaders);
return tf.tensor([output]);
}
output = this.formatInputsForPrediction(_input, meta, inputHeaders);
return tf.tensor([output]);
}
/**
* check if the input needs to be onehot encoded or
* normalized
* @param {*} _input
* @param {*} _meta
*/
// eslint-disable-next-line class-methods-use-this
}, {
key: 'isOneHotEncodedOrNormalized',
value: function isOneHotEncodedOrNormalized(_input, _key, _meta) {
var input = _input;
var key = _key;
var output = void 0;
if (typeof _input !== 'number') {
output = _meta[key].legend[input];
} else {
output = _input;
if (this.neuralNetworkData.meta.isNormalized) {
output = this.normalizeInput(_input, key, _meta);
}
}
return output;
}
/**
* ////////////////////////////////////////////////////////////
* Model prep
* ////////////////////////////////////////////////////////////
*/
/**
* train
* @param {*} optionsOrCallback
* @param {*} optionsOrWhileTraining
* @param {*} callback
*/
}, {
key: 'train',
value: function train(optionsOrCallback, optionsOrWhileTraining, callback) {
var options = void 0;
var whileTrainingCb = void 0;
var finishedTrainingCb = void 0;
if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && typeof optionsOrWhileTraining === 'function' && typeof callback === 'function') {
options = optionsOrCallback;
whileTrainingCb = optionsOrWhileTraining;
finishedTrainingCb = callback;
} else if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && typeof optionsOrWhileTraining === 'function') {
options = optionsOrCallback;
whileTrainingCb = null;
finishedTrainingCb = optionsOrWhileTraining;
} else if (typeof optionsOrCallback === 'function' && typeof optionsOrWhileTraining === 'function') {
options = {};
whileTrainingCb = optionsOrCallback;
finishedTrainingCb = optionsOrWhileTraining;
} else {
options = {};
whileTrainingCb = null;
finishedTrainingCb = optionsOrCallback;
}
this.trainInternal(options, whileTrainingCb, finishedTrainingCb);
}
/**
* train
* @param {*} _options
* @param {*} _cb
*/
}, {
key: 'trainInternal',
value: function trainInternal(_options, whileTrainingCb, finishedTrainingCb) {
var options = (0, _extends3.default)({
epochs: 10,
batchSize: 32,
validationSplit: 0.1,
whileTraining: null
}, _options);
// if debug mode is true, then use tf vis
if (this.options.debug === true) {
options.whileTraining = [this.neuralNetworkVis.trainingVis(), {
onEpochEnd: null
}];
} else {
// if not use the default training
// options.whileTraining = whileTrainingCb === null ? [{
// onEpochEnd: (epoch, loss) => {
// console.log(epoch, loss.loss)
// }
// }] :
// [{
// onEpochEnd: whileTrainingCb
// }];
options.whileTraining = [{
onEpochEnd: whileTrainingCb
}];
}
// if metadata needs to be generated about the data
if (!this.neuralNetworkData.isMetadataReady) {
// if the inputs are defined as an array of [img_width, img_height, channels]
this.createMetaData(this.neuralNetworkData.data.raw);
}
// if the data still need to be summarized, onehotencoded, etc
if (!this.neuralNetworkData.isWarmedUp) {
this.prepareForTraining(this.neuralNetworkData.data.raw);
}
// if inputs and outputs are not specified
// in the options, then create the tensors
// from the this.neuralNetworkData.data.raws
if (!options.inputs && !options.outputs) {
var _convertTrainingDataT = this.convertTrainingDataToTensors(),
inputs = _convertTrainingDataT.inputs,
outputs = _convertTrainingDataT.outputs;
options.inputs = inputs;
options.outputs = outputs;
}
// check to see if layers are passed into the constructor
// then use those to create your architecture
if (!this.neuralNetwork.isLayered) {
this.options.layers = this.createNetworkLayers(this.options.layers, this.neuralNetworkData.meta);
}
// if the model does not have any layers defined yet
// then use the default structure
if (!this.neuralNetwork.isLayered) {
this.options.layers = this.addDefaultLayers(this.options.task, this.neuralNetworkData.meta);
}
if (!this.neuralNetwork.isCompiled) {
// compile the model with defaults
this.compile();
}
// train once the model is compiled
this.neuralNetwork.train(options, finishedTrainingCb);
}
/**
* addLayer
* @param {*} options
*/
}, {
key: 'addLayer',
value: function addLayer(options) {
this.neuralNetwork.addLayer(options);
}
/**
* add custom layers in options
*/
}, {
key: 'createNetworkLayers',
value: function createNetworkLayers(layerJsonArray, meta) {
var _this5 = this;
var layers = [].concat((0, _toConsumableArray3.default)(layerJsonArray));
var _Object$assign2 = (0, _assign2.default)({}, meta),
inputUnits = _Object$assign2.inputUnits,
outputUnits = _Object$assign2.outputUnits;
var layersLength = layers.length;
if (!(layers.length >= 2)) {
return false;
}
// set the inputShape
layers[0].inputShape = layers[0].inputShape ? layers[0].inputShape : inputUnits;
// set the output units
var lastIndex = layersLength - 1;
var lastLayer = layers[lastIndex];
lastLayer.units = lastLayer.units ? lastLayer.units : outputUnits;
layers.forEach(function (layer) {
_this5.addLayer(tf.layers[layer.type](layer));
});
return layers;
}
// /**
// * createDenseLayer
// * @param {*} _options
// */
// // eslint-disable-next-line class-methods-use-this
// createDenseLayer(_options) {
// const options = Object.assign({}, {
// units: this.options.hiddenUnits,
// activation: 'relu',
// ..._options
// });
// return tf.layers.dense(options);
// }
// /**
// * createConv2dLayer
// * @param {*} _options
// */
// // eslint-disable-next-line class-methods-use-this
// createConv2dLayer(_options) {
// const options = Object.assign({}, {
// kernelSize: 5,
// filters: 8,
// strides: 1,
// activation: 'relu',
// kernelInitializer: 'varianceScaling',
// ..._options
// })
// return tf.layers.conv2d(options);
// }
/**
* addDefaultLayers
* @param {*} _task
*/
}, {
key: 'addDefaultLayers',
value: function addDefaultLayers(task, meta) {
var layers = void 0;
switch (task.toLowerCase()) {
// if the task is classification
case 'classification':
layers = [{
type: 'dense',
units: this.options.hiddenUnits,
activation: 'relu'
}, {
type: 'dense',
activation: 'softmax'
}];
return this.createNetworkLayers(layers, meta);
// if the task is regression
case 'regression':
layers = [{
type: 'dense',
units: this.options.hiddenUnits,
activation: 'relu'
}, {
type: 'dense',
activation: 'sigmoid'
}];
return this.createNetworkLayers(layers, meta);
// if the task is imageClassification
case 'imageclassification':
layers = [{
type: 'conv2d',
filters: 2,
kernelSize: 2,
strides: 2,
activation: 'relu',
kernelInitializer: 'varianceScaling'
}, {
type: 'maxPooling2d',
poolSize: [1, 1],
strides: [1, 1]
}, {
type: 'conv2d',
filters: 1,
kernelSize: 1,
strides: 1,
activation: 'relu',
kernelInitializer: 'varianceScaling'
}, {
type: 'maxPooling2d',
poolSize: [1, 1],
strides: [1, 1]
}, {
type: 'flatten'
}, {
type: 'dense',
kernelInitializer: 'varianceScaling',
activation: 'softmax'
}];
return this.createNetworkLayers(layers, meta);
default:
console.log('no imputUnits or outputUnits defined');
layers = [{
type: 'dense',
units: this.options.hiddenUnits,
activation: 'relu'
}, {
type: 'dense',
activation: 'sigmoid'
}];
return this.createNetworkLayers(layers, meta);
}
}
/**
* compile the model
* @param {*} _options
*/
}, {
key: 'compile',
value: function compile() {
var _modelOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var _learningRate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var LEARNING_RATE = _learningRate === null ? this.options.learningRate : _learningRate;
var options = {};
if (_modelOptions !== null) {
options = (0, _extends3.default)({}, _modelOptions);
} else if (this.options.task === 'classification' || this.options.task === 'imageClassification') {
options = {
loss: 'categoricalCrossentropy',
optimizer: tf.train.sgd,
metrics: ['accuracy']
};
} else if (this.options.task === 'regression') {
options = {
loss: 'meanSquaredError',
optimizer: tf.train.adam,
metrics: ['accuracy']
};
}
options.optimizer = options.optimizer ? this.neuralNetwork.setOptimizerFunction(LEARNING_RATE, options.optimizer) : this.neuralNetwork.setOptimizerFunction(LEARNING_RATE, tf.train.sgd);
this.neuralNetwork.compile(options);
// if debug mode is true, then show the model summary
if (this.options.debug) {
this.neuralNetworkVis.modelSummary({
name: 'Model Summary'
}, this.neuralNetwork.model);
}
}
/**
* ////////////////////////////////////////////////////////////
* Prediction / classification
* ////////////////////////////////////////////////////////////
*/
/**
* synchronous predict
* @param {*} _input
*/
}, {
key: 'predictSync',
value: function predictSync(_input) {
return this.predictSyncInternal(_input);
}
/**
* predict
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'predict',
value: function predict(_input, _cb) {
return (0, _callcallback2.default)(this.predictInternal(_input), _cb);
}
/**
* predictMultiple
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'predictMultiple',
value: function predictMultiple(_input, _cb) {
return (0, _callcallback2.default)(this.predictInternal(_input), _cb);
}
/**
* synchronous classify
* @param {*} _input
*/
}, {
key: 'classifySync',
value: function classifySync(_input) {
return this.classifySyncInternal(_input);
}
/**
* classify
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'classify',
value: function classify(_input, _cb) {
return (0, _callcallback2.default)(this.classifyInternal(_input), _cb);
}
/**
* classifyMultiple
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'classifyMultiple',
value: function classifyMultiple(_input, _cb) {
return (0, _callcallback2.default)(this.classifyInternal(_input), _cb);
}
/**
* synchronous predict internal
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'predictSyncInternal',
value: function predictSyncInternal(_input) {
var meta = this.neuralNetworkData.meta;
var headers = (0, _keys2.default)(meta.inputs);
var inputData = this.formatInputsForPredictionAll(_input, meta, headers);
var unformattedResults = this.neuralNetwork.predictSync(inputData);
inputData.dispose();
if (meta !== null) {
var labels = (0, _keys2.default)(meta.outputs);
var formattedResults = unformattedResults.map(function (unformattedResult) {
return labels.map(function (item, idx) {
var _d;
// check to see if the data were normalized
// if not, then send back the values, otherwise
// unnormalize then return
var val = void 0;
var unNormalized = void 0;
if (meta.isNormalized) {
var _meta$outputs$item = meta.outputs[item],
min = _meta$outputs$item.min,
max = _meta$outputs$item.max;
val = _NeuralNetworkUtils2.default.unnormalizeValue(unformattedResult[idx], min, max);
unNormalized = unformattedResult[idx];
} else {
val = unformattedResult[idx];
}
var d = (_d = {}, (0, _defineProperty3.default)(_d, labels[idx], val), (0, _defineProperty3.default)(_d, 'label', item), (0, _defineProperty3.default)(_d, 'value', val), _d);
// if unNormalized is not undefined, then
// add that to the output
if (unNormalized) {
d.unNormalizedValue = unNormalized;
}
return d;
});
});
// return single array if the length is less than 2,
// otherwise return array of arrays
if (formattedResults.length < 2) {
return formattedResults[0];
}
return formattedResults;
}
// if no meta exists, then return unformatted results;
return unformattedResults;
}
/**
* predict
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'predictInternal',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(_input) {
var meta, headers, inputData, unformattedResults, labels, formattedResults;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
meta = this.neuralNetworkData.meta;
headers = (0, _keys2.default)(meta.inputs);
inputData = this.formatInputsForPredictionAll(_input, meta, headers);
_context2.next = 5;
return this.neuralNetwork.predict(inputData);
case 5:
unformattedResults = _context2.sent;
inputData.dispose();
if (!(meta !== null)) {
_context2.next = 13;
break;
}
labels = (0, _keys2.default)(meta.outputs);
formattedResults = unformattedResults.map(function (unformattedResult) {
return labels.map(function (item, idx) {
var _d2;
// check to see if the data were normalized
// if not, then send back the values, otherwise
// unnormalize then return
var val = void 0;
var unNormalized = void 0;
if (meta.isNormalized) {
var _meta$outputs$item2 = meta.outputs[item],
min = _meta$outputs$item2.min,
max = _meta$outputs$item2.max;
val = _NeuralNetworkUtils2.default.unnormalizeValue(unformattedResult[idx], min, max);
unNormalized = unformattedResult[idx];
} else {
val = unformattedResult[idx];
}
var d = (_d2 = {}, (0, _defineProperty3.default)(_d2, labels[idx], val), (0, _defineProperty3.default)(_d2, 'label', item), (0, _defineProperty3.default)(_d2, 'value', val), _d2);
// if unNormalized is not undefined, then
// add that to the output
if (unNormalized) {
d.unNormalizedValue = unNormalized;
}
return d;
});
});
// return single array if the length is less than 2,
// otherwise return array of arrays
if (!(formattedResults.length < 2)) {
_context2.next = 12;
break;
}
return _context2.abrupt('return', formattedResults[0]);
case 12:
return _context2.abrupt('return', formattedResults);
case 13:
return _context2.abrupt('return', unformattedResults);
case 14:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function predictInternal(_x9) {
return _ref2.apply(this, arguments);
}
return predictInternal;
}()
/**
* synchronous classify internal
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'classifySyncInternal',
value: function classifySyncInternal(_input) {
var meta = this.neuralNetworkData.meta;
var headers = (0, _keys2.default)(meta.inputs);
var inputData = void 0;
if (this.options.task === 'imageClassification') {
// get the inputData for classification
// if it is a image type format it and
// flatten it
inputData = this.searchAndFormat(_input);
if (Array.isArray(inputData)) {
inputData = inputData.flat();
} else {
inputData = inputData[headers[0]];
}
if (meta.isNormalized) {
// TODO: check to make sure this property is not static!!!!
var _meta$inputs$headers$ = meta.inputs[headers[0]],
min = _meta$inputs$headers$.min,
max = _meta$inputs$headers$.max;
inputData = this.neuralNetworkData.normalizeArray((0, _from2.default)(inputData), { min: min, max: max });
} else {
inputData = (0, _from2.default)(inputData);
}
inputData = tf.tensor([inputData], [1].concat((0, _toConsumableArray3.default)(meta.inputUnits)));
} else {
inputData = this.formatInputsForPredictionAll(_input, meta, headers);
}
var unformattedResults = this.neuralNetwork.classifySync(inputData);
inputData.dispose();
if (meta !== null) {
var label = (0, _keys2.default)(meta.outputs)[0];
var vals = (0, _entries2.default)(meta.outputs[label].legend);
var formattedResults = unformattedResults.map(function (unformattedResult) {
return vals.map(function (item, idx) {
var _ref3;
return _ref3 = {}, (0, _defineProperty3.default)(_ref3, item[0], unformattedResult[idx]), (0, _defineProperty3.default)(_ref3, 'label', item[0]), (0, _defineProperty3.default)(_ref3, 'confidence', unformattedResult[idx]), _ref3;
}).sort(function (a, b) {
return b.confidence - a.confidence;
});
});
// return single array if the length is less than 2,
// otherwise return array of arrays
if (formattedResults.length < 2) {
return formattedResults[0];
}
return formattedResults;
}
return unformattedResults;
}
/**
* classify
* @param {*} _input
* @param {*} _cb
*/
}, {
key: 'classifyInternal',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(_input) {
var meta, headers, inputData, _meta$inputs$headers$2, min, max, unformattedResults, label, vals, formattedResults;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
meta = this.neuralNetworkData.meta;
headers = (0, _keys2.default)(meta.inputs);
inputData = void 0;
if (this.options.task === 'imageClassification') {
// get the inputData for classification
// if it is a image type format it and
// flatten it
inputData = this.searchAndFormat(_input);
if (Array.isArray(inputData)) {
inputData = inputData.flat();
} else {
inputData = inputData[headers[0]];
}
if (meta.isNormalized) {
// TODO: check to make sure this property is not static!!!!
_meta$inputs$headers$2 = meta.inputs[headers[0]], min = _meta$inputs$headers$2.min, max = _meta$inputs$headers$2.max;
inputData = this.neuralNetworkData.normalizeArray((0, _from2.default)(inputData), { min: min, max: max });
} else {
inputData = (0, _from2.default)(inputData);
}
inputData = tf.tensor([inputData], [1].concat((0, _toConsumableArray3.default)(meta.inputUnits)));
} else {
inputData = this.formatInputsForPredictionAll(_input, meta, headers);
}
_context3.next = 6;
return this.neuralNetwork.classify(inputData);
case 6:
unformattedResults = _context3.sent;
inputData.dispose();
if (!(meta !== null)) {
_context3.next = 15;
break;
}
label = (0, _keys2.default)(meta.outputs)[0];
vals = (0, _entries2.default)(meta.outputs[label].legend);
formattedResults = unformattedResults.map(function (unformattedResult) {
return vals.map(function (item, idx) {
var _ref5;
return _ref5 = {}, (0, _defineProperty3.default)(_ref5, item[0], unformattedResult[idx]), (0, _defineProperty3.default)(_ref5, 'label', item[0]), (0, _defineProperty3.default)(_ref5, 'confidence', unformattedResult[idx]), _ref5;
}).sort(function (a, b) {
return b.confidence - a.confidence;
});
});
// return single array if the length is less than 2,
// otherwise return array of arrays
if (!(formattedResults.length < 2)) {
_context3.next = 14;
break;
}
return _context3.abrupt('return', formattedResults[0]);
case 14:
return _context3.abrupt('return', formattedResults);
case 15:
return _context3.abrupt('return', unformattedResults);
case 16:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function classifyInternal(_x10) {
return _ref4.apply(this, arguments);
}
return classifyInternal;
}()
/**
* ////////////////////////////////////////////////////////////
* Save / Load Data
* ////////////////////////////////////////////////////////////
*/
/**
* save data
* @param {*} name
*/
}, {
key: 'saveData',
value: function saveData(name) {
this.neuralNetworkData.saveData(name);
}
/**
* load data
* @param {*} filesOrPath
* @param {*} callback
*/
}, {
key: 'loadData',
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4() {
var filesOrPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var callback = arguments[1];
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.neuralNetworkData.loadData(filesOrPath, callback);
case 1:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function loadData() {
return _ref6.apply(this, arguments);
}
return loadData;
}()
/**
* ////////////////////////////////////////////////////////////
* Save / Load Model
* ////////////////////////////////////////////////////////////
*/
/**
* saves the model, weights, and metadata
* @param {*} nameOrCb
* @param {*} cb
*/
}, {
key: 'save',
value: function save(nameOrCb, cb) {
var _this6 = this;
var modelName = void 0;
var callback = void 0;
if (typeof nameOrCb === 'function') {
modelName = 'model';
callback = nameOrCb;
} else if (typeof nameOrCb === 'string') {
modelName = nameOrCb;
if (typeof cb === 'function') {
callback = cb;
}
} else {
modelName = 'model';
}
// save the model
this.neuralNetwork.save(modelName, function () {
_this6.neuralNetworkData.saveMeta(modelName, callback);
});
}
/**
* load a model and metadata
* @param {*} filesOrPath
* @param {*} callback
*/
}, {
key: 'load',
value: function () {
var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5() {
var _this7 = this;
var filesOrPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var cb = arguments[1];
var callback;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
callback = void 0;
if (cb) {
callback = cb;
}
this.neuralNetwork.load(filesOrPath, function () {
_this7.neuralNetworkData.loadMeta(filesOrPath, callback);
return _this7.neuralNetwork.model;
});
case 3:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function load() {
return _ref7.apply(this, arguments);
}
return load;
}()
/**
* dispose and release memory for a model
*/
}, {
key: 'dispose',
value: function dispose() {
this.neuralNetwork.dispose();
}
/**
* ////////////////////////////////////////////////////////////
* New methods for Neuro Evolution
* ////////////////////////////////////////////////////////////
*/
/**
* mutate the weights of a model
* @param {*} rate
* @param {*} mutateFunction
*/
}, {
key: 'mutate',
value: function mutate(rate, mutateFunction) {
this.neuralNetwork.mutate(rate, mutateFunction);
}
/**
* create a new neural network with crossover
* @param {*} other
*/
}, {
key: 'crossover',
value: function crossover(other) {
var nnCopy = this.copy();
nnCopy.neuralNetwork.crossover(other.neuralNetwork);
return nnCopy;
}
}]);
return DiyNeuralNetwork;
}();
var neuralNetwork = function neuralNetwork(inputsOrOptions, outputsOrCallback, callback) {
var options = void 0;
var cb = void 0;
if (inputsOrOptions instanceof Object) {
options = inputsOrOptions;
cb = outputsOrCallback;
} else {
options = {
inputs: inputsOrOptions,
outputs: outputsOrCallback
};
cb = callback;
}
var instance = new DiyNeuralNetwork(options, cb);
return instance;
};
exports.default = neuralNetwork;
/***/ }),
/* 311 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
// "none": {
// "id": -1,
// "color": [0, 0, 0]
// },
"leftFace": {
"id": 0,
"color": [110, 64, 170]
},
"rightFace": {
"id": 1,
"color": [106, 72, 183]
},
"rightUpperLegFront": {
"id": 2,
"color": [100, 81, 196]
},
"rightLowerLegBack": {
"id": 3,
"color": [92, 91, 206]
},
"rightUpperLegBack": {
"id": 4,
"color": [84, 101, 214]
},
"leftLowerLegFront": {
"id": 5,
"color": [75, 113, 221]
},
"leftUpperLegFront": {
"id": 6,
"color": [66, 125, 224]
},
"leftUpperLegBack": {
"id": 7,
"color": [56, 138, 226]
},
"leftLowerLegBack": {
"id": 8,
"color": [48, 150, 224]
},
"rightFeet": {
"id": 9,
"color": [40, 163, 220]
},
"rightLowerLegFront": {
"id": 10,
"color": [33, 176, 214]
},
"leftFeet": {
"id": 11,
"color": [29, 188, 205]
},
"torsoFront": {
"id": 12,
"color": [26, 199, 194]
},
"torsoBack": {
"id": 13,
"color": [26, 210, 182]
},
"rightUpperArmFront": {
"id": 14,
"color": [28, 219, 169]
},
"rightUpperArmBack": {
"id": 15,
"color": [33, 227, 155]
},
"rightLowerArmBack": {
"id": 16,
"color": [41, 234, 141]
},
"leftLowerArmFront": {
"id": 17,
"color": [51, 240, 128]
},
"leftUpperArmFront": {
"id": 18,
"color": [64, 243, 116]
},
"leftUpperArmBack": {
"id": 19,
"color": [79, 246, 105]
},
"leftLowerArmBack": {
"id": 20,
"color": [96, 247, 97]
},
"rightHand": {
"id": 21,
"color": [115, 246, 91]
},
"rightLowerArmFront": {
"id": 22,
"color": [134, 245, 88]
},
"leftHand": {
"id": 23,
"color": [155, 243, 88]
}
};
/***/ }),
/* 312 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BodyPix", function() { return BodyPix; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkpoints", function() { return checkpoints; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodePartSegmentation", function() { return decodePartSegmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMask", function() { return toMask; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "drawBokehEffect", function() { return drawBokehEffect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "drawMask", function() { return drawMask; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "drawPixelatedMask", function() { return drawPixelatedMask; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toColoredPartImageData", function() { return toColoredPartImageData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMaskImageData", function() { return toMaskImageData; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partChannels", function() { return partChannels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resizeAndPadTo", function() { return resizeAndPadTo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scaleAndCropToInputTensorShape", function() { return scaleAndCropToInputTensorShape; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/**
* @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.
* =============================================================================
*/
function __awaiter(e,t,r,a){return new(r||(r=Promise))(function(n,o){function i(e){try{d(a.next(e))}catch(e){o(e)}}function s(e){try{d(a.throw(e))}catch(e){o(e)}}function d(e){e.done?n(e.value):new r(function(t){t(e.value)}).then(i,s)}d((a=a.apply(e,t||[])).next())})}function __generator(e,t){var r,a,n,o,i={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,a&&(n=2&o[0]?a.return:o[0]?a.throw||((n=a.return)&&n.call(a),0):a.next)&&!(n=n.call(a,o[1])).done)return n;switch(a=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,a=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(n=(n=i.trys).length>0&&n[n.length-1])&&(6===o[0]||2===o[0])){i=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]<n[3])){i.label=o[1];break}if(6===o[0]&&i.label<n[1]){i.label=n[1],n=o;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(o);break}n[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],a=0}finally{r=n=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var mobileNet100Architecture=[["conv2d",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",2],["separableConv",1]],mobileNet75Architecture=[["conv2d",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1]],mobileNet50Architecture=[["conv2d",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1]],mobileNet25Architecture=mobileNet50Architecture,VALID_OUTPUT_STRIDES=[8,16,32];function assertValidOutputStride(e){_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e,function(){return"outputStride is not a number"}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(VALID_OUTPUT_STRIDES.indexOf(e)>=0,function(){return"outputStride of "+e+" is invalid. It must be either 8, 16, or 32"})}var mobileNetArchitectures={100:mobileNet100Architecture,75:mobileNet75Architecture,50:mobileNet50Architecture,25:mobileNet25Architecture};function toOutputStridedLayers(e,t){var r=1,a=1;return e.map(function(e,n){var o,i,s=e[0],d=e[1];return r===t?(o=1,i=a,a*=d):(o=d,i=1,r*=d),{blockId:n,convType:s,stride:o,rate:i,outputStride:r}})}var MobileNet=function(){function e(e,t){this.PREPROCESS_DIVISOR=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(127.5),this.ONE=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1),this.modelWeights=e,this.convolutionDefinitions=t}return e.prototype.predict=function(e,t){var r=this,a=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(e.toFloat(),this.PREPROCESS_DIVISOR),n=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["sub"])(a,this.ONE);return toOutputStridedLayers(this.convolutionDefinitions,t).reduce(function(e,t){var a=t.blockId,n=t.stride,o=t.convType,i=t.rate;if("conv2d"===o)return r.conv(e,n,a);if("separableConv"===o)return r.separableConv(e,n,a,i);throw Error("Unknown conv type of "+o)},n)},e.prototype.convToOutput=function(e,t){return e.conv2d(this.weights(t),1,"same").add(this.convBias(t,!1))},e.prototype.conv=function(e,t,r){var a=this.weights("Conv2d_"+String(r));return e.conv2d(a,t,"same").add(this.convBias("Conv2d_"+String(r))).clipByValue(0,6)},e.prototype.separableConv=function(e,t,r,a){void 0===a&&(a=1);var n="Conv2d_"+String(r)+"_depthwise",o="Conv2d_"+String(r)+"_pointwise";return e.depthwiseConv2D(this.depthwiseWeights(n),t,"same","NHWC",a).add(this.depthwiseBias(n)).clipByValue(0,6).conv2d(this.weights(o),[1,1],"same").add(this.convBias(o)).clipByValue(0,6)},e.prototype.weights=function(e){return this.modelWeights.weights(e)},e.prototype.convBias=function(e,t){return void 0===t&&(t=!0),this.modelWeights.convBias(e,t)},e.prototype.depthwiseBias=function(e){return this.modelWeights.depthwiseBias(e)},e.prototype.depthwiseWeights=function(e){return this.modelWeights.depthwiseWeights(e)},e.prototype.dispose=function(){this.modelWeights.dispose()},e}(),BASE_URL="https://storage.googleapis.com/tfjs-models/savedmodel/",checkpoints={1:{url:BASE_URL+"posenet_mobilenet_100_partmap/",architecture:mobileNetArchitectures[100]},.75:{url:BASE_URL+"posenet_mobilenet_075_partmap/",architecture:mobileNetArchitectures[75]},.5:{url:BASE_URL+"posenet_mobilenet_050_partmap/",architecture:mobileNetArchitectures[50]},.25:{url:BASE_URL+"posenet_mobilenet_025_partmap/",architecture:mobileNetArchitectures[25]}};function toFlattenedOneHotPartMap(e){var t=e.shape[2],r=e.argMax(2).reshape([-1]);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["oneHot"])(r,t)}function clipByMask2d(e,t){return e.mul(t)}function toMask(e,t){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return e.greater(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(t)).toInt()})}function decodePartSegmentation(e,t){var r=t.shape,a=r[0],n=r[1],o=r[2];return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r=toFlattenedOneHotPartMap(t),i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["range"])(0,o,1,"int32").expandDims(1);return clipByMask2d(r.matMul(i).toInt().reshape([a,n]).add(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1,"int32")),e).sub(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(1,"int32"))})}var ModelWeights=function(){function e(e){this.graphModel=e}return e.prototype.weights=function(e){return this.getVariable("MobilenetV1/"+e+"/weights")},e.prototype.convBias=function(e,t){return void 0===t&&(t=!0),this.getVariable("MobilenetV1/"+e+"/Conv2D_bias")},e.prototype.depthwiseBias=function(e){return this.getVariable("MobilenetV1/"+e+"/depthwise_bias")},e.prototype.depthwiseWeights=function(e){return this.getVariable("MobilenetV1/"+e+"/depthwise_weights")},e.prototype.getVariable=function(e){return this.graphModel.weights[""+e][0]},e.prototype.dispose=function(){this.graphModel.dispose()},e}();function toInputTensor(e){return e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?e:_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(e)}function resizeAndPadTo(e,t,r){var a=t[0],n=t[1];void 0===r&&(r=!1);var o,i,s,d,u,l,c=e.shape,p=c[0],h=c[1]/p;if(h>n/a){o=n;var f=a-(i=Math.ceil(o/h));s=0,d=0,u=Math.floor(f/2),l=a-(i+u)}else{i=a;var v=n-(o=Math.ceil(a*h));s=Math.floor(v/2),d=n-(o+s),u=0,l=0}return{resizedAndPadded:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var t;return t=r?e.reverse(1).resizeBilinear([i,o]):e.resizeBilinear([i,o]),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["pad3d"])(t,[[u,l],[s,d],[0,0]])}),paddedBy:[[u,l],[s,d]]}}function scaleAndCropToInputTensorShape(e,t,r,a){var n=t[0],o=t[1],i=r[0],s=r[1],d=a[0],u=d[0],l=d[1],c=a[1],p=c[0],h=c[1];return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return removePaddingAndResizeBack(e.resizeBilinear([i,s],!0),[n,o],[[u,l],[p,h]])})}function removePaddingAndResizeBack(e,t,r){var a=t[0],n=t[1],o=r[0],i=o[0],s=o[1],d=r[1],u=d[0],l=d[1],c=e.shape,p=c[0],h=c[1],f=p-(i+s),v=h-(u+l);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["slice3d"])(e,[i,u,0],[f,v,e.shape[2]]).resizeBilinear([a,n],!0)})}var _this=void 0,segmentationModelImageDimensions=[353,257],BodyPix=function(){function e(e){this.mobileNet=e}return e.prototype.predictForSegmentation=function(e,t){var r=this;return void 0===t&&(t=16),assertValidOutputStride(t),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var a=r.mobileNet.predict(e,t);return r.mobileNet.convToOutput(a,"segment_2").sigmoid()})},e.prototype.predictForPartMap=function(e,t){var r=this;return void 0===t&&(t=16),assertValidOutputStride(t),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var a=r.mobileNet.predict(e,t),n=r.mobileNet.convToOutput(a,"segment_2"),o=r.mobileNet.convToOutput(a,"part_heatmap_2");return{segmentScores:n.sigmoid(),partHeatmapScores:o.sigmoid()}})},e.prototype.estimatePersonSegmentationActivation=function(e,t,r){var a=this;return void 0===t&&(t=16),void 0===r&&(r=.5),assertValidOutputStride(t),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var n=toInputTensor(e),o=resizeAndPadTo(n,segmentationModelImageDimensions),i=o.resizedAndPadded,s=o.paddedBy,d=a.predictForSegmentation(i,t),u=i.shape,l=u[0],c=u[1],p=n.shape;return toMask(scaleAndCropToInputTensorShape(d,[p[0],p[1]],[l,c],s).squeeze(),r)})},e.prototype.estimatePersonSegmentation=function(e,t,r){return void 0===t&&(t=16),void 0===r&&(r=.5),__awaiter(this,void 0,void 0,function(){var a,n,o,i,s;return __generator(this,function(d){switch(d.label){case 0:return a=this.estimatePersonSegmentationActivation(e,t,r),n=a.shape,o=n[0],i=n[1],[4,a.data()];case 1:return s=d.sent(),a.dispose(),[2,{height:o,width:i,data:s}]}})})},e.prototype.estimatePartSegmentationActivation=function(e,t,r){var a=this;return void 0===t&&(t=16),void 0===r&&(r=.5),assertValidOutputStride(t),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var n=toInputTensor(e),o=resizeAndPadTo(n,segmentationModelImageDimensions),i=o.resizedAndPadded,s=o.paddedBy,d=a.predictForPartMap(i,t),u=d.segmentScores,l=d.partHeatmapScores,c=i.shape,p=c[0],h=c[1],f=n.shape,v=f[0],m=f[1],g=scaleAndCropToInputTensorShape(u,[v,m],[p,h],s),b=scaleAndCropToInputTensorShape(l,[v,m],[p,h],s);return decodePartSegmentation(toMask(g.squeeze(),r),b)})},e.prototype.estimatePartSegmentation=function(e,t,r){return void 0===t&&(t=16),void 0===r&&(r=.5),__awaiter(this,void 0,void 0,function(){var a,n,o,i,s;return __generator(this,function(d){switch(d.label){case 0:return a=this.estimatePartSegmentationActivation(e,t,r),n=a.shape,o=n[0],i=n[1],[4,a.data()];case 1:return s=d.sent(),a.dispose(),[2,{height:o,width:i,data:s}]}})})},e.prototype.dispose=function(){this.mobileNet.dispose()},e}();function load(e){return void 0===e&&(e=.75),__awaiter(this,void 0,void 0,function(){var t,r;return __generator(this,function(a){switch(a.label){case 0:if(null==_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");return t=Object.keys(checkpoints),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e,function(){return"got multiplier type of "+typeof e+" when it should be a number."}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t.indexOf(e.toString())>=0,function(){return"invalid multiplier value of "+e+". No checkpoint exists for that multiplier. Must be one of "+t.join(",")+"."}),[4,mobilenetLoader.load(e)];case 1:return r=a.sent(),[2,new BodyPix(r)]}})})}var mobilenetLoader={load:function(e){return __awaiter(_this,void 0,void 0,function(){var t,r,a,n;return __generator(this,function(o){switch(o.label){case 0:return t=checkpoints[e],r=t.url,[4,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])(r+"model.json")];case 1:return a=o.sent(),n=new ModelWeights(a),[2,new MobileNet(n,t.architecture)]}})})}};function cpuBlur(e,t,r){for(var a=e.getContext("2d"),n=0,o=1/(2*Math.PI*5*5),i=r<3?1:2,s=-r;s<=r;s+=i)for(var d=-r;d<=r;d+=i){n+=o*Math.exp(-(d*d+s*s)/50)}for(s=-r;s<=r;s+=i)for(d=-r;d<=r;d+=i)a.globalAlpha=o*Math.exp(-(d*d+s*s)/50)/n*r,a.drawImage(t,d,s);a.globalAlpha=1}var offScreenCanvases={};function isSafari(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function assertSameDimensions(e,t,r,a){var n=e.width,o=e.height,i=t.width,s=t.height;if(n!==i||o!==s)throw new Error("error: dimensions must match. "+r+" has dimensions "+n+"x"+o+", "+a+" has dimensions "+i+"x"+s)}function flipCanvasHorizontal(e){var t=e.getContext("2d");t.scale(-1,1),t.translate(-e.width,0)}function drawWithCompositing(e,t,r){e.globalCompositeOperation=r,e.drawImage(t,0,0)}function createOffScreenCanvas(){return document.createElement("canvas")}function ensureOffscreenCanvasCreated(e){return offScreenCanvases[e]||(offScreenCanvases[e]=createOffScreenCanvas()),offScreenCanvases[e]}function drawAndBlurImageOnCanvas(e,t,r){var a=e.height,n=e.width,o=r.getContext("2d");r.width=n,r.height=a,o.clearRect(0,0,n,a),o.save(),isSafari()?cpuBlur(r,e,t):(o.filter="blur("+t+"px)",o.drawImage(e,0,0,n,a)),o.restore()}function drawAndBlurImageOnOffScreenCanvas(e,t,r){var a=ensureOffscreenCanvasCreated(r);return 0===t?renderImageToCanvas(e,a):drawAndBlurImageOnCanvas(e,t,a),a}function renderImageToCanvas(e,t){var r=e.width,a=e.height;t.width=r,t.height=a,t.getContext("2d").drawImage(e,0,0,r,a)}function renderImageDataToCanvas(e,t){t.width=e.width,t.height=e.height,t.getContext("2d").putImageData(e,0,0)}function renderImageDataToOffScreenCanvas(e,t){var r=ensureOffscreenCanvasCreated(t);return renderImageDataToCanvas(e,r),r}function toMaskImageData(e,t){void 0===t&&(t=!0);for(var r=e.width,a=e.height,n=e.data,o=new Uint8ClampedArray(r*a*4),i=0;i<a*r;++i){var s=255*(t?1-n[i]:n[i]),d=4*i;o[d+0]=0,o[d+1]=0,o[d+2]=0,o[d+3]=Math.round(s)}return new ImageData(o,r,a)}function toColoredPartImageData(e,t){for(var r=e.width,a=e.height,n=e.data,o=new Uint8ClampedArray(r*a*4),i=0;i<a*r;++i){var s=Math.round(n[i]),d=4*i;if(-1===s)o[d+0]=255,o[d+1]=255,o[d+2]=255,o[d+3]=255;else{var u=t[s];if(!u)throw new Error("No color could be found for part id "+s);o[d+0]=u[0],o[d+1]=u[1],o[d+2]=u[2],o[d+3]=255}}return new ImageData(o,r,a)}var CANVAS_NAMES={blurred:"blurred",blurredMask:"blurred-mask",mask:"mask",lowresPartMask:"lowres-part-mask"};function drawMask(e,t,r,a,n,o){void 0===a&&(a=.7),void 0===n&&(n=0),void 0===o&&(o=!1),assertSameDimensions(t,r,"image","mask");var i=drawAndBlurImageOnOffScreenCanvas(renderImageDataToOffScreenCanvas(r,CANVAS_NAMES.mask),n,CANVAS_NAMES.blurredMask);e.width=i.width,e.height=i.height;var s=e.getContext("2d");s.save(),o&&flipCanvasHorizontal(e),s.drawImage(t,0,0),s.globalAlpha=a,s.drawImage(i,0,0),s.restore()}function drawPixelatedMask(e,t,r,a,n,o,i){void 0===a&&(a=.7),void 0===n&&(n=0),void 0===o&&(o=!1),void 0===i&&(i=10),assertSameDimensions(t,r,"image","mask");var s=drawAndBlurImageOnOffScreenCanvas(renderImageDataToOffScreenCanvas(r,CANVAS_NAMES.mask),n,CANVAS_NAMES.blurredMask);e.width=s.width,e.height=s.height;var d=e.getContext("2d");d.save(),o&&flipCanvasHorizontal(e);var u=ensureOffscreenCanvasCreated(CANVAS_NAMES.lowresPartMask),l=u.getContext("2d");u.width=s.width*(1/i),u.height=s.height*(1/i),l.drawImage(s,0,0,s.width,s.height,0,0,u.width,u.height),d.imageSmoothingEnabled=!1,d.drawImage(u,0,0,u.width,u.height,0,0,e.width,e.height);for(var c=0;c<u.width;c++)d.beginPath(),d.strokeStyle="#ffffff",d.moveTo(i*c,0),d.lineTo(i*c,e.height),d.stroke();for(c=0;c<u.height;c++)d.beginPath(),d.strokeStyle="#ffffff",d.moveTo(0,i*c),d.lineTo(e.width,i*c),d.stroke();d.globalAlpha=1-a,d.drawImage(t,0,0),d.restore()}function createPersonMask(e,t){var r=renderImageDataToOffScreenCanvas(toMaskImageData(e,!1),CANVAS_NAMES.mask);return 0===t?r:drawAndBlurImageOnOffScreenCanvas(r,t,CANVAS_NAMES.blurredMask)}function drawBokehEffect(e,t,r,a,n,o){void 0===a&&(a=3),void 0===n&&(n=3),void 0===o&&(o=!1),assertSameDimensions(t,r,"image","segmentation");var i=drawAndBlurImageOnOffScreenCanvas(t,a,CANVAS_NAMES.blurred),s=createPersonMask(r,n),d=e.getContext("2d");d.save(),o&&flipCanvasHorizontal(e),d.drawImage(t,0,0),drawWithCompositing(d,s,"destination-in"),drawWithCompositing(d,i,"destination-over"),d.restore()}var partChannels=["leftFace","rightFace","rightUpperLegFront","rightLowerLegBack","rightUpperLegBack","leftLowerLegFront","leftUpperLegFront","leftUpperLegBack","leftLowerLegBack","rightFeet","rightLowerLegFront","leftFeet","torsoFront","torsoBack","rightUpperArmFront","rightUpperArmBack","rightLowerArmBack","leftLowerArmFront","leftUpperArmFront","leftUpperArmBack","leftLowerArmBack","rightHand","rightLowerArmFront","leftHand"];
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _toConsumableArray2 = __webpack_require__(82);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _bodyPix = __webpack_require__(312);
var bp = _interopRequireWildcard(_bodyPix);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _p5Utils = __webpack_require__(83);
var _p5Utils2 = _interopRequireDefault(_p5Utils);
var _BODYPIX_PALETTE = __webpack_require__(311);
var _BODYPIX_PALETTE2 = _interopRequireDefault(_BODYPIX_PALETTE);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
"multiplier": 0.75,
"outputStride": 16,
"segmentationThreshold": 0.5,
"palette": _BODYPIX_PALETTE2.default,
"returnTensors": false
}; // Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
* BodyPix: Real-time Person Segmentation in the Browser
* Ported and integrated from all the hard work by: https://github.com/tensorflow/tfjs-models/tree/master/body-pix
*/
var BodyPix = function () {
/**
* Create BodyPix.
* @param {HTMLVideoElement} video - An HTMLVideoElement.
* @param {object} options - An object with options.
* @param {function} callback - A callback to be called when the model is ready.
*/
function BodyPix(video, options, callback) {
(0, _classCallCheck3.default)(this, BodyPix);
this.video = video;
this.model = null;
this.modelReady = false;
this.modelPath = '';
this.config = {
multiplier: options.multiplier || DEFAULTS.multiplier,
outputStride: options.outputStride || DEFAULTS.outputStride,
segmentationThreshold: options.segmentationThreshold || DEFAULTS.segmentationThreshold,
palette: options.palette || DEFAULTS.palette,
returnTensors: options.returnTensors || DEFAULTS.returnTensors
};
this.ready = (0, _callcallback2.default)(this.loadModel(), callback);
}
/**
* Load the model and set it to this.model
* @return {this} the BodyPix model.
*/
(0, _createClass3.default)(BodyPix, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return bp.load(this.config.multiplier);
case 2:
this.model = _context.sent;
this.modelReady = true;
return _context.abrupt('return', this);
case 5:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Returns an rgb array
* @param {Object} a p5.Color obj
* @return {Array} an [r,g,b] array
*/
/* eslint class-methods-use-this: "off" */
}, {
key: 'p5Color2RGB',
value: function p5Color2RGB(p5ColorObj) {
var regExp = /\(([^)]+)\)/;
var match = regExp.exec(p5ColorObj.toString('rgb'));
var _match$1$split = match[1].split(','),
_match$1$split2 = (0, _slicedToArray3.default)(_match$1$split, 3),
r = _match$1$split2[0],
g = _match$1$split2[1],
b = _match$1$split2[2];
return [r, g, b];
}
/**
* Returns a p5Image
* @param {*} tfBrowserPixelImage
*/
}, {
key: 'convertToP5Image',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(tfBrowserPixelImage, segmentationWidth, segmentationHeight) {
var blob1, p5Image1;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _p5Utils2.default.rawToBlob(tfBrowserPixelImage, segmentationWidth, segmentationHeight);
case 2:
blob1 = _context2.sent;
_context2.next = 5;
return _p5Utils2.default.blobToP5Image(blob1);
case 5:
p5Image1 = _context2.sent;
return _context2.abrupt('return', p5Image1);
case 7:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function convertToP5Image(_x, _x2, _x3) {
return _ref2.apply(this, arguments);
}
return convertToP5Image;
}()
/**
* Returns a bodyPartsSpec object
* @param {Array} an array of [r,g,b] colors
* @return {object} an object with the bodyParts by color and id
*/
/* eslint class-methods-use-this: "off" */
}, {
key: 'bodyPartsSpec',
value: function bodyPartsSpec(colorOptions) {
var _this = this;
var result = colorOptions !== undefined || (0, _keys2.default)(colorOptions).length >= 24 ? colorOptions : this.config.palette;
// Check if we're getting p5 colors, make sure they are rgb
if (_p5Utils2.default.checkP5() && result !== undefined && (0, _keys2.default)(result).length >= 24) {
// Ensure the p5Color object is an RGB array
(0, _keys2.default)(result).forEach(function (part) {
if (result[part].color instanceof window.p5.Color) {
result[part].color = _this.p5Color2RGB(result[part].color);
} else {
result[part].color = result[part].color;
}
});
}
return result;
}
/**
* Segments the image with partSegmentation, return result object
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} imageToSegment -
* takes any of the following params
* @param {object} segmentationOptions - config params for the segmentation
* includes outputStride, segmentationThreshold
* @return {Object} a result object with image, raw, bodyParts
*/
}, {
key: 'segmentWithPartsInternal',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(imgToSegment, segmentationOptions) {
var _this2 = this;
var segmentation, bodyPartsMeta, colorsArray, result, _tf$tidy, personMask, backgroundMask, partMask, personMaskPixels, bgMaskPixels, partMaskPixels;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.ready;
case 2:
_context3.next = 4;
return tf.nextFrame();
case 4:
if (!(this.video && this.video.readyState === 0)) {
_context3.next = 7;
break;
}
_context3.next = 7;
return new _promise2.default(function (resolve) {
_this2.video.onloadeddata = function () {
return resolve();
};
});
case 7:
this.config.palette = segmentationOptions.palette || this.config.palette;
this.config.outputStride = segmentationOptions.outputStride || this.config.outputStride;
this.config.segmentationThreshold = segmentationOptions.segmentationThreshold || this.config.segmentationThreshold;
_context3.next = 12;
return this.model.estimatePartSegmentation(imgToSegment, this.config.outputStride, this.config.segmentationThreshold);
case 12:
segmentation = _context3.sent;
bodyPartsMeta = this.bodyPartsSpec(this.config.palette);
colorsArray = (0, _keys2.default)(bodyPartsMeta).map(function (part) {
return bodyPartsMeta[part].color;
});
result = {
segmentation: segmentation,
raw: {
personMask: null,
backgroundMask: null,
partMask: null
},
tensor: {
personMask: null,
backgroundMask: null,
partMask: null
},
personMask: null,
backgroundMask: null,
partMask: null,
bodyParts: bodyPartsMeta
};
result.raw.backgroundMask = bp.toMaskImageData(segmentation, true);
result.raw.personMask = bp.toMaskImageData(segmentation, false);
result.raw.partMask = bp.toColoredPartImageData(segmentation, colorsArray);
_tf$tidy = tf.tidy(function () {
var normTensor = tf.browser.fromPixels(imgToSegment);
// create a tensor from the input image
var alpha = tf.ones([segmentation.height, segmentation.width, 1]).tile([1, 1, 1]).mul(255);
normTensor = normTensor.concat(alpha, 2);
// create a tensor from the segmentation
var maskPersonTensor = tf.tensor(segmentation.data, [segmentation.height, segmentation.width, 1]);
var maskBackgroundTensor = tf.tensor(segmentation.data, [segmentation.height, segmentation.width, 1]);
var partTensor = tf.tensor([].concat((0, _toConsumableArray3.default)(result.raw.partMask.data)), [segmentation.height, segmentation.width, 4]);
// multiply the segmentation and the inputImage
maskPersonTensor = tf.cast(maskPersonTensor.add(0.2).sign().relu().mul(normTensor), 'int32');
maskBackgroundTensor = tf.cast(maskBackgroundTensor.add(0.2).sign().neg().relu().mul(normTensor), 'int32');
// TODO: handle removing background
partTensor = tf.cast(partTensor, 'int32');
return {
personMask: maskPersonTensor,
backgroundMask: maskBackgroundTensor,
partMask: partTensor
};
}), personMask = _tf$tidy.personMask, backgroundMask = _tf$tidy.backgroundMask, partMask = _tf$tidy.partMask;
_context3.next = 22;
return tf.browser.toPixels(personMask);
case 22:
personMaskPixels = _context3.sent;
_context3.next = 25;
return tf.browser.toPixels(backgroundMask);
case 25:
bgMaskPixels = _context3.sent;
_context3.next = 28;
return tf.browser.toPixels(partMask);
case 28:
partMaskPixels = _context3.sent;
// otherwise, return the pixels
result.personMask = personMaskPixels;
result.backgroundMask = bgMaskPixels;
result.partMask = partMaskPixels;
// if p5 exists, convert to p5 image
if (!_p5Utils2.default.checkP5()) {
_context3.next = 42;
break;
}
_context3.next = 35;
return this.convertToP5Image(personMaskPixels, segmentation.width, segmentation.height);
case 35:
result.personMask = _context3.sent;
_context3.next = 38;
return this.convertToP5Image(bgMaskPixels, segmentation.width, segmentation.height);
case 38:
result.backgroundMask = _context3.sent;
_context3.next = 41;
return this.convertToP5Image(partMaskPixels, segmentation.width, segmentation.height);
case 41:
result.partMask = _context3.sent;
case 42:
if (!this.config.returnTensors) {
personMask.dispose();
backgroundMask.dispose();
partMask.dispose();
} else {
// return tensors
result.tensor.personMask = personMask;
result.tensor.backgroundMask = backgroundMask;
result.tensor.partMask = partMask;
}
return _context3.abrupt('return', result);
case 44:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function segmentWithPartsInternal(_x4, _x5) {
return _ref3.apply(this, arguments);
}
return segmentWithPartsInternal;
}()
/**
* Segments the image with partSegmentation
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} optionsOrCallback -
* takes any of the following params
* @param {object} configOrCallback - config params for the segmentation
* includes palette, outputStride, segmentationThreshold
* @param {function} cb - a callback function that handles the results of the function.
* @return {function} a promise or the results of a given callback, cb.
*/
}, {
key: 'segmentWithParts',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(optionsOrCallback, configOrCallback, cb) {
var imgToSegment, callback, segmentationOptions;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
imgToSegment = this.video;
callback = void 0;
segmentationOptions = this.config;
// Handle the image to predict
if (!(typeof optionsOrCallback === 'function')) {
_context4.next = 8;
break;
}
imgToSegment = this.video;
callback = optionsOrCallback;
// clean the following conditional statement up!
_context4.next = 26;
break;
case 8:
if (!(optionsOrCallback instanceof HTMLImageElement || optionsOrCallback instanceof HTMLCanvasElement || optionsOrCallback instanceof HTMLVideoElement || optionsOrCallback instanceof ImageData)) {
_context4.next = 12;
break;
}
imgToSegment = optionsOrCallback;
_context4.next = 26;
break;
case 12:
if (!((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && (optionsOrCallback.elt instanceof HTMLImageElement || optionsOrCallback.elt instanceof HTMLCanvasElement || optionsOrCallback.elt instanceof ImageData))) {
_context4.next = 16;
break;
}
imgToSegment = optionsOrCallback.elt; // Handle p5.js image
_context4.next = 26;
break;
case 16:
if (!((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && optionsOrCallback.canvas instanceof HTMLCanvasElement)) {
_context4.next = 20;
break;
}
imgToSegment = optionsOrCallback.canvas; // Handle p5.js image
_context4.next = 26;
break;
case 20:
if (!((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && optionsOrCallback.elt instanceof HTMLVideoElement)) {
_context4.next = 24;
break;
}
imgToSegment = optionsOrCallback.elt; // Handle p5.js image
_context4.next = 26;
break;
case 24:
if (this.video instanceof HTMLVideoElement) {
_context4.next = 26;
break;
}
throw new Error('No input image provided. If you want to classify a video, pass the video element in the constructor. ');
case 26:
if ((typeof configOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(configOrCallback)) === 'object') {
segmentationOptions = configOrCallback;
} else if (typeof configOrCallback === 'function') {
callback = configOrCallback;
}
if (typeof cb === 'function') {
callback = cb;
}
return _context4.abrupt('return', (0, _callcallback2.default)(this.segmentWithPartsInternal(imgToSegment, segmentationOptions), callback));
case 29:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function segmentWithParts(_x6, _x7, _x8) {
return _ref4.apply(this, arguments);
}
return segmentWithParts;
}()
/**
* Segments the image with personSegmentation, return result object
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} imageToSegment -
* takes any of the following params
* @param {object} segmentationOptions - config params for the segmentation
* includes outputStride, segmentationThreshold
* @return {Object} a result object with maskBackground, maskPerson, raw
*/
}, {
key: 'segmentInternal',
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(imgToSegment, segmentationOptions) {
var _this3 = this;
var segmentation, result, _tf$tidy2, personMask, backgroundMask, personMaskPixels, bgMaskPixels;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.ready;
case 2:
_context5.next = 4;
return tf.nextFrame();
case 4:
if (!(this.video && this.video.readyState === 0)) {
_context5.next = 7;
break;
}
_context5.next = 7;
return new _promise2.default(function (resolve) {
_this3.video.onloadeddata = function () {
return resolve();
};
});
case 7:
this.config.outputStride = segmentationOptions.outputStride || this.config.outputStride;
this.config.segmentationThreshold = segmentationOptions.segmentationThreshold || this.config.segmentationThreshold;
_context5.next = 11;
return this.model.estimatePersonSegmentation(imgToSegment, this.config.outputStride, this.config.segmentationThreshold);
case 11:
segmentation = _context5.sent;
result = {
segmentation: segmentation,
raw: {
personMask: null,
backgroundMask: null
},
tensor: {
personMask: null,
backgroundMask: null
},
personMask: null,
backgroundMask: null
};
result.raw.backgroundMask = bp.toMaskImageData(segmentation, true);
result.raw.personMask = bp.toMaskImageData(segmentation, false);
// TODO: consider returning the canvas with the bp.drawMask()
// const bgMaskCanvas = document.createElement('canvas');
// bgMaskCanvas.width = segmentation.width;
// bgMaskCanvas.height = segmentation.height;
// bp.drawMask(bgMaskCanvas, imgToSegment, result.maskBackground, 1, 3, false);
// const featureMaskCanvas = document.createElement('canvas');
// featureMaskCanvas.width = segmentation.width;
// featureMaskCanvas.height = segmentation.height;
// bp.drawMask(featureMaskCanvas, imgToSegment, result.maskPerson, 1, 3, false);
// result.backgroundMask = bgMaskCanvas;
// result.featureMask = featureMaskCanvas;
_tf$tidy2 = tf.tidy(function () {
var normTensor = tf.browser.fromPixels(imgToSegment);
// create a tensor from the input image
var alpha = tf.ones([segmentation.height, segmentation.width, 1]).tile([1, 1, 1]).mul(255);
normTensor = normTensor.concat(alpha, 2);
// normTensor.print();
// create a tensor from the segmentation
var maskPersonTensor = tf.tensor(segmentation.data, [segmentation.height, segmentation.width, 1]);
var maskBackgroundTensor = tf.tensor(segmentation.data, [segmentation.height, segmentation.width, 1]);
// multiply the segmentation and the inputImage
maskPersonTensor = tf.cast(maskPersonTensor.neg().add(1).mul(normTensor), 'int32');
maskBackgroundTensor = tf.cast(maskBackgroundTensor.mul(normTensor), 'int32');
return {
personMask: maskPersonTensor,
backgroundMask: maskBackgroundTensor
};
}), personMask = _tf$tidy2.personMask, backgroundMask = _tf$tidy2.backgroundMask;
_context5.next = 18;
return tf.browser.toPixels(personMask);
case 18:
personMaskPixels = _context5.sent;
_context5.next = 21;
return tf.browser.toPixels(backgroundMask);
case 21:
bgMaskPixels = _context5.sent;
if (!_p5Utils2.default.checkP5()) {
_context5.next = 31;
break;
}
_context5.next = 25;
return this.convertToP5Image(personMaskPixels, segmentation.width, segmentation.height);
case 25:
result.personMask = _context5.sent;
_context5.next = 28;
return this.convertToP5Image(bgMaskPixels, segmentation.width, segmentation.height);
case 28:
result.backgroundMask = _context5.sent;
_context5.next = 33;
break;
case 31:
// otherwise, return the pixels
result.personMask = personMaskPixels;
result.backgroundMask = bgMaskPixels;
case 33:
if (!this.config.returnTensors) {
personMask.dispose();
backgroundMask.dispose();
} else {
result.tensor.personMask = personMask;
result.tensor.backgroundMask = backgroundMask;
}
return _context5.abrupt('return', result);
case 35:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function segmentInternal(_x9, _x10) {
return _ref5.apply(this, arguments);
}
return segmentInternal;
}()
/**
* Segments the image with personSegmentation
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} optionsOrCallback -
* takes any of the following params
* @param {object} configOrCallback - config params for the segmentation
* includes outputStride, segmentationThreshold
* @param {function} cb - a callback function that handles the results of the function.
* @return {function} a promise or the results of a given callback, cb.
*/
}, {
key: 'segment',
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(optionsOrCallback, configOrCallback, cb) {
var imgToSegment, callback, segmentationOptions;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
imgToSegment = this.video;
callback = void 0;
segmentationOptions = this.config;
// Handle the image to predict
if (!(typeof optionsOrCallback === 'function')) {
_context6.next = 8;
break;
}
imgToSegment = this.video;
callback = optionsOrCallback;
// clean the following conditional statement up!
_context6.next = 26;
break;
case 8:
if (!(optionsOrCallback instanceof HTMLImageElement || optionsOrCallback instanceof HTMLCanvasElement || optionsOrCallback instanceof HTMLVideoElement || optionsOrCallback instanceof ImageData)) {
_context6.next = 12;
break;
}
imgToSegment = optionsOrCallback;
_context6.next = 26;
break;
case 12:
if (!((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && (optionsOrCallback.elt instanceof HTMLImageElement || optionsOrCallback.elt instanceof HTMLCanvasElement || optionsOrCallback.elt instanceof ImageData))) {
_context6.next = 16;
break;
}
imgToSegment = optionsOrCallback.elt; // Handle p5.js image
_context6.next = 26;
break;
case 16:
if (!((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && optionsOrCallback.canvas instanceof HTMLCanvasElement)) {
_context6.next = 20;
break;
}
imgToSegment = optionsOrCallback.canvas; // Handle p5.js image
_context6.next = 26;
break;
case 20:
if (!((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object' && optionsOrCallback.elt instanceof HTMLVideoElement)) {
_context6.next = 24;
break;
}
imgToSegment = optionsOrCallback.elt; // Handle p5.js image
_context6.next = 26;
break;
case 24:
if (this.video instanceof HTMLVideoElement) {
_context6.next = 26;
break;
}
throw new Error('No input image provided. If you want to classify a video, pass the video element in the constructor. ');
case 26:
if ((typeof configOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(configOrCallback)) === 'object') {
segmentationOptions = configOrCallback;
} else if (typeof configOrCallback === 'function') {
callback = configOrCallback;
}
if (typeof cb === 'function') {
callback = cb;
}
return _context6.abrupt('return', (0, _callcallback2.default)(this.segmentInternal(imgToSegment, segmentationOptions), callback));
case 29:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function segment(_x11, _x12, _x13) {
return _ref6.apply(this, arguments);
}
return segment;
}()
}]);
return BodyPix;
}();
var bodyPix = function bodyPix(videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOrOptionsOrCallback)) === 'object' && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOrOptionsOrCallback)) === 'object') {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === 'function') {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object') {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
var instance = new BodyPix(video, options, callback);
return callback ? instance : instance.ready;
};
exports.default = bodyPix;
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _modelLoader = __webpack_require__(142);
var _modelLoader2 = _interopRequireDefault(_modelLoader);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Initializes the Sentiment demo.
*/
var OOV_CHAR = 2;
var PAD_CHAR = 0;
function padSequences(sequences, maxLen) {
var padding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'pre';
var truncating = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'pre';
var value = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : PAD_CHAR;
return sequences.map(function (seq) {
// Perform truncation.
if (seq.length > maxLen) {
if (truncating === 'pre') {
seq.splice(0, seq.length - maxLen);
} else {
seq.splice(maxLen, seq.length - maxLen);
}
}
// Perform padding.
if (seq.length < maxLen) {
var pad = [];
for (var i = 0; i < maxLen - seq.length; i += 1) {
pad.push(value);
}
if (padding === 'pre') {
// eslint-disable-next-line no-param-reassign
seq = pad.concat(seq);
} else {
// eslint-disable-next-line no-param-reassign
seq = seq.concat(pad);
}
}
return seq;
});
}
var Sentiment = function () {
/**
* Create Sentiment model. Currently the supported model name is 'moviereviews'. ml5 may support different models in the future.
* @param {String} modelName - A string to the path of the JSON model.
* @param {function} callback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise that will be resolved once the model has loaded.
*/
function Sentiment(modelName, callback) {
(0, _classCallCheck3.default)(this, Sentiment);
/**
* Boolean value that specifies if the model has loaded.
* @type {boolean}
* @public
*/
this.ready = (0, _callcallback2.default)(this.loadModel(modelName), callback);
}
/**
* Initializes the Sentiment demo.
*/
(0, _createClass3.default)(Sentiment, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(modelName) {
var movieReviews, modelPath, metadataJson, sentimentMetadata;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
movieReviews = {
model: null,
metadata: null
};
if (!(modelName.toLowerCase() === 'moviereviews')) {
_context.next = 6;
break;
}
movieReviews.model = 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/model.json';
movieReviews.metadata = 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/metadata.json';
_context.next = 14;
break;
case 6:
if (!(_modelLoader2.default.isAbsoluteURL(modelName) === true)) {
_context.next = 12;
break;
}
modelPath = _modelLoader2.default.getModelPath(modelName);
movieReviews.model = modelPath + '/model.json';
movieReviews.metadata = modelPath + '/metadata.json';
_context.next = 14;
break;
case 12:
console.error('problem loading model');
return _context.abrupt('return', this);
case 14:
_context.next = 16;
return tf.loadLayersModel(movieReviews.model);
case 16:
this.model = _context.sent;
_context.next = 19;
return _axios2.default.get(movieReviews.metadata);
case 19:
metadataJson = _context.sent;
sentimentMetadata = metadataJson.data;
this.indexFrom = sentimentMetadata.index_from;
this.maxLen = sentimentMetadata.max_len;
this.wordIndex = sentimentMetadata.word_index;
this.vocabularySize = sentimentMetadata.vocabulary_size;
return _context.abrupt('return', this);
case 26:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel(_x4) {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Scores the sentiment of given text with a value between 0 ("negative") and 1 ("positive").
* @param {String} text - string of text to predict.
* @returns {{score: Number}}
*/
}, {
key: 'predict',
value: function predict(text) {
var _this = this;
// Convert to lower case and remove all punctuations.
var inputText = text.trim().toLowerCase().replace(/[.,?!]/g, '').split(' ');
// Convert the words to a sequence of word indices.
var sequence = inputText.map(function (word) {
var wordIndex = _this.wordIndex[word] + _this.indexFrom;
if (wordIndex > _this.vocabularySize) {
wordIndex = OOV_CHAR;
}
return wordIndex;
});
// Perform truncation and padding.
var paddedSequence = padSequences([sequence], this.maxLen);
var input = tf.tensor2d(paddedSequence, [1, this.maxLen]);
var predictOut = this.model.predict(input);
var score = predictOut.dataSync()[0];
predictOut.dispose();
input.dispose();
return {
score: score
};
}
}]);
return Sentiment;
}();
var sentiment = function sentiment(modelName, callback) {
return new Sentiment(modelName, callback);
};
exports.default = sentiment;
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toConsumableArray2 = __webpack_require__(82);
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
exports.default = registerPreload;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/**
* a list to store all functions to hook p5 preload
* @param {obj} object or prototype to wrap with
* @returns obj
*/
function registerPreload(obj) {
if (typeof window === 'undefined') return obj;
if (typeof window.p5 === 'undefined') return obj;
if (typeof window.p5.prototype === 'undefined') return obj;
if (typeof window.p5.prototype.registerPreloadMethod === 'undefined') return obj;
var preloadFn = obj;
(0, _keys2.default)(obj).forEach(function (key) {
var fn = obj[key];
preloadFn[key] = function preloads() {
var originCallback = null;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var argLen = args.length;
if (typeof args[argLen - 1] === 'function') {
// find callback function attached
originCallback = args[argLen - 1];
argLen -= 1;
}
return fn.apply(obj, [].concat((0, _toConsumableArray3.default)(args.slice(0, argLen)), [function doingPreloads() {
var targetPreloadFn = '_decrementPreload';
try {
if (originCallback) originCallback();
} catch (err) {
console.error(err);
}
if (window[targetPreloadFn]) return window[targetPreloadFn]();
return null;
}]));
};
window.p5.prototype.registerPreloadMethod('' + key, obj);
});
return obj;
}
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _p5Utils = __webpack_require__(83);
var _p5Utils2 = _interopRequireDefault(_p5Utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Default pre-trained face model
// const DEFAULT = {
// "description": "DCGAN, human faces, 64x64",
// "model": "https://raw.githubusercontent.com/ml5js/ml5-data-and-models/master/models/dcgan/face/model.json",
// "modelSize": 64,
// "modelLatentDim": 128
// }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
DCGAN
This version is based on alantian's TensorFlow.js implementation: https://github.com/alantian/ganshowcase
*/
var DCGANBase = function () {
/**
* Create an DCGAN.
* @param {modelName} modelName - The name of the model to use.
* @param {function} readyCb - A callback to be called when the model is ready.
*/
function DCGANBase(modelPath, options, callback) {
(0, _classCallCheck3.default)(this, DCGANBase);
this.model = {};
this.modelPath = modelPath;
this.modelInfo = {};
this.modelPathPrefix = '';
this.modelReady = false;
this.config = {
returnTensors: options.returnTensors || false
};
this.ready = (0, _callcallback2.default)(this.loadModel(), callback);
}
/**
* Load the model and set it to this.model
* @return {this} the dcgan.
*/
(0, _createClass3.default)(DCGANBase, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var modelInfo, modelInfoJson, _modelPath$split, _modelPath$split2, modelUrl, modelJsonPath;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _axios2.default.get(this.modelPath);
case 2:
modelInfo = _context.sent;
modelInfoJson = modelInfo.data;
this.modelInfo = modelInfoJson;
_modelPath$split = this.modelPath.split('manifest.json'), _modelPath$split2 = (0, _slicedToArray3.default)(_modelPath$split, 1), modelUrl = _modelPath$split2[0];
modelJsonPath = this.isAbsoluteURL(modelUrl) ? this.modelInfo.model : this.modelPathPrefix + this.modelInfo.model;
_context.next = 9;
return tf.loadLayersModel(modelJsonPath);
case 9:
this.model = _context.sent;
this.modelReady = true;
return _context.abrupt('return', this);
case 12:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Generates a new image
* @param {function} callback - a callback function handle the results of generate
* @param {object} latentVector - an array containing the latent vector; otherwise use random vector
* @return {object} a promise or the result of the callback function.
*/
}, {
key: 'generate',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(callback, latentVector) {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.ready;
case 2:
return _context2.abrupt('return', (0, _callcallback2.default)(this.generateInternal(latentVector), callback));
case 3:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function generate(_x, _x2) {
return _ref2.apply(this, arguments);
}
return generate;
}()
/**
* Computes what will become the image tensor
* @param {number} latentDim - the number of latent dimensions to pass through
* @param {object} latentVector - an array containing the latent vector; otherwise use random vector
* @return {object} a tensor
*/
}, {
key: 'compute',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(latentDim, latentVector) {
var _this = this;
var y;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
y = tf.tidy(function () {
var z = void 0;
if (Array.isArray(latentVector) === false) {
z = tf.randomNormal([1, latentDim]);
} else {
var buffer = tf.buffer([1, latentDim]);
for (var count = 0; count < latentDim; count += 1) {
buffer.set(latentVector[count], 0, count);
}
z = buffer.toTensor();
}
// TBD: should model be a parameter to compute or is it ok to reference this.model here?
var yDim = _this.model.predict(z).squeeze().transpose([1, 2, 0]).div(tf.scalar(2)).add(tf.scalar(0.5));
return yDim;
});
return _context3.abrupt('return', y);
case 2:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function compute(_x3, _x4) {
return _ref3.apply(this, arguments);
}
return compute;
}()
/**
* Takes the tensor from compute() and returns an object of the generate image data
* @param {object} latentVector - an array containing the latent vector; otherwise use random vector
* @return {object} includes blob, raw, and tensor. if P5 exists, then a p5Image
*/
}, {
key: 'generateInternal',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(latentVector) {
var modelLatentDim, imageTensor, raw, _imageTensor$shape, imgHeight, imgWidth, blob, p5Image, result;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
modelLatentDim = this.modelInfo.modelLatentDim;
_context4.next = 3;
return this.compute(modelLatentDim, latentVector);
case 3:
imageTensor = _context4.sent;
_context4.next = 6;
return tf.browser.toPixels(imageTensor);
case 6:
raw = _context4.sent;
// get the blob from raw
_imageTensor$shape = (0, _slicedToArray3.default)(imageTensor.shape, 2), imgHeight = _imageTensor$shape[0], imgWidth = _imageTensor$shape[1];
_context4.next = 10;
return _p5Utils2.default.rawToBlob(raw, imgWidth, imgHeight);
case 10:
blob = _context4.sent;
// get the p5.Image object
p5Image = void 0;
if (!_p5Utils2.default.checkP5()) {
_context4.next = 16;
break;
}
_context4.next = 15;
return _p5Utils2.default.blobToP5Image(blob);
case 15:
p5Image = _context4.sent;
case 16:
// wrap up the final js result object
result = {};
result.blob = blob;
result.raw = raw;
if (_p5Utils2.default.checkP5()) {
result.image = p5Image;
}
if (!this.config.returnTensors) {
result.tensor = null;
imageTensor.dispose();
} else {
result.tensor = imageTensor;
}
return _context4.abrupt('return', result);
case 22:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function generateInternal(_x5) {
return _ref4.apply(this, arguments);
}
return generateInternal;
}()
/* eslint class-methods-use-this: "off" */
}, {
key: 'isAbsoluteURL',
value: function isAbsoluteURL(str) {
var pattern = new RegExp('^(?:[a-z]+:)?//', 'i');
return !!pattern.test(str);
}
}]);
return DCGANBase;
}();
var DCGAN = function DCGAN(modelPath, optionsOrCb, cb) {
var callback = void 0;
var options = {};
if (typeof modelPath !== 'string') {
throw new Error('Please specify a path to a "manifest.json" file: \n\n "models/face/manifest.json" \n\n\n This "manifest.json" file should include:\n\n {\n "description": "DCGAN, human faces, 64x64",\n "model": "https://raw.githubusercontent.com/viztopia/ml5dcgan/master/model/model.json", // "https://github.com/viztopia/ml5dcgan/blob/master/model/model.json",\n "modelSize": 64,\n "modelLatentDim": 128 \n }\n ');
}
if (typeof optionsOrCb === 'function') {
callback = optionsOrCb;
} else if ((typeof optionsOrCb === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCb)) === 'object') {
options = optionsOrCb;
callback = cb;
}
var instance = new DCGANBase(modelPath, options, callback);
return callback ? instance : instance.ready;
};
exports.default = DCGAN;
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
* CVAE: Run conditional auto-encoder for pro-trained model
*/
var Cvae = function () {
/**
* Create a Conditional Variational Autoencoder (CVAE).
* @param {String} modelPath - Required. The url path to your model.
* @param {function} callback - Required. A function to run once the model has been loaded.
*/
function Cvae(modelPath, callback) {
var _this = this;
(0, _classCallCheck3.default)(this, Cvae);
/**
* Boolean value that specifies if the model has loaded.
* @type {boolean}
* @public
*/
this.ready = false;
this.model = {};
this.latentDim = tf.randomUniform([1, 16]);
this.modelPath = modelPath;
this.modelPathPrefix = '';
this.jsonLoader().then(function (val) {
_this.modelPathPrefix = _this.modelPath.split('manifest.json')[0];
_this.ready = (0, _callcallback2.default)(_this.loadCVAEModel(_this.modelPathPrefix + val.model), callback);
_this.labels = val.labels;
// get an array full of zero with the length of labels [0, 0, 0 ...]
_this.labelVector = Array(_this.labels.length + 1).fill(0);
});
}
// load tfjs model that is converted by tensorflowjs with graph and weights
(0, _createClass3.default)(Cvae, [{
key: 'loadCVAEModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(modelPath) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return tf.loadLayersModel(modelPath);
case 2:
this.model = _context.sent;
return _context.abrupt('return', this);
case 4:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadCVAEModel(_x) {
return _ref.apply(this, arguments);
}
return loadCVAEModel;
}()
/**
* Generate a random result.
* @param {String} label - A label of the feature your want to generate
* @param {function} callback - A function to handle the results of ".generate()". Likely a function to do something with the generated image data.
* @return {raw: ImageData, src: Blob, image: p5.Image}
*/
}, {
key: 'generate',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(label, callback) {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt('return', (0, _callcallback2.default)(this.generateInternal(label), callback));
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function generate(_x2, _x3) {
return _ref2.apply(this, arguments);
}
return generate;
}()
}, {
key: 'loadAsync',
value: function loadAsync(url) {
var _this2 = this;
return new _promise2.default(function (resolve, reject) {
if (!_this2.ready) reject();
loadImage(url, function (img) {
resolve(img);
});
});
}
}, {
key: 'getBlob',
value: function getBlob(inputCanvas) {
var _this3 = this;
return new _promise2.default(function (resolve, reject) {
if (!_this3.ready) reject();
inputCanvas.toBlob(function (blob) {
resolve(blob);
});
});
}
}, {
key: 'checkP5',
value: function checkP5() {
if (typeof window !== 'undefined' && window.p5 && this && window.p5.Image && typeof window.p5.Image === 'function') return true;
return false;
}
}, {
key: 'generateInternal',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(label) {
var _this4 = this;
var res, raws, canvas, ctx, _res$shape, x, y, imgData, data, i, src, image;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
res = tf.tidy(function () {
_this4.latentDim = tf.randomUniform([1, 16]);
var cursor = _this4.labels.indexOf(label);
if (cursor < 0) {
console.log('Wrong input of the label!');
return [undefined, undefined]; // invalid input just return;
}
_this4.labelVector = _this4.labelVector.map(function () {
return 0;
}); // clear vector
_this4.labelVector[cursor + 1] = 1;
var input = tf.tensor([_this4.labelVector]);
var temp = _this4.model.predict([_this4.latentDim, input]);
return temp.reshape([temp.shape[1], temp.shape[2], temp.shape[3]]);
});
_context3.next = 3;
return tf.browser.toPixels(res);
case 3:
raws = _context3.sent;
res.dispose();
canvas = document.createElement('canvas'); // consider using offScreneCanvas
ctx = canvas.getContext('2d');
_res$shape = (0, _slicedToArray3.default)(res.shape, 2), x = _res$shape[0], y = _res$shape[1];
canvas.width = x;
canvas.height = y;
imgData = ctx.createImageData(x, y);
data = imgData.data;
for (i = 0; i < x * y * 4; i += 1) {
data[i] = raws[i];
}ctx.putImageData(imgData, 0, 0);
_context3.t0 = URL;
_context3.next = 17;
return this.getBlob(canvas);
case 17:
_context3.t1 = _context3.sent;
src = _context3.t0.createObjectURL.call(_context3.t0, _context3.t1);
image = void 0;
/* global loadImage */
if (!this.checkP5()) {
_context3.next = 24;
break;
}
_context3.next = 23;
return this.loadAsync(src);
case 23:
image = _context3.sent;
case 24:
return _context3.abrupt('return', { src: src, raws: raws, image: image });
case 25:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function generateInternal(_x4) {
return _ref3.apply(this, arguments);
}
return generateInternal;
}()
}, {
key: 'jsonLoader',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4() {
var _this5 = this;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
return _context4.abrupt('return', new _promise2.default(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', _this5.modelPath);
xhr.onload = function () {
var json = JSON.parse(xhr.responseText);
resolve(json);
};
xhr.onerror = function (error) {
reject(error);
};
xhr.send();
}));
case 1:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function jsonLoader() {
return _ref4.apply(this, arguments);
}
return jsonLoader;
}()
}]);
return Cvae;
}();
var CVAE = function CVAE(model, callback) {
return new Cvae(model, callback);
};
exports.default = CVAE;
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _imageUtilities = __webpack_require__(46);
var _p5Utils = __webpack_require__(83);
var _p5Utils2 = _interopRequireDefault(_p5Utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
Image Classifier using pre-trained networks
*/
var DEFAULTS = {
modelPath: 'https://raw.githubusercontent.com/zaidalyafeai/HostedModels/master/unet-128/model.json',
imageSize: 128,
returnTensors: false
};
var UNET = function () {
/**
* Create UNET class.
* @param {HTMLVideoElement | HTMLImageElement} video - The video or image to be used for segmentation.
* @param {Object} options - Optional. A set of options.
* @param {function} callback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise
* that will be resolved once the model has loaded.
*/
function UNET(video, options, callback) {
(0, _classCallCheck3.default)(this, UNET);
this.modelReady = false;
this.isPredicting = false;
this.config = {
modelPath: typeof options.modelPath !== 'undefined' ? options.modelPath : DEFAULTS.modelPath,
imageSize: typeof options.imageSize !== 'undefined' ? options.imageSize : DEFAULTS.imageSize,
returnTensors: typeof options.returnTensors !== 'undefined' ? options.returnTensors : DEFAULTS.returnTensors
};
this.ready = (0, _callcallback2.default)(this.loadModel(), callback);
}
(0, _createClass3.default)(UNET, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return tf.loadLayersModel(this.config.modelPath);
case 2:
this.model = _context.sent;
this.modelReady = true;
return _context.abrupt('return', this);
case 5:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
}, {
key: 'segment',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputOrCallback, cb) {
var imgToPredict, callback;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.ready;
case 2:
imgToPredict = void 0;
callback = cb;
if (inputOrCallback instanceof HTMLImageElement || inputOrCallback instanceof HTMLVideoElement || inputOrCallback instanceof HTMLCanvasElement || inputOrCallback instanceof ImageData) {
imgToPredict = inputOrCallback;
} else if ((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === 'object' && (inputOrCallback.elt instanceof HTMLImageElement || inputOrCallback.elt instanceof HTMLVideoElement || inputOrCallback.elt instanceof HTMLCanvasElement || inputOrCallback.elt instanceof ImageData)) {
imgToPredict = inputOrCallback.elt;
} else if (typeof inputOrCallback === 'function') {
imgToPredict = this.video;
callback = inputOrCallback;
}
return _context2.abrupt('return', (0, _callcallback2.default)(this.segmentInternal(imgToPredict), callback));
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function segment(_x, _x2) {
return _ref2.apply(this, arguments);
}
return segment;
}()
}, {
key: 'convertToP5Image',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(tfBrowserPixelImage) {
var blob1, p5Image1;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return _p5Utils2.default.rawToBlob(tfBrowserPixelImage, this.config.imageSize, this.config.imageSize);
case 2:
blob1 = _context3.sent;
_context3.next = 5;
return _p5Utils2.default.blobToP5Image(blob1);
case 5:
p5Image1 = _context3.sent;
return _context3.abrupt('return', p5Image1);
case 7:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function convertToP5Image(_x3) {
return _ref3.apply(this, arguments);
}
return convertToP5Image;
}()
}, {
key: 'segmentInternal',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(imgToPredict) {
var _this = this;
var _tf$tidy, featureMask, backgroundMask, segmentation, maskFeat, maskBg, mask, maskFeatDom, maskBgDom, maskFeatBlob, maskBgBlob, pFeatureMask, pBgMask, pMask;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.ready;
case 2:
if (!(imgToPredict instanceof HTMLVideoElement)) {
_context4.next = 5;
break;
}
_context4.next = 5;
return tf.nextFrame();
case 5:
this.isPredicting = true;
_tf$tidy = tf.tidy(function () {
// preprocess the input image
var tfImage = tf.browser.fromPixels(imgToPredict).toFloat();
var resizedImg = tf.image.resizeBilinear(tfImage, [_this.config.imageSize, _this.config.imageSize]);
var normTensor = resizedImg.div(tf.scalar(255));
var batchedImage = normTensor.expandDims(0);
// get the segmentation
var pred = _this.model.predict(batchedImage);
// add back the alpha channel to the normalized input image
var alpha = tf.ones([128, 128, 1]).tile([1, 1, 1]);
normTensor = normTensor.concat(alpha, 2);
// TODO: optimize these redundancies below, e.g. repetitive squeeze() etc
// get the background mask;
var maskBackgroundInternal = pred.squeeze([0]);
maskBackgroundInternal = maskBackgroundInternal.tile([1, 1, 4]);
maskBackgroundInternal = maskBackgroundInternal.sub(0.3).sign().relu().neg().add(1);
var featureMaskInternal = maskBackgroundInternal.mul(normTensor);
// get the feature mask;
var maskFeature = pred.squeeze([0]);
maskFeature = maskFeature.tile([1, 1, 4]);
maskFeature = maskFeature.sub(0.3).sign().relu();
var backgroundMaskInternal = maskFeature.mul(normTensor);
var alpha255 = tf.ones([128, 128, 1]).tile([1, 1, 1]).mul(255);
var newpred = pred.squeeze([0]);
newpred = tf.cast(newpred.tile([1, 1, 3]).sub(0.3).sign().relu().mul(255), 'int32');
newpred = newpred.concat(alpha255, 2);
return {
featureMask: featureMaskInternal,
backgroundMask: backgroundMaskInternal,
segmentation: newpred
};
}), featureMask = _tf$tidy.featureMask, backgroundMask = _tf$tidy.backgroundMask, segmentation = _tf$tidy.segmentation;
this.isPredicting = false;
// these come first because array3DToImage() will dispose of the input tensor
_context4.next = 10;
return tf.browser.toPixels(featureMask);
case 10:
maskFeat = _context4.sent;
_context4.next = 13;
return tf.browser.toPixels(backgroundMask);
case 13:
maskBg = _context4.sent;
_context4.next = 16;
return tf.browser.toPixels(segmentation);
case 16:
mask = _context4.sent;
maskFeatDom = (0, _imageUtilities.array3DToImage)(featureMask);
maskBgDom = (0, _imageUtilities.array3DToImage)(backgroundMask);
maskFeatBlob = UNET.dataURLtoBlob(maskFeatDom.src);
maskBgBlob = UNET.dataURLtoBlob(maskBgDom.src);
pFeatureMask = void 0;
pBgMask = void 0;
pMask = void 0;
if (!_p5Utils2.default.checkP5()) {
_context4.next = 34;
break;
}
_context4.next = 27;
return this.convertToP5Image(maskFeat);
case 27:
pFeatureMask = _context4.sent;
_context4.next = 30;
return this.convertToP5Image(maskBg);
case 30:
pBgMask = _context4.sent;
_context4.next = 33;
return this.convertToP5Image(mask);
case 33:
pMask = _context4.sent;
case 34:
if (!this.config.returnTensors) {
featureMask.dispose();
backgroundMask.dispose();
segmentation.dispose();
}
return _context4.abrupt('return', {
segmentation: mask,
blob: {
featureMask: maskFeatBlob,
backgroundMask: maskBgBlob
},
tensor: {
featureMask: featureMask,
backgroundMask: backgroundMask
},
raw: {
featureMask: maskFeat,
backgroundMask: maskBg
},
// returns if p5 is available
featureMask: pFeatureMask,
backgroundMask: pBgMask,
mask: pMask
});
case 36:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function segmentInternal(_x4) {
return _ref4.apply(this, arguments);
}
return segmentInternal;
}()
}], [{
key: 'dataURLtoBlob',
value: function dataURLtoBlob(dataurl) {
var arr = dataurl.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n) {
u8arr[n] = bstr.charCodeAt(n);
n -= 1;
}
return new Blob([u8arr], {
type: mime
});
}
}]);
return UNET;
}();
var uNet = function uNet(videoOr, optionsOr, cb) {
var video = null;
var options = {};
var callback = cb;
if (videoOr instanceof HTMLVideoElement) {
video = videoOr;
} else if ((typeof videoOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOr)) === 'object' && videoOr.elt instanceof HTMLVideoElement) {
video = videoOr.elt; // Handle p5.js image
} else if (typeof videoOr === 'function') {
callback = videoOr;
} else if ((typeof videoOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOr)) === 'object') {
options = videoOr;
}
if ((typeof optionsOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOr)) === 'object') {
options = optionsOr;
} else if (typeof optionsOr === 'function') {
callback = optionsOr;
}
return new UNET(video, options, callback);
};
exports.default = uNet;
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(23);
var aFunction = __webpack_require__(109);
var ctx = __webpack_require__(56);
var forOf = __webpack_require__(100);
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) {
var mapFn = arguments[1];
var mapping, A, n, cb;
aFunction(this);
mapping = mapFn !== undefined;
if (mapping) aFunction(mapFn);
if (source == undefined) return new this();
A = [];
if (mapping) {
n = 0;
cb = ctx(mapFn, arguments[2], 2);
forOf(source, false, function (nextItem) {
A.push(cb(nextItem, n++));
});
} else {
forOf(source, false, A.push, A);
}
return new this(A);
} });
};
/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
__webpack_require__(319)('Set');
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-setmap-offrom/
var $export = __webpack_require__(23);
module.exports = function (COLLECTION) {
$export($export.S, COLLECTION, { of: function of() {
var length = arguments.length;
var A = new Array(length);
while (length--) A[length] = arguments[length];
return new this(A);
} });
};
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
__webpack_require__(321)('Set');
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(100);
module.exports = function (iter, ITERATOR) {
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __webpack_require__(116);
var from = __webpack_require__(323);
module.exports = function (NAME) {
return function toJSON() {
if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(23);
$export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(324)('Set') });
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(38);
var isArray = __webpack_require__(221);
var SPECIES = __webpack_require__(25)('species');
module.exports = function (original) {
var C;
if (isArray(original)) {
C = original.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(326);
module.exports = function (original, length) {
return new (speciesConstructor(original))(length);
};
/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(56);
var IObject = __webpack_require__(163);
var toObject = __webpack_require__(65);
var toLength = __webpack_require__(122);
var asc = __webpack_require__(327);
module.exports = function (TYPE, $create) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
var create = $create || asc;
return function ($this, callbackfn, that) {
var O = toObject($this);
var self = IObject(O);
var f = ctx(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var val, res;
for (;length > index; index++) if (NO_HOLES || index in self) {
val = self[index];
res = f(val, index, O);
if (TYPE) {
if (IS_MAP) result[index] = res; // map
else if (res) switch (TYPE) {
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ }),
/* 329 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(26);
var $export = __webpack_require__(23);
var meta = __webpack_require__(146);
var fails = __webpack_require__(68);
var hide = __webpack_require__(60);
var redefineAll = __webpack_require__(148);
var forOf = __webpack_require__(100);
var anInstance = __webpack_require__(151);
var isObject = __webpack_require__(38);
var setToStringTag = __webpack_require__(102);
var dP = __webpack_require__(39).f;
var each = __webpack_require__(328)(0);
var DESCRIPTORS = __webpack_require__(32);
module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) {
var Base = global[NAME];
var C = Base;
var ADDER = IS_MAP ? 'set' : 'add';
var proto = C && C.prototype;
var O = {};
if (!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () {
new C().entries().next();
}))) {
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
C = wrapper(function (target, iterable) {
anInstance(target, C, NAME, '_c');
target._c = new Base();
if (iterable != undefined) forOf(iterable, IS_MAP, target[ADDER], target);
});
each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','), function (KEY) {
var IS_ADDER = KEY == 'add' || KEY == 'set';
if (KEY in proto && !(IS_WEAK && KEY == 'clear')) hide(C.prototype, KEY, function (a, b) {
anInstance(this, C, KEY);
if (!IS_ADDER && IS_WEAK && !isObject(a)) return KEY == 'get' ? undefined : false;
var result = this._c[KEY](a === 0 ? 0 : a, b);
return IS_ADDER ? this : result;
});
});
IS_WEAK || dP(C.prototype, 'size', {
get: function () {
return this._c.size;
}
});
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F, O);
if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ }),
/* 330 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var dP = __webpack_require__(39).f;
var create = __webpack_require__(117);
var redefineAll = __webpack_require__(148);
var ctx = __webpack_require__(56);
var anInstance = __webpack_require__(151);
var forOf = __webpack_require__(100);
var $iterDefine = __webpack_require__(152);
var step = __webpack_require__(231);
var setSpecies = __webpack_require__(224);
var DESCRIPTORS = __webpack_require__(32);
var fastKey = __webpack_require__(146).fastKey;
var validate = __webpack_require__(202);
var SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function (that, key) {
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return that._i[index];
// frozen object case
for (entry = that._f; entry; entry = entry.n) {
if (entry.k == key) return entry;
}
};
module.exports = {
getConstructor: function (wrapper, NAME, IS_MAP, ADDER) {
var C = wrapper(function (that, iterable) {
anInstance(that, C, NAME, '_i');
that._t = NAME; // collection type
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear() {
for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) {
entry.r = true;
if (entry.p) entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function (key) {
var that = validate(this, NAME);
var entry = getEntry(that, key);
if (entry) {
var next = entry.n;
var prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if (prev) prev.n = next;
if (next) next.p = prev;
if (that._f == entry) that._f = next;
if (that._l == entry) that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /* , that = undefined */) {
validate(this, NAME);
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);
var entry;
while (entry = entry ? entry.n : this._f) {
f(entry.v, entry.k, this);
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key) {
return !!getEntry(validate(this, NAME), key);
}
});
if (DESCRIPTORS) dP(C.prototype, 'size', {
get: function () {
return validate(this, NAME)[SIZE];
}
});
return C;
},
def: function (that, key, value) {
var entry = getEntry(that, key);
var prev, index;
// change existing entry
if (entry) {
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if (!that._f) that._f = entry;
if (prev) prev.n = entry;
that[SIZE]++;
// add to index
if (index !== 'F') that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function (C, NAME, IS_MAP) {
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function (iterated, kind) {
this._t = validate(iterated, NAME); // target
this._k = kind; // kind
this._l = undefined; // previous
}, function () {
var that = this;
var kind = that._k;
var entry = that._l;
// revert to the last existing entry
while (entry && entry.r) entry = entry.p;
// get next entry
if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) {
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if (kind == 'keys') return step(0, entry.k);
if (kind == 'values') return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var strong = __webpack_require__(330);
var validate = __webpack_require__(202);
var SET = 'Set';
// 23.2 Set Objects
module.exports = __webpack_require__(329)(SET, function (get) {
return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value) {
return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ }),
/* 332 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(153);
__webpack_require__(85);
__webpack_require__(101);
__webpack_require__(331);
__webpack_require__(325);
__webpack_require__(322);
__webpack_require__(320);
module.exports = __webpack_require__(18).Set;
/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _set = __webpack_require__(203);
var _set2 = _interopRequireDefault(_set);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var models = ['alarm_clock', 'ambulance', 'angel', 'ant', 'antyoga', 'backpack', 'barn', 'basket', 'bear', 'bee', 'beeflower', 'bicycle', 'bird', 'book', 'brain', 'bridge', 'bulldozer', 'bus', 'butterfly', 'cactus', 'calendar', 'castle', 'cat', 'catbus', 'catpig', 'chair', 'couch', 'crab', 'crabchair', 'crabrabbitfacepig', 'cruise_ship', 'diving_board', 'dog', 'dogbunny', 'dolphin', 'duck', 'elephant', 'elephantpig', 'eye', 'face', 'fan', 'fire_hydrant', 'firetruck', 'flamingo', 'flower', 'floweryoga', 'frog', 'frogsofa', 'garden', 'hand', 'hedgeberry', 'hedgehog', 'helicopter', 'kangaroo', 'key', 'lantern', 'lighthouse', 'lion', 'lionsheep', 'lobster', 'map', 'mermaid', 'monapassport', 'monkey', 'mosquito', 'octopus', 'owl', 'paintbrush', 'palm_tree', 'parrot', 'passport', 'peas', 'penguin', 'pig', 'pigsheep', 'pineapple', 'pool', 'postcard', 'power_outlet', 'rabbit', 'rabbitturtle', 'radio', 'radioface', 'rain', 'rhinoceros', 'rifle', 'roller_coaster', 'sandwich', 'scorpion', 'sea_turtle', 'sheep', 'skull', 'snail', 'snowflake', 'speedboat', 'spider', 'squirrel', 'steak', 'stove', 'strawberry', 'swan', 'swing_set', 'the_mona_lisa', 'tiger', 'toothbrush', 'toothpaste', 'tractor', 'trombone', 'truck', 'whale', 'windmill', 'yoga', 'yogabicycle', 'everything'];
var modelPaths = new _set2.default(models);
exports.default = modelPaths;
/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function stringToUint8array(b64encoded) {
var u8 = new Uint8Array(atob(b64encoded)
.split("")
.map(function (c) {
return c.charCodeAt(0);
}));
return u8;
}
exports.stringToUint8array = stringToUint8array;
function stringToArray(b64encoded) {
var u = stringToUint8array(b64encoded);
var result = new Int16Array(u.buffer);
return result;
}
exports.stringToArray = stringToArray;
var returnV = false;
var vVal = 0.0;
function gaussRandom() {
if (returnV) {
returnV = false;
return vVal;
}
var u = 2 * Math.random() - 1;
var v = 2 * Math.random() - 1;
var r = u * u + v * v;
if (r === 0 || r > 1) {
return gaussRandom();
}
var c = Math.sqrt(-2 * Math.log(r) / r);
vVal = v * c;
returnV = true;
return u * c;
}
exports.gaussRandom = gaussRandom;
function randf(a, b) {
return Math.random() * (b - a) + a;
}
exports.randf = randf;
function randi(a, b) {
return Math.floor(Math.random() * (b - a) + a);
}
exports.randi = randi;
function randn(mu, std) {
return mu + gaussRandom() * std;
}
exports.randn = randn;
function birandn(mu1, mu2, std1, std2, rho) {
var z1 = randn(0, 1);
var z2 = randn(0, 1);
var x = Math.sqrt(1 - rho * rho) * std1 * z1 + rho * std1 * z2 + mu1;
var y = std2 * z2 + mu2;
return [x, y];
}
exports.birandn = birandn;
function sampleSoftmax(zSample) {
var x = randf(0, 1);
var N = zSample.length;
var accumulate = 0;
var i;
for (i = 0; i < N; i++) {
accumulate += zSample[i];
if (accumulate >= x) {
return i;
}
}
console.log('error sampling pi index');
return -1;
}
exports.sampleSoftmax = sampleSoftmax;
function simplifyLine(V, tolerance) {
if (tolerance === void 0) { tolerance = 2.0; }
var tol = tolerance;
function diff(u, v) {
return [u[0] - v[0], u[1] - v[1]];
}
function dot(u, v) {
return u[0] * v[0] + u[1] * v[1];
}
function norm2(v) {
return v[0] * v[0] + v[1] * v[1];
}
function d2(u, v) { return norm2(diff(u, v)); }
function simplifyDP(tol, v, j, k, mk) {
if (k <= j + 1) {
return;
}
var maxi = j;
var maxd2 = 0;
var tol2 = tol * tol;
var S = [v[j], v[k]];
var u = diff(S[1], S[0]);
var cu = norm2(u);
var w;
var pb;
var b, cw, dv2;
for (var i_1 = j + 1; i_1 < k; i_1++) {
w = diff(v[i_1], S[0]);
cw = dot(w, u);
if (cw <= 0) {
dv2 = d2(v[i_1], S[0]);
}
else if (cu <= cw) {
dv2 = d2(v[i_1], S[1]);
}
else {
b = cw / cu;
pb = [S[0][0] + b * u[0], S[0][1] + b * u[1]];
dv2 = d2(v[i_1], pb);
}
if (dv2 <= maxd2) {
continue;
}
maxi = i_1;
maxd2 = dv2;
}
if (maxd2 > tol2) {
mk[maxi] = 1;
simplifyDP(tol, v, j, maxi, mk);
simplifyDP(tol, v, maxi, k, mk);
}
return;
}
var n = V.length;
var sV = [];
var i, k, m, pv;
var tol2 = tol * tol;
var vt = [];
var mk = [];
vt[0] = V[0];
for (i = k = 1, pv = 0; i < n; i++) {
if (d2(V[i], V[pv]) < tol2) {
continue;
}
vt[k++] = V[i];
pv = i;
}
if (pv < n - 1) {
vt[k++] = V[n - 1];
}
mk[0] = mk[k - 1] = 1;
simplifyDP(tol, vt, 0, k - 1, mk);
for (i = m = 0; i < k; i++) {
if (mk[i]) {
sV[m++] = vt[i];
}
}
return sV;
}
exports.simplifyLine = simplifyLine;
function simplifyLines(lines, tolerance) {
var result = [];
var tol = 2.0;
if (tolerance) {
tol = tolerance;
}
for (var i = 0; i < lines.length; i++) {
result.push(simplifyLine(lines[i], tol));
}
return result;
}
exports.simplifyLines = simplifyLines;
function linesToStrokes(rawData) {
var x, y;
var px = 0, py = 0;
var dx, dy;
var pon, poff;
var stroke = [];
var i, j;
var len;
var p;
for (i = 0; i < rawData.length; i++) {
len = rawData[i].length;
if (len > 1) {
for (j = 0; j < len; j++) {
p = rawData[i][j];
x = p[0];
y = p[1];
if (j === len - 1) {
poff = 1;
pon = 0;
}
else {
poff = 0;
pon = 1;
}
dx = x - px;
dy = y - py;
px = x;
py = y;
stroke.push([dx, dy, pon, poff, 0]);
}
}
}
stroke.push([0, 0, 0, 0, 1]);
return stroke.slice(1);
}
exports.linesToStrokes = linesToStrokes;
function lineToStroke(line, lastPoint) {
var pon, poff;
var stroke = [];
var len;
var p;
var dx, dy;
var x, y;
var px, py;
var j;
px = lastPoint[0];
py = lastPoint[1];
len = line.length;
if (len > 1) {
for (j = 0; j < len; j++) {
p = line[j];
x = p[0];
y = p[1];
if (j === len - 1) {
poff = 1;
pon = 0;
}
else {
poff = 0;
pon = 1;
}
dx = x - px;
dy = y - py;
px = x;
py = y;
stroke.push([dx, dy, pon, poff, 0]);
}
}
return stroke;
}
exports.lineToStroke = lineToStroke;
//# sourceMappingURL=sketch_support.js.map
/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var tf = __webpack_require__(0);
var support = __webpack_require__(334);
var SketchRNN = (function () {
function SketchRNN(checkpointURL) {
this.NMIXTURE = 20;
this.checkpointURL = checkpointURL;
this.initialized = false;
}
SketchRNN.prototype.isInitialized = function () {
return this.initialized;
};
SketchRNN.prototype.instantiateFromJSON = function (info, weightDims, weightStrings) {
this.forgetBias = tf.scalar(1.0);
this.info = info;
this.setPixelFactor(2.0);
this.weightDims = weightDims;
this.numUnits = this.weightDims[0][0];
var rawWeights;
var maxWeight = 10.0;
this.weights = [];
for (var i = 0; i < weightStrings.length; i++) {
rawWeights = new Float32Array(support.stringToArray(weightStrings[i]));
var N = rawWeights.length;
for (var j = 0; j < N; j++) {
rawWeights[j] = maxWeight * rawWeights[j] / 32767;
}
this.weights.push(rawWeights);
}
this.outputKernel = tf.tensor2d(this.weights[0], [this.weightDims[0][0], this.weightDims[0][1]]);
this.outputBias = tf.tensor1d(this.weights[1]);
var lstmKernelXH = tf.tensor2d(this.weights[2], [this.weightDims[2][0], this.weightDims[2][1]]);
var lstmKernelHH = tf.tensor2d(this.weights[3], [this.weightDims[3][0], this.weightDims[3][1]]);
var axis = 0;
this.lstmKernel = tf.concat2d([lstmKernelXH, lstmKernelHH], axis);
this.lstmBias = tf.tensor1d(this.weights[4]);
this.rawVars = [
this.outputKernel,
this.outputBias,
this.lstmKernel,
this.lstmBias
];
};
SketchRNN.prototype.initialize = function () {
return __awaiter(this, void 0, void 0, function () {
var vars;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.dispose();
return [4, fetch(this.checkpointURL)
.then(function (response) { return response.json(); })];
case 1:
vars = _a.sent();
this.instantiateFromJSON(vars[0], vars[1], vars[2]);
this.initialized = true;
console.log('Initialized SketchRNN.');
return [2];
}
});
});
};
SketchRNN.prototype.dispose = function () {
if (this.rawVars) {
for (var i = 0; i < this.rawVars.length; i++) {
this.rawVars[i].dispose();
}
this.rawVars = undefined;
}
if (this.forgetBias) {
this.forgetBias.dispose();
this.forgetBias = undefined;
}
this.initialized = false;
};
SketchRNN.prototype.setPixelFactor = function (scale) {
this.pixelFactor = scale;
this.scaleFactor = this.info.scale_factor / this.pixelFactor;
};
SketchRNN.prototype.update = function (stroke, state) {
var _this = this;
var out = tf.tidy(function () {
var numUnits = _this.numUnits;
var s = _this.scaleFactor;
var normStroke = [stroke[0] / s, stroke[1] / s, stroke[2], stroke[3], stroke[4]];
var x = tf.tensor2d(normStroke, [1, 5]);
var c = tf.tensor2d(state.c, [1, numUnits]);
var h = tf.tensor2d(state.h, [1, numUnits]);
var newState = tf.basicLSTMCell(_this.forgetBias, _this.lstmKernel, _this.lstmBias, x, c, h);
return tf.concat(newState, 1);
});
var newCH = out.dataSync();
out.dispose();
var newC = newCH.slice(0, this.numUnits);
var newH = newCH.slice(this.numUnits, this.numUnits * 2);
var finalState = {
c: new Float32Array(newC),
h: new Float32Array(newH)
};
return finalState;
};
SketchRNN.prototype.updateStrokes = function (strokes, state, steps) {
var _this = this;
var out = tf.tidy(function () {
var numUnits = _this.numUnits;
var s = _this.scaleFactor;
var normStroke;
var x;
var c;
var h;
var newState;
var numSteps = strokes.length;
if (steps) {
numSteps = steps;
}
c = tf.tensor2d(state.c, [1, numUnits]);
h = tf.tensor2d(state.h, [1, numUnits]);
for (var i = 0; i < numSteps; i++) {
normStroke = [strokes[i][0] / s,
strokes[i][1] / s,
strokes[i][2],
strokes[i][3],
strokes[i][4]];
x = tf.tensor2d(normStroke, [1, 5]);
newState = tf.basicLSTMCell(_this.forgetBias, _this.lstmKernel, _this.lstmBias, x, c, h);
c = newState[0];
h = newState[1];
}
return tf.concat(newState, 1);
});
var newCH = out.dataSync();
out.dispose();
var newC = newCH.slice(0, this.numUnits);
var newH = newCH.slice(this.numUnits, this.numUnits * 2);
var finalState = {
c: new Float32Array(newC),
h: new Float32Array(newH)
};
return finalState;
};
SketchRNN.prototype.getPDF = function (state, temperature, softmaxTemperature) {
var _this = this;
if (temperature === void 0) { temperature = 0.65; }
var temp = temperature;
var discreteTemp = 0.5 + temp * 0.5;
if (softmaxTemperature) {
discreteTemp = softmaxTemperature;
}
var NOUT = this.NMIXTURE;
var out = tf.tidy(function () {
var numUnits = _this.numUnits;
var h = tf.tensor2d(state.h, [1, numUnits]);
var sqrttemp = tf.scalar(Math.sqrt(temp));
var softtemp = tf.scalar(discreteTemp);
var z = tf.add(tf.matMul(h, _this.outputKernel), _this.outputBias)
.squeeze();
var _a = tf.split(z, [3, NOUT * 6]), rawPen = _a[0], rst = _a[1];
var _b = tf.split(rst, 6), rawPi = _b[0], mu1 = _b[1], mu2 = _b[2], rawSigma1 = _b[3], rawSigma2 = _b[4], rawCorr = _b[5];
var pen = tf.softmax(rawPen.div(softtemp));
var pi = tf.softmax(rawPi.div(softtemp));
var sigma1 = tf.exp(rawSigma1).mul(sqrttemp);
var sigma2 = tf.exp(rawSigma2).mul(sqrttemp);
var corr = tf.tanh(rawCorr);
var result = [pi, mu1, mu2, sigma1, sigma2, corr, pen];
return tf.concat(result);
});
var result = out.dataSync();
out.dispose();
var pdf = {
pi: new Float32Array(result.slice(0, NOUT)),
muX: new Float32Array(result.slice(1 * NOUT, 2 * NOUT)),
muY: new Float32Array(result.slice(2 * NOUT, 3 * NOUT)),
sigmaX: new Float32Array(result.slice(3 * NOUT, 4 * NOUT)),
sigmaY: new Float32Array(result.slice(4 * NOUT, 15 * NOUT)),
corr: new Float32Array(result.slice(5 * NOUT, 6 * NOUT)),
pen: new Float32Array(result.slice(6 * NOUT, 6 * NOUT + 3))
};
return pdf;
};
SketchRNN.prototype.zeroState = function () {
var result = {
c: new Float32Array(this.numUnits),
h: new Float32Array(this.numUnits)
};
return result;
};
SketchRNN.prototype.copyState = function (rnnState) {
var result = {
c: new Float32Array(rnnState.c),
h: new Float32Array(rnnState.h)
};
return result;
};
SketchRNN.prototype.zeroInput = function () {
return [0, 0, 1, 0, 0];
};
SketchRNN.prototype.sample = function (pdf) {
var idx = support.sampleSoftmax(pdf.pi);
var mu1 = pdf.muX[idx];
var mu2 = pdf.muY[idx];
var sigma1 = pdf.sigmaX[idx];
var sigma2 = pdf.sigmaY[idx];
var corr = pdf.corr[idx];
var penIdx = support.sampleSoftmax(pdf.pen);
var penstate = [0, 0, 0];
penstate[penIdx] = 1;
var delta = support.birandn(mu1, mu2, sigma1, sigma2, corr);
var stroke = [
delta[0] * this.scaleFactor,
delta[1] * this.scaleFactor,
penstate[0],
penstate[1],
penstate[2]
];
return stroke;
};
SketchRNN.prototype.simplifyLine = function (line, tolerance) {
return support.simplifyLine(line, tolerance);
};
SketchRNN.prototype.simplifyLines = function (lines, tolerance) {
return support.simplifyLines(lines, tolerance);
};
SketchRNN.prototype.linesToStroke = function (lines) {
return support.linesToStrokes(lines);
};
SketchRNN.prototype.lineToStroke = function (line, lastPoint) {
return support.lineToStroke(line, lastPoint);
};
return SketchRNN;
}());
exports.SketchRNN = SketchRNN;
//# sourceMappingURL=model.js.map
/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var model_1 = __webpack_require__(335);
exports.SketchRNN = model_1.SketchRNN;
//# sourceMappingURL=index.js.map
/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var tf = __webpack_require__(4);
exports.tf = tf;
__export(__webpack_require__(336));
//# sourceMappingURL=index.js.map
/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _sketch = __webpack_require__(337);
var ms = _interopRequireWildcard(_sketch);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _models = __webpack_require__(333);
var _models2 = _interopRequireDefault(_models);
var _modelLoader = __webpack_require__(142);
var _modelLoader2 = _interopRequireDefault(_modelLoader);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// const PATH_START_LARGE = 'https://storage.googleapis.com/quickdraw-models/sketchRNN/large_models/';
// const PATH_START_SMALL = 'https://storage.googleapis.com/quickdraw-models/sketchRNN/models/';
// const PATH_END = '.gen.json';
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ['error', {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: 'off' */
/*
SketchRNN
*/
var DEFAULTS = {
modelPath: 'https://storage.googleapis.com/quickdraw-models/sketchRNN/large_models/',
modelPath_large: 'https://storage.googleapis.com/quickdraw-models/sketchRNN/models/',
modelPath_small: 'https://storage.googleapis.com/quickdraw-models/sketchRNN/models/',
PATH_END: '.gen.json',
temperature: 0.65,
pixelFactor: 3.0
};
var SketchRNN = function () {
/**
* Create SketchRNN.
* @param {String} model - The name of the sketch model to be loaded.
* The names can be found in the models.js file
* @param {function} callback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise
* that will be resolved once the model has loaded.
*/
function SketchRNN(model, callback) {
var large = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
(0, _classCallCheck3.default)(this, SketchRNN);
var checkpointUrl = model;
this.config = {
temperature: 0.65,
pixelFactor: 3.0,
modelPath: DEFAULTS.modelPath,
modelPath_small: DEFAULTS.modelPath_small,
modelPath_large: DEFAULTS.modelPath_large,
PATH_END: DEFAULTS.PATH_END
};
if (_modelLoader2.default.isAbsoluteURL(checkpointUrl) === true) {
var modelPath = _modelLoader2.default.getModelPath(checkpointUrl);
this.config.modelPath = modelPath;
} else if (_models2.default.has(checkpointUrl)) {
checkpointUrl = (large ? this.config.modelPath : this.config.modelPath_small) + checkpointUrl + this.config.PATH_END;
this.config.modelPath = checkpointUrl;
} else {
console.log('no model found!');
return this;
}
this.model = new ms.SketchRNN(this.config.modelPath);
this.penState = this.model.zeroInput();
this.ready = (0, _callcallback2.default)(this.model.initialize(), callback);
}
(0, _createClass3.default)(SketchRNN, [{
key: 'generateInternal',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(options, strokes) {
var temperature, pixelFactor, pdf, result;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
temperature = +options.temperature || this.config.temperature;
pixelFactor = +options.pixelFactor || this.config.pixelFactor;
_context.next = 4;
return this.ready;
case 4:
if (!this.rnnState) {
this.rnnState = this.model.zeroState();
this.model.setPixelFactor(pixelFactor);
}
if (Array.isArray(strokes) && strokes.length) {
this.rnnState = this.model.updateStrokes(strokes, this.rnnState);
}
this.rnnState = this.model.update(this.penState, this.rnnState);
pdf = this.model.getPDF(this.rnnState, temperature);
this.penState = this.model.sample(pdf);
result = {
dx: this.penState[0],
dy: this.penState[1]
};
if (this.penState[2] === 1) {
result.pen = 'down';
} else if (this.penState[3] === 1) {
result.pen = 'up';
} else if (this.penState[4] === 1) {
result.pen = 'end';
}
return _context.abrupt('return', result);
case 12:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function generateInternal(_x2, _x3) {
return _ref.apply(this, arguments);
}
return generateInternal;
}()
}, {
key: 'generate',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(optionsOrSeedOrCallback, seedOrCallback, cb) {
var callback, options, seedStrokes, strokes;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
callback = void 0;
options = void 0;
seedStrokes = void 0;
if (typeof optionsOrSeedOrCallback === 'function') {
options = {};
seedStrokes = [];
callback = optionsOrSeedOrCallback;
} else if (Array.isArray(optionsOrSeedOrCallback)) {
options = {};
seedStrokes = optionsOrSeedOrCallback;
callback = seedOrCallback;
} else if (typeof seedOrCallback === 'function') {
options = optionsOrSeedOrCallback || {};
seedStrokes = [];
callback = seedOrCallback;
} else {
options = optionsOrSeedOrCallback || {};
seedStrokes = seedOrCallback || [];
callback = cb;
}
strokes = seedStrokes.map(function (s) {
var up = s.pen === 'up' ? 1 : 0;
var down = s.pen === 'down' ? 1 : 0;
var end = s.pen === 'end' ? 1 : 0;
return [s.dx, s.dy, down, up, end];
});
return _context2.abrupt('return', (0, _callcallback2.default)(this.generateInternal(options, strokes), callback));
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function generate(_x4, _x5, _x6) {
return _ref2.apply(this, arguments);
}
return generate;
}()
}, {
key: 'reset',
value: function reset() {
this.penState = this.model.zeroInput();
if (this.rnnState) {
this.rnnState = this.model.zeroState();
}
}
}]);
return SketchRNN;
}();
var sketchRNN = function sketchRNN(model, callback) {
var large = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
return new SketchRNN(model, callback, large);
};
exports.default = sketchRNN;
/***/ }),
/* 339 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CheckpointLoaderPix2pix = function () {
function CheckpointLoaderPix2pix(urlPath) {
(0, _classCallCheck3.default)(this, CheckpointLoaderPix2pix);
this.urlPath = urlPath;
}
(0, _createClass3.default)(CheckpointLoaderPix2pix, [{
key: 'getAllVariables',
value: function getAllVariables() {
var _this = this;
return new _promise2.default(function (resolve, reject) {
var weightsCache = {};
if (_this.urlPath in weightsCache) {
resolve(weightsCache[_this.urlPath]);
return;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', _this.urlPath, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (xhr.status !== 200) {
reject(new Error('missing model'));
return;
}
var buf = xhr.response;
if (!buf) {
reject(new Error('invalid arraybuffer'));
return;
}
var parts = [];
var offset = 0;
while (offset < buf.byteLength) {
var b = new Uint8Array(buf.slice(offset, offset + 4));
offset += 4;
var len = (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + b[3]; // eslint-disable-line no-bitwise
parts.push(buf.slice(offset, offset + len));
offset += len;
}
var shapes = JSON.parse(new TextDecoder('utf8').decode(parts[0]));
var index = new Float32Array(parts[1]);
var encoded = new Uint8Array(parts[2]);
// decode using index
var arr = new Float32Array(encoded.length);
for (var i = 0; i < arr.length; i += 1) {
arr[i] = index[encoded[i]];
}
var weights = {};
offset = 0;
for (var _i = 0; _i < shapes.length; _i += 1) {
var shape = shapes[_i].shape;
var size = shape.reduce(function (total, num) {
return total * num;
});
var values = arr.slice(offset, offset + size);
var tfarr = tf.tensor1d(values, 'float32');
weights[shapes[_i].name] = tfarr.reshape(shape);
offset += size;
}
weightsCache[_this.urlPath] = weights;
resolve(weights);
};
xhr.send(null);
});
}
}]);
return CheckpointLoaderPix2pix;
}(); /* eslint max-len: "off" */
exports.default = CheckpointLoaderPix2pix;
/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _checkpointLoaderPix2pix = __webpack_require__(339);
var _checkpointLoaderPix2pix2 = _interopRequireDefault(_checkpointLoaderPix2pix);
var _imageUtilities = __webpack_require__(46);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint max-len: "off" */
/*
Pix2pix
The original pix2pix TensorFlow implementation was made by affinelayer: github.com/affinelayer/pix2pix-tensorflow
This version is heavily based on Christopher Hesse TensorFlow.js implementation: https://github.com/affinelayer/pix2pix-tensorflow/tree/master/server
*/
var Pix2pix = function () {
/**
* Create a Pix2pix model.
* @param {model} model - The path for a valid model.
* @param {function} callback - Optional. A function to run once the model has been loaded. If no callback is provided, it will return a promise that will be resolved once the model has loaded.
*/
function Pix2pix(model, callback) {
(0, _classCallCheck3.default)(this, Pix2pix);
/**
* Boolean to check if the model has loaded
* @type {boolean}
* @public
*/
this.ready = (0, _callcallback2.default)(this.loadCheckpoints(model), callback);
}
(0, _createClass3.default)(Pix2pix, [{
key: 'loadCheckpoints',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(path) {
var checkpointLoader;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
checkpointLoader = new _checkpointLoaderPix2pix2.default(path);
_context.next = 3;
return checkpointLoader.getAllVariables();
case 3:
this.variables = _context.sent;
return _context.abrupt('return', this);
case 5:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadCheckpoints(_x) {
return _ref.apply(this, arguments);
}
return loadCheckpoints;
}()
/**
* Given an canvas element, applies image-to-image translation using the provided model. Returns an image.
* @param {HTMLCanvasElement} inputElement
* @param {function} cb - A function to run once the model has made the transfer. If no callback is provided, it will return a promise that will be resolved once the model has made the transfer.
*/
}, {
key: 'transfer',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputElement, cb) {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt('return', (0, _callcallback2.default)(this.transferInternal(inputElement), cb));
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function transfer(_x2, _x3) {
return _ref2.apply(this, arguments);
}
return transfer;
}()
}, {
key: 'transferInternal',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(inputElement) {
var _this = this;
var result;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
result = (0, _imageUtilities.array3DToImage)(tf.tidy(function () {
var input = tf.browser.fromPixels(inputElement);
var inputData = input.dataSync();
var floatInput = tf.tensor3d(inputData, input.shape);
var normalizedInput = tf.div(floatInput, tf.scalar(255));
var preprocessedInput = Pix2pix.preprocess(normalizedInput);
var layers = [];
var filter = _this.variables['generator/encoder_1/conv2d/kernel'];
var bias = _this.variables['generator/encoder_1/conv2d/bias'];
var convolved = Pix2pix.conv2d(preprocessedInput, filter, bias);
layers.push(convolved);
for (var i = 2; i <= 8; i += 1) {
var scope = 'generator/encoder_' + i.toString();
filter = _this.variables[scope + '/conv2d/kernel'];
var bias2 = _this.variables[scope + '/conv2d/bias'];
var _layerInput = layers[layers.length - 1];
var rectified = tf.leakyRelu(_layerInput, 0.2);
convolved = Pix2pix.conv2d(rectified, filter, bias2);
var scale = _this.variables[scope + '/batch_normalization/gamma'];
var offset = _this.variables[scope + '/batch_normalization/beta'];
var normalized = Pix2pix.batchnorm(convolved, scale, offset);
layers.push(normalized);
}
for (var _i = 8; _i >= 2; _i -= 1) {
var _layerInput2 = void 0;
if (_i === 8) {
_layerInput2 = layers[layers.length - 1];
} else {
var skipLayer = _i - 1;
_layerInput2 = tf.concat([layers[layers.length - 1], layers[skipLayer]], 2);
}
var _rectified = tf.relu(_layerInput2);
var _scope = 'generator/decoder_' + _i.toString();
filter = _this.variables[_scope + '/conv2d_transpose/kernel'];
bias = _this.variables[_scope + '/conv2d_transpose/bias'];
convolved = Pix2pix.deconv2d(_rectified, filter, bias);
var _scale = _this.variables[_scope + '/batch_normalization/gamma'];
var _offset = _this.variables[_scope + '/batch_normalization/beta'];
var _normalized = Pix2pix.batchnorm(convolved, _scale, _offset);
layers.push(_normalized);
}
var layerInput = tf.concat([layers[layers.length - 1], layers[0]], 2);
var rectified2 = tf.relu(layerInput);
filter = _this.variables['generator/decoder_1/conv2d_transpose/kernel'];
var bias3 = _this.variables['generator/decoder_1/conv2d_transpose/bias'];
convolved = Pix2pix.deconv2d(rectified2, filter, bias3);
rectified2 = tf.tanh(convolved);
layers.push(rectified2);
var output = layers[layers.length - 1];
var deprocessedOutput = Pix2pix.deprocess(output);
return deprocessedOutput;
}));
_context3.next = 3;
return tf.nextFrame();
case 3:
return _context3.abrupt('return', result);
case 4:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function transferInternal(_x4) {
return _ref3.apply(this, arguments);
}
return transferInternal;
}()
}], [{
key: 'preprocess',
value: function preprocess(inputPreproc) {
var result = tf.tidy(function () {
return tf.sub(tf.mul(inputPreproc, tf.scalar(2)), tf.scalar(1));
});
inputPreproc.dispose();
return result;
}
}, {
key: 'deprocess',
value: function deprocess(inputDeproc) {
var result = tf.tidy(function () {
return tf.div(tf.add(inputDeproc, tf.scalar(1)), tf.scalar(2));
});
inputDeproc.dispose();
return result;
}
}, {
key: 'batchnorm',
value: function batchnorm(inputBat, scale, offset) {
var result = tf.tidy(function () {
var moments = tf.moments(inputBat, [0, 1]);
var varianceEpsilon = 1e-5;
return tf.batchNorm(inputBat, moments.mean, moments.variance, offset, scale, varianceEpsilon);
});
inputBat.dispose();
return result;
}
}, {
key: 'conv2d',
value: function conv2d(inputCon, filterCon) {
var tempFilter = filterCon.clone();
var result = tf.tidy(function () {
return tf.conv2d(inputCon, tempFilter, [2, 2], 'same');
});
inputCon.dispose();
tempFilter.dispose();
return result;
}
}, {
key: 'deconv2d',
value: function deconv2d(inputDeconv, filterDeconv, biasDecon) {
var result = tf.tidy(function () {
var convolved = tf.conv2dTranspose(inputDeconv, filterDeconv, [inputDeconv.shape[0] * 2, inputDeconv.shape[1] * 2, filterDeconv.shape[2]], [2, 2], 'same');
var biased = tf.add(convolved, biasDecon);
return biased;
});
inputDeconv.dispose();
filterDeconv.dispose();
biasDecon.dispose();
return result;
}
}]);
return Pix2pix;
}();
var pix2pix = function pix2pix(model, callback) {
var instance = new Pix2pix(model, callback);
return callback ? instance : instance.ready;
};
exports.default = pix2pix;
/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Utils for sampling
// Sample from a distrubution
var sampleFromDistribution = function sampleFromDistribution(input) {
var randomValue = Math.random();
var sum = 0;
var result = void 0;
for (var j = 0; j < input.length; j += 1) {
sum += input[j];
if (randomValue < sum) {
result = j;
break;
}
}
return result;
};
exports.default = sampleFromDistribution;
/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _sample = __webpack_require__(341);
var _sample2 = _interopRequireDefault(_sample);
var _checkpointLoader = __webpack_require__(204);
var _checkpointLoader2 = _interopRequireDefault(_checkpointLoader);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var regexCell = /cell_[0-9]|lstm_[0-9]/gi; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: false}}] */
/* eslint no-await-in-loop: "off" */
/*
A LSTM Generator: Run inference mode for a pre-trained LSTM.
*/
var regexWeights = /weights|weight|kernel|kernels|w/gi;
var regexFullyConnected = /softmax/gi;
var CharRNN = function () {
/**
* Create a CharRNN.
* @param {String} modelPath - The path to the trained charRNN model.
* @param {function} callback - Optional. A callback to be called once
* the model has loaded. If no callback is provided, it will return a
* promise that will be resolved once the model has loaded.
*/
function CharRNN(modelPath, callback) {
(0, _classCallCheck3.default)(this, CharRNN);
/**
* Boolean value that specifies if the model has loaded.
* @type {boolean}
* @public
*/
this.ready = false;
/**
* The pre-trained charRNN model.
* @type {model}
* @public
*/
this.model = {};
this.cellsAmount = 0;
this.cells = [];
this.zeroState = { c: [], h: [] };
/**
* The vocabulary size (or total number of possible characters).
* @type {c: Array, h: Array}
* @public
*/
this.state = { c: [], h: [] };
this.vocab = {};
this.vocabSize = 0;
this.probabilities = [];
this.defaults = {
seed: "a", // TODO: use no seed by default
length: 20,
temperature: 0.5,
stateful: false
};
this.ready = (0, _callcallback2.default)(this.loadCheckpoints(modelPath), callback);
// this.then = this.ready.then.bind(this.ready);
}
(0, _createClass3.default)(CharRNN, [{
key: "resetState",
value: function resetState() {
this.state = this.zeroState;
}
}, {
key: "setState",
value: function setState(state) {
this.state = state;
}
}, {
key: "getState",
value: function getState() {
return this.state;
}
}, {
key: "loadCheckpoints",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(path) {
var _this = this;
var reader, vars;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
reader = new _checkpointLoader2.default(path);
_context.next = 3;
return reader.getAllVariables();
case 3:
vars = _context.sent;
(0, _keys2.default)(vars).forEach(function (key) {
if (key.match(regexCell)) {
if (key.match(regexWeights)) {
_this.model["Kernel_" + key.match(/[0-9]/)[0]] = vars[key];
_this.cellsAmount += 1;
} else {
_this.model["Bias_" + key.match(/[0-9]/)[0]] = vars[key];
}
} else if (key.match(regexFullyConnected)) {
if (key.match(regexWeights)) {
_this.model.fullyConnectedWeights = vars[key];
} else {
_this.model.fullyConnectedBiases = vars[key];
}
} else {
_this.model[key] = vars[key];
}
});
_context.next = 7;
return this.loadVocab(path);
case 7:
_context.next = 9;
return this.initCells();
case 9:
return _context.abrupt("return", this);
case 10:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadCheckpoints(_x) {
return _ref.apply(this, arguments);
}
return loadCheckpoints;
}()
}, {
key: "loadVocab",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(path) {
var _ref3, data;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return _axios2.default.get(path + "/vocab.json");
case 3:
_ref3 = _context2.sent;
data = _ref3.data;
this.vocab = data;
this.vocabSize = (0, _keys2.default)(data).length;
return _context2.abrupt("return", this.vocab);
case 10:
_context2.prev = 10;
_context2.t0 = _context2["catch"](0);
return _context2.abrupt("return", _context2.t0);
case 13:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[0, 10]]);
}));
function loadVocab(_x2) {
return _ref2.apply(this, arguments);
}
return loadVocab;
}()
}, {
key: "initCells",
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() {
var _this2 = this;
var forgetBias, lstm, i;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
this.cells = [];
this.zeroState = { c: [], h: [] };
forgetBias = tf.tensor(1.0);
lstm = function lstm(i) {
var cell = function cell(DATA, C, H) {
return tf.basicLSTMCell(forgetBias, _this2.model["Kernel_" + i], _this2.model["Bias_" + i], DATA, C, H);
};
return cell;
};
for (i = 0; i < this.cellsAmount; i += 1) {
this.zeroState.c.push(tf.zeros([1, this.model["Bias_" + i].shape[0] / 4]));
this.zeroState.h.push(tf.zeros([1, this.model["Bias_" + i].shape[0] / 4]));
this.cells.push(lstm(i));
}
this.state = this.zeroState;
case 6:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function initCells() {
return _ref4.apply(this, arguments);
}
return initCells;
}()
}, {
key: "generateInternal",
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(options) {
var _this3 = this;
var seed, length, temperature, stateful, results, userInput, encodedInput, input, probabilitiesNormalized, i, onehotBuffer, onehot, output, embedded, outputH, weightedResult, logits, divided, probabilities, generated;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.ready;
case 2:
seed = options.seed || this.defaults.seed;
length = +options.length || this.defaults.length;
temperature = +options.temperature || this.defaults.temperature;
stateful = options.stateful || this.defaults.stateful;
if (!stateful) {
this.state = this.zeroState;
}
results = [];
userInput = (0, _from2.default)(seed);
encodedInput = [];
userInput.forEach(function (char) {
encodedInput.push(_this3.vocab[char]);
});
input = encodedInput[0];
probabilitiesNormalized = []; // will contain final probabilities (normalized)
i = 0;
case 14:
if (!(i < userInput.length + length + -1)) {
_context4.next = 36;
break;
}
_context4.next = 17;
return tf.buffer([1, this.vocabSize]);
case 17:
onehotBuffer = _context4.sent;
onehotBuffer.set(1.0, 0, input);
onehot = onehotBuffer.toTensor();
output = void 0;
if (this.model.embedding) {
embedded = tf.matMul(onehot, this.model.embedding);
output = tf.multiRNNCell(this.cells, embedded, this.state.c, this.state.h);
} else {
output = tf.multiRNNCell(this.cells, onehot, this.state.c, this.state.h);
}
this.state.c = output[0];
this.state.h = output[1];
outputH = this.state.h[1];
weightedResult = tf.matMul(outputH, this.model.fullyConnectedWeights);
logits = tf.add(weightedResult, this.model.fullyConnectedBiases);
divided = tf.div(logits, tf.tensor(temperature));
probabilities = tf.exp(divided);
_context4.next = 31;
return tf.div(probabilities, tf.sum(probabilities)).data();
case 31:
probabilitiesNormalized = _context4.sent;
if (i < userInput.length - 1) {
input = encodedInput[i + 1];
} else {
input = (0, _sample2.default)(probabilitiesNormalized);
results.push(input);
}
case 33:
i += 1;
_context4.next = 14;
break;
case 36:
generated = "";
results.forEach(function (char) {
var mapped = (0, _keys2.default)(_this3.vocab).find(function (key) {
return _this3.vocab[key] === char;
});
if (mapped) {
generated += mapped;
}
});
this.probabilities = probabilitiesNormalized;
return _context4.abrupt("return", {
sample: generated,
state: this.state
});
case 40:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function generateInternal(_x3) {
return _ref5.apply(this, arguments);
}
return generateInternal;
}()
/**
* Reset the model state.
*/
}, {
key: "reset",
value: function reset() {
this.state = this.zeroState;
}
/**
* @typedef {Object} options
* @property {String} seed
* @property {number} length
* @property {number} temperature
*/
// stateless
/**
* Generates content in a stateless manner, based on some initial text
* (known as a "seed"). Returns a string.
* @param {options} options - An object specifying the input parameters of
* seed, length and temperature. Default length is 20, temperature is 0.5
* and seed is a random character from the model. The object should look like
* this:
* @param {function} callback - Optional. A function to be called when the model
* has generated content. If no callback is provided, it will return a promise
* that will be resolved once the model has generated new content.
*/
}, {
key: "generate",
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(options, callback) {
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
this.reset();
return _context5.abrupt("return", (0, _callcallback2.default)(this.generateInternal(options), callback));
case 2:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function generate(_x4, _x5) {
return _ref6.apply(this, arguments);
}
return generate;
}()
// stateful
/**
* Predict the next character based on the model's current state.
* @param {number} temp
* @param {function} callback - Optional. A function to be called when the
* model finished adding the seed. If no callback is provided, it will
* return a promise that will be resolved once the prediction has been generated.
*/
}, {
key: "predict",
value: function () {
var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(temp, callback) {
var _this4 = this;
var probabilitiesNormalized, temperature, outputH, weightedResult, logits, divided, probabilities, sample, result, pm;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
probabilitiesNormalized = [];
temperature = temp > 0 ? temp : 0.1;
outputH = this.state.h[1];
weightedResult = tf.matMul(outputH, this.model.fullyConnectedWeights);
logits = tf.add(weightedResult, this.model.fullyConnectedBiases);
divided = tf.div(logits, tf.tensor(temperature));
probabilities = tf.exp(divided);
_context6.next = 9;
return tf.div(probabilities, tf.sum(probabilities)).data();
case 9:
probabilitiesNormalized = _context6.sent;
sample = (0, _sample2.default)(probabilitiesNormalized);
result = (0, _keys2.default)(this.vocab).find(function (key) {
return _this4.vocab[key] === sample;
});
this.probabilities = probabilitiesNormalized;
if (callback) {
callback(result);
}
/* eslint max-len: ["error", { "code": 180 }] */
pm = (0, _keys2.default)(this.vocab).map(function (c) {
return {
char: c,
probability: _this4.probabilities[_this4.vocab[c]]
};
});
return _context6.abrupt("return", {
sample: result,
probabilities: pm
});
case 16:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function predict(_x6, _x7) {
return _ref7.apply(this, arguments);
}
return predict;
}()
/**
* Feed a string of characters to the model state.
* @param {String} inputSeed - A string to feed the charRNN model state.
* @param {function} callback - Optional. A function to be called when
* the model finished adding the seed. If no callback is provided, it
* will return a promise that will be resolved once seed has been fed.
*/
}, {
key: "feed",
value: function () {
var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(inputSeed, callback) {
var _this5 = this;
var seed, encodedInput, input, i, onehotBuffer, onehot, output, embedded;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return this.ready;
case 2:
seed = (0, _from2.default)(inputSeed);
encodedInput = [];
seed.forEach(function (char) {
encodedInput.push(_this5.vocab[char]);
});
input = encodedInput[0];
i = 0;
case 7:
if (!(i < seed.length)) {
_context7.next = 21;
break;
}
_context7.next = 10;
return tf.buffer([1, this.vocabSize]);
case 10:
onehotBuffer = _context7.sent;
onehotBuffer.set(1.0, 0, input);
onehot = onehotBuffer.toTensor();
output = void 0;
if (this.model.embedding) {
embedded = tf.matMul(onehot, this.model.embedding);
output = tf.multiRNNCell(this.cells, embedded, this.state.c, this.state.h);
} else {
output = tf.multiRNNCell(this.cells, onehot, this.state.c, this.state.h);
}
this.state.c = output[0];
this.state.h = output[1];
input = encodedInput[i];
case 18:
i += 1;
_context7.next = 7;
break;
case 21:
if (callback) {
callback();
}
case 22:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function feed(_x8, _x9) {
return _ref8.apply(this, arguments);
}
return feed;
}()
}]);
return CharRNN;
}();
var charRNN = function charRNN() {
var modelPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "./";
var callback = arguments[1];
return new CharRNN(modelPath, callback);
};
exports.default = charRNN;
/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _getPrototypeOf = __webpack_require__(98);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(97);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(96);
var _inherits3 = _interopRequireDefault(_inherits2);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _Video2 = __webpack_require__(143);
var _Video3 = _interopRequireDefault(_Video2);
var _checkpointLoader = __webpack_require__(204);
var _checkpointLoader2 = _interopRequireDefault(_checkpointLoader);
var _imageUtilities = __webpack_require__(46);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var IMAGE_SIZE = 200; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint max-len: "off" */
/* eslint no-trailing-spaces: "off" */
/*
Fast Style Transfer
This implementation is heavily based on github.com/reiinakano/fast-style-transfer-deeplearnjs by Reiichiro Nakano.
The original TensorFlow implementation was developed by Logan Engstrom: github.com/lengstrom/fast-style-transfer
*/
var convertCanvasToImage = function convertCanvasToImage(canvas) {
return new _promise2.default(function (resolve) {
var image = new Image(IMAGE_SIZE, IMAGE_SIZE);
image.onload = function () {
return resolve(image);
};
image.src = canvas.toDataURL();
});
};
var StyleTransfer = function (_Video) {
(0, _inherits3.default)(StyleTransfer, _Video);
/**
* Create a new Style Transfer Instance。
* @param {model} model - The path to Style Transfer model.
* @param {HTMLVideoElement || p5.Video} video - Optional. A HTML video element or a p5 video element.
* @param {funciton} callback - Optional. A function to be called once the model is loaded. If no callback is provided, it will return a promise that will be resolved once the model has loaded.
*/
function StyleTransfer(model, video, callback) {
(0, _classCallCheck3.default)(this, StyleTransfer);
/**
* Boolean value that specifies if the model has loaded.
* @type {boolean}
* @public
*/
var _this = (0, _possibleConstructorReturn3.default)(this, (StyleTransfer.__proto__ || (0, _getPrototypeOf2.default)(StyleTransfer)).call(this, video, IMAGE_SIZE));
_this.ready = false;
_this.variableDictionary = {};
_this.timesScalar = tf.scalar(150);
_this.plusScalar = tf.scalar(255.0 / 2);
_this.epsilonScalar = tf.scalar(1e-3);
_this.video = null;
_this.ready = (0, _callcallback2.default)(_this.load(model), callback);
// this.then = this.ready.then;
return _this;
}
(0, _createClass3.default)(StyleTransfer, [{
key: 'load',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(model) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!this.videoElt) {
_context.next = 4;
break;
}
_context.next = 3;
return this.loadVideo();
case 3:
this.videoReady = true;
case 4:
_context.next = 6;
return this.loadCheckpoints(model);
case 6:
return _context.abrupt('return', this);
case 7:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function load(_x) {
return _ref.apply(this, arguments);
}
return load;
}()
}, {
key: 'loadCheckpoints',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(path) {
var checkpointLoader;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
checkpointLoader = new _checkpointLoader2.default(path);
_context2.next = 3;
return checkpointLoader.getAllVariables();
case 3:
this.variables = _context2.sent;
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function loadCheckpoints(_x2) {
return _ref2.apply(this, arguments);
}
return loadCheckpoints;
}()
}, {
key: 'instanceNorm',
value: function instanceNorm(input, id) {
var _this2 = this;
return tf.tidy(function () {
var _input$shape = (0, _slicedToArray3.default)(input.shape, 3),
height = _input$shape[0],
width = _input$shape[1],
inDepth = _input$shape[2];
var moments = tf.moments(input, [0, 1]);
var mu = moments.mean;
var sigmaSq = moments.variance;
var shift = _this2.variables[StyleTransfer.getVariableName(id)];
var scale = _this2.variables[StyleTransfer.getVariableName(id + 1)];
var epsilon = _this2.epsilonScalar;
var normalized = tf.div(tf.sub(input.asType('float32'), mu), tf.sqrt(tf.add(sigmaSq, epsilon)));
var shifted = tf.add(tf.mul(scale, normalized), shift);
return shifted.as3D(height, width, inDepth);
});
}
}, {
key: 'convLayer',
value: function convLayer(input, strides, relu, id) {
var y = tf.conv2d(input, this.variables[StyleTransfer.getVariableName(id)], [strides, strides], 'same');
var y2 = this.instanceNorm(y, id + 1);
if (relu) {
return tf.relu(y2);
}
return y2;
}
}, {
key: 'residualBlock',
value: function residualBlock(input, id) {
var conv1 = this.convLayer(input, 1, true, id);
var conv2 = this.convLayer(conv1, 1, false, id + 3);
return tf.add(conv2, input);
}
}, {
key: 'convTransposeLayer',
value: function convTransposeLayer(input, numFilters, strides, id) {
var _input$shape2 = (0, _slicedToArray3.default)(input.shape, 2),
height = _input$shape2[0],
width = _input$shape2[1];
var newRows = height * strides;
var newCols = width * strides;
var newShape = [newRows, newCols, numFilters];
var y = tf.conv2dTranspose(input, this.variables[StyleTransfer.getVariableName(id)], newShape, [strides, strides], 'same');
var y2 = this.instanceNorm(y, id + 1);
var y3 = tf.relu(y2);
return y3;
}
/**
*
* @param {Image || p5.Image || HTMLVideoElement || p5.Video} input - A HTML video or image element or a p5 image or video element. If no input is provided, the default is to use the video element given in the constructor.
* @param {funciton} callback - Optional. A function to run once the model has made the transfer. If no callback is provided, it will return a promise that will be resolved once the model has made the transfer.
*/
}, {
key: 'transfer',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(inputOrCallback, cb) {
var input, callback;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
input = void 0;
callback = cb;
if (!(inputOrCallback instanceof HTMLVideoElement || inputOrCallback instanceof HTMLImageElement || inputOrCallback instanceof ImageData)) {
_context3.next = 6;
break;
}
input = inputOrCallback;
_context3.next = 19;
break;
case 6:
if (!(inputOrCallback instanceof HTMLCanvasElement)) {
_context3.next = 12;
break;
}
_context3.next = 9;
return convertCanvasToImage(inputOrCallback);
case 9:
input = _context3.sent;
_context3.next = 19;
break;
case 12:
if (!((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === 'object' && inputOrCallback.elt instanceof HTMLCanvasElement)) {
_context3.next = 18;
break;
}
_context3.next = 15;
return convertCanvasToImage(inputOrCallback.elt);
case 15:
input = _context3.sent;
_context3.next = 19;
break;
case 18:
if ((typeof inputOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOrCallback)) === 'object' && (inputOrCallback.elt instanceof HTMLVideoElement || inputOrCallback.elt instanceof HTMLImageElement || inputOrCallback.elt instanceof ImageData)) {
input = inputOrCallback.elt;
} else if (typeof inputOrCallback === 'function') {
input = this.video;
callback = inputOrCallback;
}
case 19:
return _context3.abrupt('return', (0, _callcallback2.default)(this.transferInternal(input), callback));
case 20:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function transfer(_x3, _x4) {
return _ref3.apply(this, arguments);
}
return transfer;
}()
}, {
key: 'transferInternal',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(input) {
var _this3 = this;
var image, result;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
image = tf.browser.fromPixels(input);
result = (0, _imageUtilities.array3DToImage)(tf.tidy(function () {
var conv1 = _this3.convLayer(image, 1, true, 0);
var conv2 = _this3.convLayer(conv1, 2, true, 3);
var conv3 = _this3.convLayer(conv2, 2, true, 6);
var res1 = _this3.residualBlock(conv3, 9);
var res2 = _this3.residualBlock(res1, 15);
var res3 = _this3.residualBlock(res2, 21);
var res4 = _this3.residualBlock(res3, 27);
var res5 = _this3.residualBlock(res4, 33);
var convT1 = _this3.convTransposeLayer(res5, 64, 2, 39);
var convT2 = _this3.convTransposeLayer(convT1, 32, 2, 42);
var convT3 = _this3.convLayer(convT2, 1, false, 45);
var outTanh = tf.tanh(convT3);
var scaled = tf.mul(_this3.timesScalar, outTanh);
var shifted = tf.add(_this3.plusScalar, scaled);
var clamped = tf.clipByValue(shifted, 0, 255);
var normalized = tf.div(clamped, tf.scalar(255.0));
return normalized;
}));
image.dispose();
_context4.next = 5;
return tf.nextFrame();
case 5:
return _context4.abrupt('return', result);
case 6:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function transferInternal(_x5) {
return _ref4.apply(this, arguments);
}
return transferInternal;
}()
// Static Methods
}], [{
key: 'getVariableName',
value: function getVariableName(id) {
if (id === 0) {
return 'Variable';
}
return 'Variable_' + id;
}
}]);
return StyleTransfer;
}(_Video3.default);
var styleTransfer = function styleTransfer(model, videoOrCallback, cb) {
var video = videoOrCallback;
var callback = cb;
if (typeof videoOrCallback === 'function') {
callback = videoOrCallback;
}
var instance = new StyleTransfer(model, video, callback);
return callback ? instance : instance.ready;
};
exports.default = styleTransfer;
/***/ }),
/* 344 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeMultiplePoses", function() { return decodeMultiplePoses; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeSinglePose", function() { return decodeSinglePose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MobileNet", function() { return MobileNet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partChannels", function() { return partChannels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partIds", function() { return partIds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "partNames", function() { return partNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "poseChain", function() { return poseChain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseNet", function() { return PoseNet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAdjacentKeyPoints", function() { return getAdjacentKeyPoints; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBoundingBox", function() { return getBoundingBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBoundingBoxPoints", function() { return getBoundingBoxPoints; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scaleAndFlipPoses", function() { return scaleAndFlipPoses; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scalePose", function() { return scalePose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/**
* @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 extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function __extends(e,t){function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function __awaiter(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function u(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(s,u)}a((r=r.apply(e,t||[])).next())})}function __generator(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=(o=s.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}var BaseModel=function(){function e(e,t){this.model=e,this.outputStride=t;var n=this.model.inputs[0].shape;_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(-1===n[1]&&-1===n[2],function(){return"Input shape ["+n[1]+", "+n[2]+"] must both be equal to or -1"})}return e.prototype.predict=function(e){var t=this;return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var n=t.preprocessInput(e.toFloat()).expandDims(0),r=t.model.predict(n).map(function(e){return e.squeeze([0])}),o=t.nameOutputResults(r);return{heatmapScores:o.heatmap.sigmoid(),offsets:o.offsets,displacementFwd:o.displacementFwd,displacementBwd:o.displacementBwd}})},e.prototype.dispose=function(){this.model.dispose()},e}(),MobileNet=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.preprocessInput=function(e){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(e,127.5).sub(1)})},t.prototype.nameOutputResults=function(e){return{offsets:e[0],heatmap:e[1],displacementFwd:e[2],displacementBwd:e[3]}},t}(BaseModel);function half(e){return Math.floor(e/2)}var MaxHeap=function(){function e(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}return e.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)},e.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e},e.prototype.empty=function(){return-1===this.numberOfElements},e.prototype.size=function(){return this.numberOfElements+1},e.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},e.prototype.max=function(){return this.priorityQueue[0]},e.prototype.swim=function(e){for(;e>0&&this.less(half(e),e);)this.exchange(e,half(e)),e=half(e)},e.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(t<this.numberOfElements&&this.less(t,t+1)&&t++,!this.less(e,t))break;this.exchange(e,t),e=t}},e.prototype.getValueAt=function(e){return this.getElementValue(this.priorityQueue[e])},e.prototype.less=function(e,t){return this.getValueAt(e)<this.getValueAt(t)},e.prototype.exchange=function(e,t){var n=this.priorityQueue[e];this.priorityQueue[e]=this.priorityQueue[t],this.priorityQueue[t]=n},e}();function scoreIsMaximumInLocalWindow(e,t,n,r,o,i){for(var s=i.shape,u=s[0],a=s[1],l=!0,p=Math.max(n-o,0),c=Math.min(n+o+1,u),f=p;f<c;++f){for(var d=Math.max(r-o,0),h=Math.min(r+o+1,a),m=d;m<h;++m)if(i.get(f,m,e)>t){l=!1;break}if(!l)break}return l}function buildPartWithScoreQueue(e,t,n){for(var r=n.shape,o=r[0],i=r[1],s=r[2],u=new MaxHeap(o*i*s,function(e){return e.score}),a=0;a<o;++a)for(var l=0;l<i;++l)for(var p=0;p<s;++p){var c=n.get(a,l,p);c<e||scoreIsMaximumInLocalWindow(p,c,a,l,t,n)&&u.enqueue({score:c,part:{heatmapY:a,heatmapX:l,id:p}})}return u}var partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],NUM_KEYPOINTS=partNames.length,partIds=partNames.reduce(function(e,t,n){return e[t]=n,e},{}),connectedPartNames=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]],connectedPartIndices=connectedPartNames.map(function(e){var t=e[0],n=e[1];return[partIds[t],partIds[n]]}),partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"];function getOffsetPoint(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+NUM_KEYPOINTS)}}function getImageCoords(e,t,n){var r=getOffsetPoint(e.heatmapY,e.heatmapX,e.id,n),o=r.y,i=r.x;return{x:e.heatmapX*t+i,y:e.heatmapY*t+o}}function clamp(e,t,n){return e<t?t:e>n?n:e}function squaredDistance(e,t,n,r){var o=n-e,i=r-t;return o*o+i*i}function addVectors(e,t){return{x:e.x+t.x,y:e.y+t.y}}var parentChildrenTuples=poseChain.map(function(e){var t=e[0],n=e[1];return[partIds[t],partIds[n]]}),parentToChildEdges=parentChildrenTuples.map(function(e){return e[1]}),childToParentEdges=parentChildrenTuples.map(function(e){return e[0]});function getDisplacement(e,t,n){var r=n.shape[2]/2;return{y:n.get(t.y,t.x,e),x:n.get(t.y,t.x,r+e)}}function getStridedIndexNearPoint(e,t,n,r){return{y:clamp(Math.round(e.y/t),0,n-1),x:clamp(Math.round(e.x/t),0,r-1)}}function traverseToTargetKeypoint(e,t,n,r,o,i,s,u){void 0===u&&(u=2);for(var a=r.shape,l=a[0],p=a[1],c=getDisplacement(e,getStridedIndexNearPoint(t.position,i,l,p),s),f=addVectors(t.position,c),d=0;d<u;d++){var h=getStridedIndexNearPoint(f,i,l,p),m=getOffsetPoint(h.y,h.x,n,o);f=addVectors({x:h.x*i,y:h.y*i},{x:m.x,y:m.y})}var g=getStridedIndexNearPoint(f,i,l,p),_=r.get(g.y,g.x,n);return{position:f,part:partNames[n],score:_}}function decodePose(e,t,n,r,o,i){var s=t.shape[2],u=parentToChildEdges.length,a=new Array(s),l=e.part,p=e.score,c=getImageCoords(l,r,n);a[l.id]={score:p,part:partNames[l.id],position:c};for(var f=u-1;f>=0;--f){var d=parentToChildEdges[f],h=childToParentEdges[f];a[d]&&!a[h]&&(a[h]=traverseToTargetKeypoint(f,a[d],h,t,n,r,i))}for(f=0;f<u;++f){d=childToParentEdges[f],h=parentToChildEdges[f];a[d]&&!a[h]&&(a[h]=traverseToTargetKeypoint(f,a[d],h,t,n,r,o))}return a}function withinNmsRadiusOfCorrespondingPoint(e,t,n,r){var o=n.x,i=n.y;return e.some(function(e){var n=e.keypoints[r].position;return squaredDistance(i,o,n.y,n.x)<=t})}function getInstanceScore(e,t,n){return n.reduce(function(n,r,o){var i=r.position,s=r.score;return withinNmsRadiusOfCorrespondingPoint(e,t,i,o)||(n+=s),n},0)/n.length}var kLocalMaximumRadius=1;function decodeMultiplePoses(e,t,n,r,o,i,s,u){void 0===s&&(s=.5),void 0===u&&(u=20);for(var a=[],l=buildPartWithScoreQueue(s,kLocalMaximumRadius,e),p=u*u;a.length<i&&!l.empty();){var c=l.dequeue();if(!withinNmsRadiusOfCorrespondingPoint(a,p,getImageCoords(c.part,o,t),c.part.id)){var f=decodePose(c,e,t,o,n,r),d=getInstanceScore(a,p,f);a.push({keypoints:f,score:d})}}return a}function mod(e,t){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var n=e.div(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(t,"int32"));return e.sub(n.mul(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(t,"int32")))})}function argmax2d(e){var t=e.shape,n=t[0],r=t[1],o=t[2];return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var t=e.reshape([n*r,o]).argMax(0),i=t.div(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(r,"int32")).expandDims(1),s=mod(t,r).expandDims(1);return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["concat"])([i,s],1)})}function getPointsConfidence(e,t){for(var n=t.shape[0],r=new Float32Array(n),o=0;o<n;o++){var i=t.get(o,0),s=t.get(o,1);r[o]=e.get(i,s,o)}return r}function getOffsetPoint$1(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+NUM_KEYPOINTS)}}function getOffsetVectors(e,t){for(var n=[],r=0;r<NUM_KEYPOINTS;r++){var o=getOffsetPoint$1(e.get(r,0).valueOf(),e.get(r,1).valueOf(),r,t),i=o.x,s=o.y;n.push(s),n.push(i)}return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(n,[NUM_KEYPOINTS,2])}function getOffsetPoints(e,t,n){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var r=getOffsetVectors(e,n);return e.toTensor().mul(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["scalar"])(t,"int32")).toFloat().add(r)})}function decodeSinglePose(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,o,i,s,u,a,l,p,c,f;return __generator(this,function(d){switch(d.label){case 0:return r=0,o=argmax2d(e),[4,Promise.all([e.buffer(),t.buffer(),o.buffer()])];case 1:return i=d.sent(),s=i[0],u=i[1],a=i[2],[4,(l=getOffsetPoints(a,n,u)).buffer()];case 2:return p=d.sent(),c=Array.from(getPointsConfidence(s,a)),f=c.map(function(e,t){return r+=e,{position:{y:p.get(t,0),x:p.get(t,1)},part:partNames[t],score:e}}),o.dispose(),l.dispose(),[2,{keypoints:f,score:r/f.length}]}})})}var MOBILENET_BASE_URL="https://storage.googleapis.com/tfjs-models/savedmodel/posenet/mobilenet/",RESNET50_BASE_URL="https://storage.googleapis.com/tfjs-models/savedmodel/posenet/resnet50/";function resNet50Checkpoint(e,t){var n="model-stride"+e+".json";return 4===t?RESNET50_BASE_URL+"float/"+n:RESNET50_BASE_URL+"quant"+t+"/"+n}function mobileNetCheckpoint(e,t,n){var r={1:"100",.75:"075",.5:"050"},o="model-stride"+e+".json";return 4===n?MOBILENET_BASE_URL+"float/"+r[t]+"/"+o:MOBILENET_BASE_URL+"quant"+n+"/"+r[t]+"/"+o}var imageNetMean=[-123.15,-115.9,-103.06],ResNet=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.preprocessInput=function(e){return e.add(imageNetMean)},t.prototype.nameOutputResults=function(e){var t=e[0],n=e[1];return{offsets:e[2],heatmap:e[3],displacementFwd:t,displacementBwd:n}},t}(BaseModel);function eitherPointDoesntMeetConfidence(e,t,n){return e<n||t<n}function getAdjacentKeyPoints(e,t){return connectedPartIndices.reduce(function(n,r){var o=r[0],i=r[1];return eitherPointDoesntMeetConfidence(e[o].score,e[i].score,t)?n:(n.push([e[o],e[i]]),n)},[])}var NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,POSITIVE_INFINITY=Number.POSITIVE_INFINITY;function getBoundingBox(e){return e.reduce(function(e,t){var n=e.maxX,r=e.maxY,o=e.minX,i=e.minY,s=t.position,u=s.x,a=s.y;return{maxX:Math.max(n,u),maxY:Math.max(r,a),minX:Math.min(o,u),minY:Math.min(i,a)}},{maxX:NEGATIVE_INFINITY,maxY:NEGATIVE_INFINITY,minX:POSITIVE_INFINITY,minY:POSITIVE_INFINITY})}function getBoundingBoxPoints(e){var t=getBoundingBox(e),n=t.minX,r=t.minY,o=t.maxX,i=t.maxY;return[{x:n,y:r},{x:o,y:r},{x:o,y:i},{x:n,y:i}]}function toTensorBuffers3D(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return[2,Promise.all(e.map(function(e){return e.buffer()}))]})})}function scalePose(e,t,n,r,o){return void 0===r&&(r=0),void 0===o&&(o=0),{score:e.score,keypoints:e.keypoints.map(function(e){var i=e.score,s=e.part,u=e.position;return{score:i,part:s,position:{x:u.x*n+o,y:u.y*t+r}}})}}function scalePoses(e,t,n,r,o){return void 0===r&&(r=0),void 0===o&&(o=0),1===n&&1===t&&0===r&&0===o?e:e.map(function(e){return scalePose(e,t,n,r,o)})}function flipPoseHorizontal(e,t){return{score:e.score,keypoints:e.keypoints.map(function(e){var n=e.score,r=e.part,o=e.position;return{score:n,part:r,position:{x:t-1-o.x,y:o.y}}})}}function flipPosesHorizontal(e,t){return t<=0?e:e.map(function(e){return flipPoseHorizontal(e,t)})}function toValidInputResolution(e,t){return isValidInputResolution(e,t)?e:Math.floor(e/t)*t+1}function validateInputResolution(e){_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e||"object"==typeof e,function(){return"Invalid inputResolution "+e+". Should be a number or an object with width and height"}),"object"==typeof e&&(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e.width,function(){return"inputResolution.width has a value of "+e.width+" which is invalid; it must be a number"}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e.height,function(){return"inputResolution.height has a value of "+e.height+" which is invalid; it must be a number"}))}function getValidInputResolutionDimensions(e,t){return validateInputResolution(e),"object"==typeof e?[toValidInputResolution(e.height,t),toValidInputResolution(e.width,t)]:[toValidInputResolution(e,t),toValidInputResolution(e,t)]}var VALID_OUTPUT_STRIDES=[8,16,32];function assertValidOutputStride(e){_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e,function(){return"outputStride is not a number"}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(VALID_OUTPUT_STRIDES.indexOf(e)>=0,function(){return"outputStride of "+e+" is invalid. It must be either 8, 16, or 32"})}function isValidInputResolution(e,t){return(e-1)%t==0}function assertValidResolution(e,t){_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert("number"==typeof e[0]&&"number"==typeof e[1],function(){return"both resolution values must be a number but had values "+e}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(isValidInputResolution(e[0],t),function(){return"height of "+e[0]+" is invalid for output stride "+t+"."}),_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].assert(isValidInputResolution(e[1],t),function(){return"width of "+e[1]+" is invalid for output stride "+t+"."})}function getInputTensorDimensions(e){return e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?[e.shape[0],e.shape[1]]:[e.height,e.width]}function toInputTensor(e){return e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?e:_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["browser"].fromPixels(e)}function padAndResizeTo(e,t){var n=t[0],r=t[1],o=getInputTensorDimensions(e),i=o[0],s=o[1],u=r/n,a=[0,0,0,0],l=a[0],p=a[1],c=a[2],f=a[3];return s/i<u?(l=0,p=0,c=Math.round(.5*(u*i-s)),f=Math.round(.5*(u*i-s))):(l=Math.round(.5*(1/u*s-i)),p=Math.round(.5*(1/u*s-i)),c=0,f=0),{resized:Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var t=toInputTensor(e);return(t=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["pad3d"])(t,[[l,p],[c,f],[0,0]])).resizeBilinear([n,r])}),padding:{top:l,left:c,right:f,bottom:p}}}function scaleAndFlipPoses(e,t,n,r,o){var i=t[0],s=t[1],u=n[0],a=n[1],l=scalePoses(e,(i+r.top+r.bottom)/u,(s+r.left+r.right)/a,-r.top,-r.left);return o?flipPosesHorizontal(l,s):l}var MOBILENET_V1_CONFIG={architecture:"MobileNetV1",outputStride:16,multiplier:.75,inputResolution:257},VALID_ARCHITECTURE=["MobileNetV1","ResNet50"],VALID_STRIDE={MobileNetV1:[8,16,32],ResNet50:[32,16]},VALID_MULTIPLIER={MobileNetV1:[.5,.75,1],ResNet50:[1]},VALID_QUANT_BYTES=[1,2,4];function validateModelConfig(e){if(null==(e=e||MOBILENET_V1_CONFIG).architecture&&(e.architecture="MobileNetV1"),VALID_ARCHITECTURE.indexOf(e.architecture)<0)throw new Error("Invalid architecture "+e.architecture+". Should be one of "+VALID_ARCHITECTURE);if(null==e.inputResolution&&(e.inputResolution=257),validateInputResolution(e.inputResolution),null==e.outputStride&&(e.outputStride=16),VALID_STRIDE[e.architecture].indexOf(e.outputStride)<0)throw new Error("Invalid outputStride "+e.outputStride+". Should be one of "+VALID_STRIDE[e.architecture]+" for architecutre "+e.architecture+".");if(null==e.multiplier&&(e.multiplier=1),VALID_MULTIPLIER[e.architecture].indexOf(e.multiplier)<0)throw new Error("Invalid multiplier "+e.multiplier+". Should be one of "+VALID_MULTIPLIER[e.architecture]+" for architecutre "+e.architecture+".");if(null==e.quantBytes&&(e.quantBytes=4),VALID_QUANT_BYTES.indexOf(e.quantBytes)<0)throw new Error("Invalid quantBytes "+e.quantBytes+". Should be one of "+VALID_QUANT_BYTES+" for architecutre "+e.architecture+".");return e}var SINGLE_PERSON_INFERENCE_CONFIG={flipHorizontal:!1},MULTI_PERSON_INFERENCE_CONFIG={flipHorizontal:!1,maxDetections:5,scoreThreshold:.5,nmsRadius:20};function validateMultiPersonInputConfig(e){var t=e.maxDetections,n=e.scoreThreshold,r=e.nmsRadius;if(t<=0)throw new Error("Invalid maxDetections "+t+". Should be > 0");if(n<0||n>1)throw new Error("Invalid scoreThreshold "+n+". Should be in range [0.0, 1.0]");if(r<=0)throw new Error("Invalid nmsRadius "+r+".")}var PoseNet=function(){function e(e,t){assertValidOutputStride(e.outputStride),assertValidResolution(t,e.outputStride),this.baseModel=e,this.inputResolution=t}return e.prototype.estimateMultiplePoses=function(e,t){return void 0===t&&(t=MULTI_PERSON_INFERENCE_CONFIG),__awaiter(this,void 0,void 0,function(){var n,r,o,i,s,u,a,l,p,c,f,d,h,m,g,_,I,v,y,E,b;return __generator(this,function(N){switch(N.label){case 0:return n=__assign({},MULTI_PERSON_INFERENCE_CONFIG,t),validateMultiPersonInputConfig(t),r=this.baseModel.outputStride,o=this.inputResolution,i=getInputTensorDimensions(e),s=i[0],u=i[1],a=padAndResizeTo(e,o),l=a.resized,p=a.padding,c=this.baseModel.predict(l),f=c.heatmapScores,d=c.offsets,h=c.displacementFwd,m=c.displacementBwd,[4,toTensorBuffers3D([f,d,h,m])];case 1:return g=N.sent(),_=g[0],I=g[1],v=g[2],y=g[3],[4,decodeMultiplePoses(_,I,v,y,r,n.maxDetections,n.scoreThreshold,n.nmsRadius)];case 2:return E=N.sent(),b=scaleAndFlipPoses(E,[s,u],o,p,n.flipHorizontal),f.dispose(),d.dispose(),h.dispose(),m.dispose(),l.dispose(),[2,b]}})})},e.prototype.estimateSinglePose=function(e,t){return void 0===t&&(t=SINGLE_PERSON_INFERENCE_CONFIG),__awaiter(this,void 0,void 0,function(){var n,r,o,i,s,u,a,l,p,c,f,d,h,m,g,_;return __generator(this,function(I){switch(I.label){case 0:return n=__assign({},SINGLE_PERSON_INFERENCE_CONFIG,t),r=this.baseModel.outputStride,o=this.inputResolution,i=getInputTensorDimensions(e),s=i[0],u=i[1],a=padAndResizeTo(e,o),l=a.resized,p=a.padding,c=this.baseModel.predict(l),f=c.heatmapScores,d=c.offsets,h=c.displacementFwd,m=c.displacementBwd,[4,decodeSinglePose(f,d,r)];case 1:return g=I.sent(),_=scaleAndFlipPoses([g],[s,u],o,p,n.flipHorizontal),f.dispose(),d.dispose(),h.dispose(),m.dispose(),l.dispose(),[2,_[0]]}})})},e.prototype.estimatePoses=function(e,t){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(n){switch(n.label){case 0:return"single-person"!==t.decodingMethod?[3,2]:[4,this.estimateSinglePose(e,t)];case 1:return[2,[n.sent()]];case 2:return[2,this.estimateMultiplePoses(e,t)]}})})},e.prototype.dispose=function(){this.baseModel.dispose()},e}();function loadMobileNet(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,o,i,s,u;return __generator(this,function(a){switch(a.label){case 0:if(t=e.outputStride,n=e.quantBytes,r=e.multiplier,null==_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");return o=mobileNetCheckpoint(t,r,n),[4,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])(e.modelUrl||o)];case 1:return i=a.sent(),s=new MobileNet(i,t),u=getValidInputResolutionDimensions(e.inputResolution,s.outputStride),[2,new PoseNet(s,u)]}})})}function loadResNet(e){return __awaiter(this,void 0,void 0,function(){var t,n,r,o,i,s;return __generator(this,function(u){switch(u.label){case 0:if(t=e.outputStride,n=e.quantBytes,null==_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n model.");return r=resNet50Checkpoint(t,n),[4,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_1__[/* loadGraphModel */ "c"])(e.modelUrl||r)];case 1:return o=u.sent(),i=new ResNet(o,t),s=getValidInputResolutionDimensions(e.inputResolution,i.outputStride),[2,new PoseNet(i,s)]}})})}function load(e){return void 0===e&&(e=MOBILENET_V1_CONFIG),__awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return"ResNet50"===(e=validateModelConfig(e)).architecture?[2,loadResNet(e)]:"MobileNetV1"===e.architecture?[2,loadMobileNet(e)]:[2,null]})})}var version="2.2.1";
/***/ }),
/* 345 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _stringify = __webpack_require__(99);
var _stringify2 = _interopRequireDefault(_stringify);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _getPrototypeOf = __webpack_require__(98);
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = __webpack_require__(97);
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = __webpack_require__(96);
var _inherits3 = _interopRequireDefault(_inherits2);
var _events = __webpack_require__(141);
var _events2 = _interopRequireDefault(_events);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _posenet = __webpack_require__(344);
var posenet = _interopRequireWildcard(_posenet);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
PoseNet
The original PoseNet model was ported to TensorFlow.js by Dan Oved.
*/
var DEFAULTS = {
architecture: 'MobileNetV1', // 'MobileNetV1', 'ResNet50'
outputStride: 16, // 8, 16, 32
flipHorizontal: false, // true, false
minConfidence: 0.5,
maxPoseDetections: 5, // any number > 1
scoreThreshold: 0.5,
nmsRadius: 20, // any number > 0
detectionType: 'multiple', // 'single'
inputResolution: 256, // or { width: 257, height: 200 }
multiplier: 0.75, // 1.01, 1.0, 0.75, or 0.50 -- only for MobileNet
quantBytes: 2, // 4, 2, 1
modelUrl: null // url path to model
};
var PoseNet = function (_EventEmitter) {
(0, _inherits3.default)(PoseNet, _EventEmitter);
/**
* @typedef {Object} options
* @property {string} architecture - default 'MobileNetV1',
* @property {number} inputResolution - default 257,
* @property {number} outputStride - default 16
* @property {boolean} flipHorizontal - default false
* @property {number} minConfidence - default 0.5
* @property {number} maxPoseDetections - default 5
* @property {number} scoreThreshold - default 0.5
* @property {number} nmsRadius - default 20
* @property {String} detectionType - default single
* @property {number} nmsRadius - default 0.75,
* @property {number} quantBytes - default 2,
* @property {string} modelUrl - default null
*/
/**
* Create a PoseNet model.
* @param {HTMLVideoElement || p5.Video} video - Optional. A HTML video element or a p5 video element.
* @param {options} options - Optional. An object describing a model accuracy and performance.
* @param {String} detectionType - Optional. A String value to run 'single' or 'multiple' estimation.
* @param {function} callback Optional. A function to run once the model has been loaded.
* If no callback is provided, it will return a promise that will be resolved once the
* model has loaded.
*/
function PoseNet(video, options, detectionType, callback) {
(0, _classCallCheck3.default)(this, PoseNet);
var _this = (0, _possibleConstructorReturn3.default)(this, (PoseNet.__proto__ || (0, _getPrototypeOf2.default)(PoseNet)).call(this));
_this.video = video;
/**
* The type of detection. 'single' or 'multiple'
* @type {String}
* @public
*/
_this.modelUrl = options.modelUrl || null;
_this.architecture = options.architecture || DEFAULTS.architecture;
_this.detectionType = detectionType || options.detectionType || DEFAULTS.detectionType;
_this.outputStride = options.outputStride || DEFAULTS.outputStride;
_this.flipHorizontal = options.flipHorizontal || DEFAULTS.flipHorizontal;
_this.scoreThreshold = options.scoreThreshold || DEFAULTS.scoreThreshold;
_this.minConfidence = options.minConfidence || DEFAULTS.minConfidence;
_this.maxPoseDetections = options.maxPoseDetections || DEFAULTS.maxPoseDetections;
_this.multiplier = options.multiplier || DEFAULTS.multiplier;
_this.inputResolution = options.inputResolution || DEFAULTS.inputResolution;
_this.quantBytes = options.quantBytes || DEFAULTS.quantBytes;
_this.nmsRadius = options.nmsRadius || DEFAULTS.nmsRadius;
_this.ready = (0, _callcallback2.default)(_this.load(), callback);
// this.then = this.ready.then;
return _this;
}
(0, _createClass3.default)(PoseNet, [{
key: 'load',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this2 = this;
var modelJson;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
modelJson = void 0;
if (this.architecture.toLowerCase() === 'mobilenetv1') {
modelJson = {
architecture: this.architecture,
outputStride: this.outputStride,
inputResolution: this.inputResolution,
multiplier: this.multiplier,
quantBytes: this.quantBytes,
modelUrl: this.modelUrl
};
} else {
modelJson = {
architecture: this.architecture,
outputStride: this.outputStride,
inputResolution: this.inputResolution,
quantBytes: this.quantBytes
};
}
_context.next = 4;
return posenet.load(modelJson);
case 4:
this.net = _context.sent;
if (!this.video) {
_context.next = 10;
break;
}
if (!(this.video.readyState === 0)) {
_context.next = 9;
break;
}
_context.next = 9;
return new _promise2.default(function (resolve) {
_this2.video.onloadeddata = function () {
return resolve();
};
});
case 9:
if (this.detectionType === 'single') {
this.singlePose();
} else {
this.multiPose();
}
case 10:
return _context.abrupt('return', this);
case 11:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function load() {
return _ref.apply(this, arguments);
}
return load;
}()
}, {
key: 'skeleton',
value: function skeleton(keypoints) {
var confidence = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.minConfidence;
return posenet.getAdjacentKeyPoints(keypoints, confidence);
}
// eslint-disable-next-line class-methods-use-this
}, {
key: 'mapParts',
value: function mapParts(pose) {
var newPose = JSON.parse((0, _stringify2.default)(pose));
newPose.keypoints.forEach(function (keypoint) {
newPose[keypoint.part] = {
x: keypoint.position.x,
y: keypoint.position.y,
confidence: keypoint.score
};
});
return newPose;
}
}, {
key: 'getInput',
value: function getInput(inputOr) {
var input = void 0;
if (inputOr instanceof HTMLImageElement || inputOr instanceof HTMLVideoElement || inputOr instanceof HTMLCanvasElement || inputOr instanceof ImageData) {
input = inputOr;
} else if ((typeof inputOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOr)) === 'object' && (inputOr.elt instanceof HTMLImageElement || inputOr.elt instanceof HTMLVideoElement || inputOr.elt instanceof ImageData)) {
input = inputOr.elt; // Handle p5.js image and video
} else if ((typeof inputOr === 'undefined' ? 'undefined' : (0, _typeof3.default)(inputOr)) === 'object' && inputOr.canvas instanceof HTMLCanvasElement) {
input = inputOr.canvas; // Handle p5.js image
} else {
input = this.video;
}
return input;
}
/**
* Given an image or video, returns an array of objects containing pose estimations
* using single or multi-pose detection.
* @param {HTMLVideoElement || p5.Video || function} inputOr
* @param {function} cb
*/
/* eslint max-len: ["error", { "code": 180 }] */
}, {
key: 'singlePose',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputOr, cb) {
var _this3 = this;
var input, pose, poseWithParts, result;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
input = this.getInput(inputOr);
_context2.next = 3;
return this.net.estimateSinglePose(input, { flipHorizontal: this.flipHorizontal });
case 3:
pose = _context2.sent;
poseWithParts = this.mapParts(pose);
result = [{ pose: poseWithParts, skeleton: this.skeleton(pose.keypoints) }];
this.emit('pose', result);
if (!this.video) {
_context2.next = 9;
break;
}
return _context2.abrupt('return', tf.nextFrame().then(function () {
return _this3.singlePose();
}));
case 9:
if (typeof cb === 'function') {
cb(result);
}
return _context2.abrupt('return', result);
case 11:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function singlePose(_x2, _x3) {
return _ref2.apply(this, arguments);
}
return singlePose;
}()
/**
* Given an image or video, returns an array of objects containing pose
* estimations using single or multi-pose detection.
* @param {HTMLVideoElement || p5.Video || function} inputOr
* @param {function} cb
*/
}, {
key: 'multiPose',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(inputOr, cb) {
var _this4 = this;
var input, poses, posesWithParts, result;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
input = this.getInput(inputOr);
_context3.next = 3;
return this.net.estimateMultiplePoses(input, {
flipHorizontal: this.flipHorizontal,
maxDetections: this.maxPoseDetections,
scoreThreshold: this.scoreThreshold,
nmsRadius: this.nmsRadius
});
case 3:
poses = _context3.sent;
posesWithParts = poses.map(function (pose) {
return _this4.mapParts(pose);
});
result = posesWithParts.map(function (pose) {
return { pose: pose, skeleton: _this4.skeleton(pose.keypoints) };
});
this.emit('pose', result);
if (!this.video) {
_context3.next = 9;
break;
}
return _context3.abrupt('return', tf.nextFrame().then(function () {
return _this4.multiPose();
}));
case 9:
if (typeof cb === 'function') {
cb(result);
}
return _context3.abrupt('return', result);
case 11:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function multiPose(_x4, _x5) {
return _ref3.apply(this, arguments);
}
return multiPose;
}()
}]);
return PoseNet;
}(_events2.default);
var poseNet = function poseNet(videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
var detectionType = null;
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOrOptionsOrCallback)) === 'object' && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(videoOrOptionsOrCallback)) === 'object') {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === 'function') {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object') {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === 'string') {
detectionType = optionsOrCallback;
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
return new PoseNet(video, options, detectionType, callback);
};
exports.default = poseNet;
/***/ }),
/* 346 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _extends2 = __webpack_require__(90);
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _index = __webpack_require__(206);
var _index2 = __webpack_require__(205);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
ObjectDetection
*/
var ObjectDetector =
/**
* @typedef {Object} options
* @property {number} filterBoxesThreshold - Optional. default 0.01
* @property {number} IOUThreshold - Optional. default 0.4
* @property {number} classProbThreshold - Optional. default 0.4
*/
/**
* Create ObjectDetector model. Works on video and images.
* @param {string} modelNameOrUrl - The name or the URL of the model to use. Current model name options
* are: 'YOLO' and 'CocoSsd'.
* @param {Object} options - Optional. A set of options.
* @param {function} callback - Optional. A callback function that is called once the model has loaded.
*/
function ObjectDetector(modelNameOrUrl, video, options, callback) {
(0, _classCallCheck3.default)(this, ObjectDetector);
this.video = video;
this.modelNameOrUrl = modelNameOrUrl;
this.options = options || {};
this.callback = callback;
switch (modelNameOrUrl) {
case "yolo":
this.model = new _index.YOLO(this.video, (0, _extends3.default)({
disableDeprecationNotice: true
}, this.options), callback);
return this;
case "cocossd":
this.model = new _index2.CocoSsd(this.video, this.options, callback);
return this;
default:
// use cocossd as default
this.model = new _index2.CocoSsd(this.video, this.options, callback);
return this;
}
};
var objectDetector = function objectDetector(modelName, videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
var model = modelName;
if (typeof model !== "string") {
throw new Error('Please specify a model to use. E.g: "YOLO"');
} else if (model.indexOf("http") === -1) {
model = modelName.toLowerCase();
}
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object" && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object") {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === "function") {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object") {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === "function") {
callback = optionsOrCallback;
}
var instance = new ObjectDetector(model, video, options, callback);
return instance.model.callback ? instance.model : instance.model.ready;
};
exports.default = objectDetector;
/***/ }),
/* 347 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ObjectDetection", function() { return ObjectDetection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20);
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/**
* @license
* Copyright 2020 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.
* =============================================================================
*/
function __awaiter(e,a,i,n){return new(i||(i=Promise))(function(t,m){function r(e){try{s(n.next(e))}catch(e){m(e)}}function d(e){try{s(n.throw(e))}catch(e){m(e)}}function s(e){e.done?t(e.value):new i(function(a){a(e.value)}).then(r,d)}s((n=n.apply(e,a||[])).next())})}function __generator(e,a){var i,n,t,m,r={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]};return m={next:d(0),throw:d(1),return:d(2)},"function"==typeof Symbol&&(m[Symbol.iterator]=function(){return this}),m;function d(m){return function(d){return function(m){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,n&&(t=2&m[0]?n.return:m[0]?n.throw||((t=n.return)&&t.call(n),0):n.next)&&!(t=t.call(n,m[1])).done)return t;switch(n=0,t&&(m=[2&m[0],t.value]),m[0]){case 0:case 1:t=m;break;case 4:return r.label++,{value:m[1],done:!1};case 5:r.label++,n=m[1],m=[0];continue;case 7:m=r.ops.pop(),r.trys.pop();continue;default:if(!(t=(t=r.trys).length>0&&t[t.length-1])&&(6===m[0]||2===m[0])){r=0;continue}if(3===m[0]&&(!t||m[1]>t[0]&&m[1]<t[3])){r.label=m[1];break}if(6===m[0]&&r.label<t[1]){r.label=t[1],t=m;break}if(t&&r.label<t[2]){r.label=t[2],r.ops.push(m);break}t[2]&&r.ops.pop(),r.trys.pop();continue}m=a.call(e,r)}catch(e){m=[6,e],n=0}finally{i=t=0}if(5&m[0])throw m[1];return{value:m[0]?m[1]:void 0,done:!0}}([m,d])}}}function __read(e,a){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,t,m=i.call(e),r=[];try{for(;(void 0===a||a-- >0)&&!(n=m.next()).done;)r.push(n.value)}catch(e){t={error:e}}finally{try{n&&!n.done&&(i=m.return)&&i.call(m)}finally{if(t)throw t.error}}return r}var CLASSES={1:{name:"/m/01g317",id:1,displayName:"person"},2:{name:"/m/0199g",id:2,displayName:"bicycle"},3:{name:"/m/0k4j",id:3,displayName:"car"},4:{name:"/m/04_sv",id:4,displayName:"motorcycle"},5:{name:"/m/05czz6l",id:5,displayName:"airplane"},6:{name:"/m/01bjv",id:6,displayName:"bus"},7:{name:"/m/07jdr",id:7,displayName:"train"},8:{name:"/m/07r04",id:8,displayName:"truck"},9:{name:"/m/019jd",id:9,displayName:"boat"},10:{name:"/m/015qff",id:10,displayName:"traffic light"},11:{name:"/m/01pns0",id:11,displayName:"fire hydrant"},13:{name:"/m/02pv19",id:13,displayName:"stop sign"},14:{name:"/m/015qbp",id:14,displayName:"parking meter"},15:{name:"/m/0cvnqh",id:15,displayName:"bench"},16:{name:"/m/015p6",id:16,displayName:"bird"},17:{name:"/m/01yrx",id:17,displayName:"cat"},18:{name:"/m/0bt9lr",id:18,displayName:"dog"},19:{name:"/m/03k3r",id:19,displayName:"horse"},20:{name:"/m/07bgp",id:20,displayName:"sheep"},21:{name:"/m/01xq0k1",id:21,displayName:"cow"},22:{name:"/m/0bwd_0j",id:22,displayName:"elephant"},23:{name:"/m/01dws",id:23,displayName:"bear"},24:{name:"/m/0898b",id:24,displayName:"zebra"},25:{name:"/m/03bk1",id:25,displayName:"giraffe"},27:{name:"/m/01940j",id:27,displayName:"backpack"},28:{name:"/m/0hnnb",id:28,displayName:"umbrella"},31:{name:"/m/080hkjn",id:31,displayName:"handbag"},32:{name:"/m/01rkbr",id:32,displayName:"tie"},33:{name:"/m/01s55n",id:33,displayName:"suitcase"},34:{name:"/m/02wmf",id:34,displayName:"frisbee"},35:{name:"/m/071p9",id:35,displayName:"skis"},36:{name:"/m/06__v",id:36,displayName:"snowboard"},37:{name:"/m/018xm",id:37,displayName:"sports ball"},38:{name:"/m/02zt3",id:38,displayName:"kite"},39:{name:"/m/03g8mr",id:39,displayName:"baseball bat"},40:{name:"/m/03grzl",id:40,displayName:"baseball glove"},41:{name:"/m/06_fw",id:41,displayName:"skateboard"},42:{name:"/m/019w40",id:42,displayName:"surfboard"},43:{name:"/m/0dv9c",id:43,displayName:"tennis racket"},44:{name:"/m/04dr76w",id:44,displayName:"bottle"},46:{name:"/m/09tvcd",id:46,displayName:"wine glass"},47:{name:"/m/08gqpm",id:47,displayName:"cup"},48:{name:"/m/0dt3t",id:48,displayName:"fork"},49:{name:"/m/04ctx",id:49,displayName:"knife"},50:{name:"/m/0cmx8",id:50,displayName:"spoon"},51:{name:"/m/04kkgm",id:51,displayName:"bowl"},52:{name:"/m/09qck",id:52,displayName:"banana"},53:{name:"/m/014j1m",id:53,displayName:"apple"},54:{name:"/m/0l515",id:54,displayName:"sandwich"},55:{name:"/m/0cyhj_",id:55,displayName:"orange"},56:{name:"/m/0hkxq",id:56,displayName:"broccoli"},57:{name:"/m/0fj52s",id:57,displayName:"carrot"},58:{name:"/m/01b9xk",id:58,displayName:"hot dog"},59:{name:"/m/0663v",id:59,displayName:"pizza"},60:{name:"/m/0jy4k",id:60,displayName:"donut"},61:{name:"/m/0fszt",id:61,displayName:"cake"},62:{name:"/m/01mzpv",id:62,displayName:"chair"},63:{name:"/m/02crq1",id:63,displayName:"couch"},64:{name:"/m/03fp41",id:64,displayName:"potted plant"},65:{name:"/m/03ssj5",id:65,displayName:"bed"},67:{name:"/m/04bcr3",id:67,displayName:"dining table"},70:{name:"/m/09g1w",id:70,displayName:"toilet"},72:{name:"/m/07c52",id:72,displayName:"tv"},73:{name:"/m/01c648",id:73,displayName:"laptop"},74:{name:"/m/020lf",id:74,displayName:"mouse"},75:{name:"/m/0qjjc",id:75,displayName:"remote"},76:{name:"/m/01m2v",id:76,displayName:"keyboard"},77:{name:"/m/050k8",id:77,displayName:"cell phone"},78:{name:"/m/0fx9l",id:78,displayName:"microwave"},79:{name:"/m/029bxz",id:79,displayName:"oven"},80:{name:"/m/01k6s3",id:80,displayName:"toaster"},81:{name:"/m/0130jx",id:81,displayName:"sink"},82:{name:"/m/040b_t",id:82,displayName:"refrigerator"},84:{name:"/m/0bt_c3",id:84,displayName:"book"},85:{name:"/m/01x3z",id:85,displayName:"clock"},86:{name:"/m/02s195",id:86,displayName:"vase"},87:{name:"/m/01lsmm",id:87,displayName:"scissors"},88:{name:"/m/0kmg4",id:88,displayName:"teddy bear"},89:{name:"/m/03wvsk",id:89,displayName:"hair drier"},90:{name:"/m/012xff",id:90,displayName:"toothbrush"}},version="2.0.3",BASE_PATH="https://storage.googleapis.com/tfjs-models/savedmodel/";function load(e){return void 0===e&&(e={}),__awaiter(this,void 0,void 0,function(){var a,i,n;return __generator(this,function(t){switch(t.label){case 0:if(null==_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");if(a=e.base||"lite_mobilenet_v2",i=e.modelUrl,-1===["mobilenet_v1","mobilenet_v2","lite_mobilenet_v2"].indexOf(a))throw new Error("ObjectDetection constructed with invalid base model "+a+". Valid names are 'mobilenet_v1', 'mobilenet_v2' and 'lite_mobilenet_v2'.");return[4,(n=new ObjectDetection(a,i)).load()];case 1:return t.sent(),[2,n]}})})}var ObjectDetection=function(){function e(e,a){this.modelPath=a||""+BASE_PATH+this.getPrefix(e)+"/model.json"}return e.prototype.getPrefix=function(e){return"lite_mobilenet_v2"===e?"ssd"+e:"ssd_"+e},e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e,a,i;return __generator(this,function(n){switch(n.label){case 0:return e=this,[4,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__[/* loadGraphModel */ "c"])(this.modelPath)];case 1:return e.model=n.sent(),a=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["zeros"])([1,300,300,3],"int32"),[4,this.model.executeAsync(a)];case 2:return i=n.sent(),[4,Promise.all(i.map(function(e){return e.data()}))];case 3:return n.sent(),i.map(function(e){return e.dispose()}),a.dispose(),[2]}})})},e.prototype.infer=function(e,a){return __awaiter(this,void 0,void 0,function(){var i,n,t,m,r,d,s,o,l,p,c,y;return __generator(this,function(u){switch(u.label){case 0:return i=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tidy"])(function(){return e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["Tensor"]||(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["browser"].fromPixels(e)),e.expandDims(0)}),n=i.shape[1],t=i.shape[2],[4,this.model.executeAsync(i)];case 1:return m=u.sent(),r=m[0].dataSync(),d=m[1].dataSync(),i.dispose(),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["dispose"])(m),s=__read(this.calculateMaxScores(r,m[0].shape[1],m[0].shape[2]),2),o=s[0],l=s[1],p=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["getBackend"])(),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["setBackend"])("cpu"),c=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tidy"])(function(){var e=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tensor2d"])(d,[m[1].shape[1],m[1].shape[3]]);return _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["image"].nonMaxSuppression(e,o,a,.5,.5)}),y=c.dataSync(),c.dispose(),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["setBackend"])(p),[2,this.buildDetectedObjects(t,n,d,o,y,l)]}})})},e.prototype.buildDetectedObjects=function(e,a,i,n,t,m){for(var r=t.length,d=[],s=0;s<r;s++){for(var o=[],l=0;l<4;l++)o[l]=i[4*t[s]+l];var p=o[0]*a,c=o[1]*e,y=o[2]*a,u=o[3]*e;o[0]=c,o[1]=p,o[2]=u-c,o[3]=y-p,d.push({bbox:o,class:CLASSES[m[t[s]]+1].displayName,score:n[t[s]]})}return d},e.prototype.calculateMaxScores=function(e,a,i){for(var n=[],t=[],m=0;m<a;m++){for(var r=Number.MIN_VALUE,d=-1,s=0;s<i;s++)e[m*i+s]>r&&(r=e[m*i+s],d=s);n[m]=r,t[m]=d}return[n,t]},e.prototype.detect=function(e,a){return void 0===a&&(a=20),__awaiter(this,void 0,void 0,function(){return __generator(this,function(i){return[2,this.infer(e,a)]})})},e.prototype.dispose=function(){null!=this.model&&this.model.dispose()},e}();
/***/ }),
/* 348 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.nonMaxSuppression = exports.boxesToCorners = exports.filterBoxes = exports.boxIOU = exports.boxUnion = exports.boxIntersection = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var filterBoxes = exports.filterBoxes = function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(boxes, boxConfidence, boxClassProbs, threshold) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', tf.tidy(function () {
var boxScores = tf.mul(boxConfidence, boxClassProbs);
var boxClasses = tf.argMax(boxScores, -1);
var boxClassScores = tf.max(boxScores, -1);
var predictionMask = tf.greaterEqual(boxClassScores, tf.scalar(threshold));
var maskArr = predictionMask.dataSync();
var indicesArr = [];
for (var i = 0; i < maskArr.length; i += 1) {
var v = maskArr[i];
if (v) {
indicesArr.push(i);
}
}
if (indicesArr.length === 0) {
return [null, null, null];
}
var indices = tf.tensor1d(indicesArr, 'int32');
var result = [tf.gather(boxes.reshape([maskArr.length, 4]), indices), tf.gather(boxClassScores.flatten(), indices), tf.gather(boxClasses.flatten(), indices)];
// boxes.dispose();
// boxClassScores.dispose();
// boxClasses.dispose();
return result;
}));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function filterBoxes(_x, _x2, _x3, _x4) {
return _ref.apply(this, arguments);
};
}();
exports.head = head;
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// export const ANCHORS = tf.tensor2d([
// [0.57273, 0.677385],
// [1.87446, 2.06253],
// [3.33843, 5.47434],
// [7.88282, 3.52778],
// [9.77052, 9.16828],
// ]);
var boxIntersection = exports.boxIntersection = function boxIntersection(a, b) {
var w = Math.min(a[3], b[3]) - Math.max(a[1], b[1]);
var h = Math.min(a[2], b[2]) - Math.max(a[0], b[0]);
if (w < 0 || h < 0) {
return 0;
}
return w * h;
}; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
// Heavily derived from YAD2K (https://github.com/allanzelener/YAD2K)
/* eslint max-len: ["error", { "code": 180 }] */
var boxUnion = exports.boxUnion = function boxUnion(a, b) {
var i = boxIntersection(a, b);
return (a[3] - a[1]) * (a[2] - a[0]) + (b[3] - b[1]) * (b[2] - b[0]) - i;
};
var boxIOU = exports.boxIOU = function boxIOU(a, b) {
return boxIntersection(a, b) / boxUnion(a, b);
};
var boxesToCorners = exports.boxesToCorners = function boxesToCorners(boxXY, boxWH) {
return tf.tidy(function () {
var two = tf.tensor1d([2.0]);
var boxMins = tf.sub(boxXY, tf.div(boxWH, two));
var boxMaxes = tf.add(boxXY, tf.div(boxWH, two));
var dim0 = boxMins.shape[0];
var dim1 = boxMins.shape[1];
var dim2 = boxMins.shape[2];
var size = [dim0, dim1, dim2, 1];
return tf.concat([boxMins.slice([0, 0, 0, 1], size), boxMins.slice([0, 0, 0, 0], size), boxMaxes.slice([0, 0, 0, 1], size), boxMaxes.slice([0, 0, 0, 0], size)], 3);
});
};
var nonMaxSuppression = exports.nonMaxSuppression = function nonMaxSuppression(boxes, scores, iouThreshold) {
return tf.tidy(function () {
// Zip together scores, box corners, and index
var zipped = [];
for (var i = 0; i < scores.length; i += 1) {
zipped.push([scores[i], [boxes[4 * i], boxes[4 * i + 1], boxes[4 * i + 2], boxes[4 * i + 3]], i]);
}
var sortedBoxes = zipped.sort(function (a, b) {
return b[0] - a[0];
});
var selectedBoxes = [];
sortedBoxes.forEach(function (box) {
var add = true;
for (var _i = 0; _i < selectedBoxes.length; _i += 1) {
var curIOU = boxIOU(box[1], selectedBoxes[_i][1]);
if (curIOU > iouThreshold) {
add = false;
break;
}
}
if (add) {
selectedBoxes.push(box);
}
});
return [selectedBoxes.map(function (e) {
return e[2];
}), selectedBoxes.map(function (e) {
return e[1];
}), selectedBoxes.map(function (e) {
return e[0];
})];
});
};
// Convert yolo output to bounding box + prob tensors
/* eslint no-param-reassign: 0 */
function head(feats, anchors, numClasses) {
return tf.tidy(function () {
var numAnchors = anchors.shape[0];
var anchorsTensor = tf.reshape(anchors, [1, 1, numAnchors, 2]);
var convDims = feats.shape.slice(1, 3);
// For later use
var convDims0 = convDims[0];
var convDims1 = convDims[1];
var convHeightIndex = tf.range(0, convDims[0]);
var convWidthIndex = tf.range(0, convDims[1]);
convHeightIndex = tf.tile(convHeightIndex, [convDims[1]]);
convWidthIndex = tf.tile(tf.expandDims(convWidthIndex, 0), [convDims[0], 1]);
convWidthIndex = tf.transpose(convWidthIndex).flatten();
var convIndex = tf.transpose(tf.stack([convHeightIndex, convWidthIndex]));
convIndex = tf.reshape(convIndex, [convDims[0], convDims[1], 1, 2]);
convIndex = tf.cast(convIndex, feats.dtype);
feats = tf.reshape(feats, [convDims[0], convDims[1], numAnchors, numClasses + 5]);
convDims = tf.cast(tf.reshape(tf.tensor1d(convDims), [1, 1, 1, 2]), feats.dtype);
var boxXY = tf.sigmoid(feats.slice([0, 0, 0, 0], [convDims0, convDims1, numAnchors, 2]));
var boxWH = tf.exp(feats.slice([0, 0, 0, 2], [convDims0, convDims1, numAnchors, 2]));
var boxConfidence = tf.sigmoid(feats.slice([0, 0, 0, 4], [convDims0, convDims1, numAnchors, 1]));
var boxClassProbs = tf.softmax(feats.slice([0, 0, 0, 5], [convDims0, convDims1, numAnchors, numClasses]));
boxXY = tf.div(tf.add(boxXY, convIndex), convDims);
boxWH = tf.div(tf.mul(boxWH, anchorsTensor), convDims);
return [boxXY, boxWH, boxConfidence, boxClassProbs];
});
}
/***/ }),
/* 349 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint-disable */
exports.default = ['person', 'bicycle', 'car', 'motorbike', 'aeroplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'sofa', 'pottedplant', 'bed', 'diningtable', 'toilet', 'tvmonitor', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'];
/***/ }),
/* 350 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(23);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __webpack_require__(117) });
/***/ }),
/* 351 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(350);
var $Object = __webpack_require__(18).Object;
module.exports = function create(P, D) {
return $Object.create(P, D);
};
/***/ }),
/* 352 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(351), __esModule: true };
/***/ }),
/* 353 */
/***/ (function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(38);
var anObject = __webpack_require__(48);
var check = function (O, proto) {
anObject(O);
if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function (test, buggy, set) {
try {
set = __webpack_require__(56)(Function.call, __webpack_require__(219).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch (e) { buggy = true; }
return function setPrototypeOf(O, proto) {
check(O, proto);
if (buggy) O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ }),
/* 354 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(23);
$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(353).set });
/***/ }),
/* 355 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(354);
module.exports = __webpack_require__(18).Object.setPrototypeOf;
/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(355), __esModule: true };
/***/ }),
/* 357 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(65);
var $getPrototypeOf = __webpack_require__(232);
__webpack_require__(209)('getPrototypeOf', function () {
return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
/***/ }),
/* 358 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(357);
module.exports = __webpack_require__(18).Object.getPrototypeOf;
/***/ }),
/* 359 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(23);
var $values = __webpack_require__(207)(false);
$export($export.S, 'Object', {
values: function values(it) {
return $values(it);
}
});
/***/ }),
/* 360 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(359);
module.exports = __webpack_require__(18).Object.values;
/***/ }),
/* 361 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _values = __webpack_require__(208);
var _values2 = _interopRequireDefault(_values);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Word2Vec = function () {
/**
* Create Word2Vec model
* @param {String} modelPath - path to pre-trained word vector model in .json e.g data/wordvecs1000.json
* @param {function} callback - Optional. A callback function that is called once the model has loaded. If no callback is provided, it will return a promise
* that will be resolved once the model has loaded.
*/
function Word2Vec(modelPath, callback) {
(0, _classCallCheck3.default)(this, Word2Vec);
this.model = {};
this.modelPath = modelPath;
this.modelSize = 0;
this.modelLoaded = false;
this.ready = (0, _callcallback2.default)(this.loadModel(), callback);
// TODO: Add support to Promise
// this.then = this.ready.then.bind(this.ready);
}
(0, _createClass3.default)(Word2Vec, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this = this;
var _ref2, data;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return _axios2.default.get(this.modelPath);
case 2:
_ref2 = _context.sent;
data = _ref2.data;
(0, _keys2.default)(data.vectors).forEach(function (word) {
_this.model[word] = tf.tensor1d(data.vectors[word]);
});
this.modelSize = (0, _keys2.default)(this.model).length;
this.modelLoaded = true;
return _context.abrupt('return', this);
case 8:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
}, {
key: 'dispose',
value: function dispose(callback) {
(0, _values2.default)(this.model).forEach(function (x) {
return x.dispose();
});
if (callback) {
callback();
}
}
}, {
key: 'add',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(inputs, maxOrCb, cb) {
var _this2 = this;
var _Word2Vec$parser, max, callback;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_Word2Vec$parser = Word2Vec.parser(maxOrCb, cb, 10), max = _Word2Vec$parser.max, callback = _Word2Vec$parser.callback;
_context2.next = 3;
return this.ready;
case 3:
return _context2.abrupt('return', tf.tidy(function () {
var sum = Word2Vec.addOrSubtract(_this2.model, inputs, 'ADD');
var result = Word2Vec.nearest(_this2.model, sum, inputs.length, inputs.length + max);
if (callback) {
callback(undefined, result);
}
return result;
}));
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function add(_x, _x2, _x3) {
return _ref3.apply(this, arguments);
}
return add;
}()
}, {
key: 'subtract',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(inputs, maxOrCb, cb) {
var _this3 = this;
var _Word2Vec$parser2, max, callback;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_Word2Vec$parser2 = Word2Vec.parser(maxOrCb, cb, 10), max = _Word2Vec$parser2.max, callback = _Word2Vec$parser2.callback;
_context3.next = 3;
return this.ready;
case 3:
return _context3.abrupt('return', tf.tidy(function () {
var subtraction = Word2Vec.addOrSubtract(_this3.model, inputs, 'SUBTRACT');
var result = Word2Vec.nearest(_this3.model, subtraction, inputs.length, inputs.length + max);
if (callback) {
callback(undefined, result);
}
return result;
}));
case 4:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function subtract(_x4, _x5, _x6) {
return _ref4.apply(this, arguments);
}
return subtract;
}()
}, {
key: 'average',
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(inputs, maxOrCb, cb) {
var _this4 = this;
var _Word2Vec$parser3, max, callback;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_Word2Vec$parser3 = Word2Vec.parser(maxOrCb, cb, 10), max = _Word2Vec$parser3.max, callback = _Word2Vec$parser3.callback;
_context4.next = 3;
return this.ready;
case 3:
return _context4.abrupt('return', tf.tidy(function () {
var sum = Word2Vec.addOrSubtract(_this4.model, inputs, 'ADD');
var avg = tf.div(sum, tf.tensor(inputs.length));
var result = Word2Vec.nearest(_this4.model, avg, inputs.length, inputs.length + max);
if (callback) {
callback(undefined, result);
}
return result;
}));
case 4:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function average(_x7, _x8, _x9) {
return _ref5.apply(this, arguments);
}
return average;
}()
}, {
key: 'nearest',
value: function () {
var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(input, maxOrCb, cb) {
var _Word2Vec$parser4, max, callback, vector, result;
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_Word2Vec$parser4 = Word2Vec.parser(maxOrCb, cb, 10), max = _Word2Vec$parser4.max, callback = _Word2Vec$parser4.callback;
_context5.next = 3;
return this.ready;
case 3:
vector = this.model[input];
result = void 0;
if (vector) {
result = Word2Vec.nearest(this.model, vector, 1, max + 1);
} else {
result = null;
}
if (callback) {
callback(undefined, result);
}
return _context5.abrupt('return', result);
case 8:
case 'end':
return _context5.stop();
}
}
}, _callee5, this);
}));
function nearest(_x10, _x11, _x12) {
return _ref6.apply(this, arguments);
}
return nearest;
}()
/* Given a set of your own words, find the nearest neighbors */
}, {
key: 'nearestFromSet',
value: function () {
var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(input, set, maxOrCb, cb) {
var _this5 = this;
var _Word2Vec$parser5, max, callback, vector, miniModel, result;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_Word2Vec$parser5 = Word2Vec.parser(maxOrCb, cb, 10), max = _Word2Vec$parser5.max, callback = _Word2Vec$parser5.callback;
_context6.next = 3;
return this.ready;
case 3:
vector = this.model[input];
// If the input vector isn't found, bail out early.
if (vector) {
_context6.next = 7;
break;
}
if (callback) callback(undefined, null);
return _context6.abrupt('return', null);
case 7:
miniModel = {};
set.forEach(function (word) {
if (_this5.model[word]) miniModel[word] = _this5.model[word];
});
// If none of the words in the set are found, also bail out
if (miniModel.length) {
_context6.next = 12;
break;
}
if (callback) callback(undefined, null);
return _context6.abrupt('return', null);
case 12:
result = Word2Vec.nearest(miniModel, vector, 1, max + 1);
if (callback) {
callback(undefined, result);
}
return _context6.abrupt('return', result);
case 15:
case 'end':
return _context6.stop();
}
}
}, _callee6, this);
}));
function nearestFromSet(_x13, _x14, _x15, _x16) {
return _ref7.apply(this, arguments);
}
return nearestFromSet;
}()
}, {
key: 'getRandomWord',
value: function () {
var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(callback) {
var words, result;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return this.ready;
case 2:
words = (0, _keys2.default)(this.model);
result = words[Math.floor(Math.random() * words.length)];
if (callback) {
callback(undefined, result);
}
return _context7.abrupt('return', result);
case 6:
case 'end':
return _context7.stop();
}
}
}, _callee7, this);
}));
function getRandomWord(_x17) {
return _ref8.apply(this, arguments);
}
return getRandomWord;
}()
}], [{
key: 'parser',
value: function parser(maxOrCallback, cb, defaultMax) {
var max = defaultMax;
var callback = cb;
if (typeof maxOrCallback === 'function') {
callback = maxOrCallback;
} else if (typeof maxOrCallback === 'number') {
max = maxOrCallback;
}
return { max: max, callback: callback };
}
}, {
key: 'addOrSubtract',
value: function addOrSubtract(model, values, operation) {
return tf.tidy(function () {
var vectors = [];
var notFound = [];
if (values.length < 2) {
throw new Error('Invalid input, must be passed more than 1 value');
}
values.forEach(function (value) {
var vector = model[value];
if (!vector) {
notFound.push(value);
} else {
vectors.push(vector);
}
});
if (notFound.length > 0) {
throw new Error('Invalid input, vector not found for: ' + notFound.toString());
}
var result = vectors[0];
if (operation === 'ADD') {
for (var i = 1; i < vectors.length; i += 1) {
result = tf.add(result, vectors[i]);
}
} else {
for (var _i = 1; _i < vectors.length; _i += 1) {
result = tf.sub(result, vectors[_i]);
}
}
return result;
});
}
}, {
key: 'nearest',
value: function nearest(model, input, start, max) {
var nearestVectors = [];
(0, _keys2.default)(model).forEach(function (word) {
var distance = tf.util.distSquared(input.dataSync(), model[word].dataSync());
nearestVectors.push({ word: word, distance: distance });
});
nearestVectors.sort(function (a, b) {
return a.distance - b.distance;
});
return nearestVectors.slice(start, max);
}
}]);
return Word2Vec;
}(); // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
Word2Vec
*/
var word2vec = function word2vec(model, cb) {
return new Word2Vec(model, cb);
};
exports.default = word2vec;
/***/ }),
/* 362 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = __webpack_require__(99);
var _stringify2 = _interopRequireDefault(_stringify);
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _assign = __webpack_require__(89);
var _assign2 = _interopRequireDefault(_assign);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _Video = __webpack_require__(143);
var _Video2 = _interopRequireDefault(_Video);
var _imageUtilities = __webpack_require__(46);
var _io = __webpack_require__(115);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
A class that extract features from Mobilenet
*/
var IMAGE_SIZE = 224;
var BASE_URL = "https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v";
var DEFAULTS = {
version: 1,
alpha: 0.25,
topk: 3,
learningRate: 0.0001,
hiddenUnits: 100,
epochs: 20,
numLabels: 2,
batchSize: 0.4,
layer: "conv_pw_13_relu"
};
var MODEL_INFO = {
1: {
0.25: "https://tfhub.dev/google/imagenet/mobilenet_v1_025_224/classification/1",
0.5: "https://tfhub.dev/google/imagenet/mobilenet_v1_050_224/classification/1",
0.75: "https://tfhub.dev/google/imagenet/mobilenet_v1_075_224/classification/1",
1.0: "https://tfhub.dev/google/imagenet/mobilenet_v1_100_224/classification/1"
},
2: {
0.5: "https://tfhub.dev/google/imagenet/mobilenet_v2_050_224/classification/2",
0.75: "https://tfhub.dev/google/imagenet/mobilenet_v2_075_224/classification/2",
1.0: "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/2"
}
};
var EMBEDDING_NODES = {
1: "module_apply_default/MobilenetV1/Logits/global_pool",
2: "module_apply_default/MobilenetV2/Logits/AvgPool"
};
var Mobilenet = function () {
function Mobilenet(options, callback) {
(0, _classCallCheck3.default)(this, Mobilenet);
this.mobilenet = null;
this.topKPredictions = 10;
/**
* Boolean value that specifies if new data has been added to the model
* @type {boolean}
* @public
*/
this.hasAnyTrainedClass = false;
this.customModel = null;
this.jointModel = null;
this.config = {
epochs: options.epochs || DEFAULTS.epochs,
version: options.version || DEFAULTS.version,
hiddenUnits: options.hiddenUnits || DEFAULTS.hiddenUnits,
numLabels: options.numLabels || DEFAULTS.numLabels,
learningRate: options.learningRate || DEFAULTS.learningRate,
batchSize: options.batchSize || DEFAULTS.batchSize,
layer: options.layer || DEFAULTS.layer,
alpha: options.alpha || DEFAULTS.alpha
};
// for graph model
this.model = null;
this.url = MODEL_INFO[this.config.version][this.config.alpha];
this.normalizationOffset = tf.scalar(127.5);
// check if a mobilenet URL is given
this.mobilenetURL = options.mobilenetURL || "" + BASE_URL + this.config.version + "_" + this.config.alpha + "_" + IMAGE_SIZE + "/model.json";
this.graphModelURL = options.graphModelURL || this.url;
/**
* Boolean value to check if the model is predicting.
* @public
* @type {boolean}
*/
this.isPredicting = false;
this.mapStringToIndex = [];
/**
* String that specifies how is the Extractor being used.
* Possible values are 'regressor' and 'classifier'
* @type {String}
* @public
*/
this.usageType = null;
this.ready = (0, _callcallback2.default)(this.loadModel(), callback);
}
(0, _createClass3.default)(Mobilenet, [{
key: "loadModel",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var layer;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return tf.loadLayersModel(this.mobilenetURL);
case 2:
this.mobilenet = _context.sent;
if (!this.graphModelURL.includes("https://tfhub.dev/")) {
_context.next = 9;
break;
}
_context.next = 6;
return tf.loadGraphModel(this.graphModelURL, { fromTFHub: true });
case 6:
this.model = _context.sent;
_context.next = 12;
break;
case 9:
_context.next = 11;
return tf.loadGraphModel(this.graphModelURL, { fromTFHub: false });
case 11:
this.model = _context.sent;
case 12:
layer = this.mobilenet.getLayer(this.config.layer);
_context.next = 15;
return tf.model({
inputs: this.mobilenet.inputs,
outputs: layer.output
});
case 15:
this.mobilenetFeatures = _context.sent;
if (!this.video) {
_context.next = 19;
break;
}
_context.next = 19;
return this.mobilenetFeatures.predict((0, _imageUtilities.imgToTensor)(this.video));
case 19:
return _context.abrupt("return", this);
case 20:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel() {
return _ref.apply(this, arguments);
}
return loadModel;
}()
/**
* Use the features of MobileNet as a classifier.
* @param {HTMLVideoElement || p5.Video} video - Optional.
* An HTML video element or a p5.js video element.
* @param {Object || function} objOrCallback - Optional.
* Callback function or config object.
* @param {function} callback - Optional. A function to be called once
* the video is ready. If no callback is provided, it will return a
* promise that will be resolved once the video element has loaded.
*/
}, {
key: "classification",
value: function classification(video) {
var objOrCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var callback = arguments[2];
var cb = void 0;
this.usageType = "classifier";
if ((typeof objOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(objOrCallback)) === "object") {
(0, _assign2.default)(this.config, objOrCallback);
} else if (typeof objOrCallback === "function") {
cb = objOrCallback;
}
if (typeof callback === "function") {
cb = callback;
}
if (video) {
(0, _callcallback2.default)(this.loadVideo(video), cb);
}
return this;
}
/**
* Use the features of MobileNet as a regressor.
* @param {HTMLVideoElement || p5.Video} video - Optional.
* An HTML video element or a p5.js video element.
* @param {function} callback - Optional. A function to be called once
* the video is ready. If no callback is provided, it will return a
* promise that will be resolved once the video element has loaded.
*/
}, {
key: "regression",
value: function regression(video, callback) {
this.usageType = "regressor";
if (video) {
(0, _callcallback2.default)(this.loadVideo(video), callback);
}
return this;
}
}, {
key: "loadVideo",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(video) {
var inputVideo, vid;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
inputVideo = null;
if (video instanceof HTMLVideoElement) {
inputVideo = video;
} else if ((typeof video === "undefined" ? "undefined" : (0, _typeof3.default)(video)) === "object" && video.elt instanceof HTMLVideoElement) {
inputVideo = video.elt; // p5.js video element
}
if (!inputVideo) {
_context2.next = 7;
break;
}
vid = new _Video2.default(inputVideo, IMAGE_SIZE);
_context2.next = 6;
return vid.loadVideo();
case 6:
this.video = _context2.sent;
case 7:
return _context2.abrupt("return", this);
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function loadVideo(_x2) {
return _ref2.apply(this, arguments);
}
return loadVideo;
}()
/**
* Adds a new image element to Mobilenet
* @param {HTMLVideoElement || p5.Video || String} inputOrLabel
* @param {String || function} labelOrCallback
* @param {function} cb
*/
}, {
key: "addImage",
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(inputOrLabel, labelOrCallback, cb) {
var imgToAdd, label, callback;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
imgToAdd = void 0;
label = void 0;
callback = cb;
if (inputOrLabel instanceof HTMLImageElement || inputOrLabel instanceof HTMLVideoElement || inputOrLabel instanceof HTMLCanvasElement || inputOrLabel.elt instanceof ImageData) {
imgToAdd = inputOrLabel;
} else if ((typeof inputOrLabel === "undefined" ? "undefined" : (0, _typeof3.default)(inputOrLabel)) === "object" && (inputOrLabel.elt instanceof HTMLImageElement || inputOrLabel.elt instanceof HTMLVideoElement || inputOrLabel.elt instanceof HTMLCanvasElement || inputOrLabel.elt instanceof ImageData)) {
imgToAdd = inputOrLabel.elt;
} else if (typeof inputOrLabel === "string" || typeof inputOrLabel === "number") {
imgToAdd = this.video;
label = inputOrLabel;
}
if (typeof labelOrCallback === "string" || typeof labelOrCallback === "number") {
label = labelOrCallback;
} else if (typeof labelOrCallback === "function") {
callback = labelOrCallback;
}
if (typeof label === "string") {
if (!this.mapStringToIndex.includes(label)) {
label = this.mapStringToIndex.push(label) - 1;
} else {
label = this.mapStringToIndex.indexOf(label);
}
}
return _context3.abrupt("return", (0, _callcallback2.default)(this.addImageInternal(imgToAdd, label), callback));
case 7:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function addImage(_x3, _x4, _x5) {
return _ref3.apply(this, arguments);
}
return addImage;
}()
}, {
key: "addImageInternal",
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(imgToAdd, label) {
var _this = this;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.ready;
case 2:
tf.tidy(function () {
var imageResize = imgToAdd === _this.video ? null : [IMAGE_SIZE, IMAGE_SIZE];
var processedImg = (0, _imageUtilities.imgToTensor)(imgToAdd, imageResize);
var prediction = _this.mobilenetFeatures.predict(processedImg);
var y = void 0;
if (_this.usageType === "classifier") {
y = tf.tidy(function () {
return tf.oneHot(tf.tensor1d([label], "int32"), _this.config.numLabels);
});
} else if (_this.usageType === "regressor") {
y = tf.tensor2d([[label]]);
}
if (_this.xs == null) {
_this.xs = tf.keep(prediction);
_this.ys = tf.keep(y);
_this.hasAnyTrainedClass = true;
} else {
var oldX = _this.xs;
_this.xs = tf.keep(oldX.concat(prediction, 0));
var oldY = _this.ys;
_this.ys = tf.keep(oldY.concat(y, 0));
oldX.dispose();
oldY.dispose();
y.dispose();
}
});
return _context4.abrupt("return", this);
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function addImageInternal(_x6, _x7) {
return _ref4.apply(this, arguments);
}
return addImageInternal;
}()
/**
* Retrain the model with the provided images and labels using the
* models original features as starting point.
* @param {function} onProgress - A function to be called to follow
* the progress of the training.
*/
}, {
key: "train",
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee6(onProgress) {
var _this2 = this;
var optimizer, batchSize;
return _regenerator2.default.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (this.hasAnyTrainedClass) {
_context6.next = 2;
break;
}
throw new Error("Add some examples before training!");
case 2:
this.isPredicting = false;
if (this.usageType === "classifier") {
this.loss = "categoricalCrossentropy";
this.customModel = tf.sequential({
layers: [tf.layers.flatten({ inputShape: [7, 7, 256] }), tf.layers.dense({
units: this.config.hiddenUnits,
activation: "relu",
kernelInitializer: "varianceScaling",
useBias: true
}), tf.layers.dense({
units: this.config.numLabels,
kernelInitializer: "varianceScaling",
useBias: false,
activation: "softmax"
})]
});
} else if (this.usageType === "regressor") {
this.loss = "meanSquaredError";
this.customModel = tf.sequential({
layers: [tf.layers.flatten({ inputShape: [7, 7, 256] }), tf.layers.dense({
units: this.config.hiddenUnits,
activation: "relu",
kernelInitializer: "varianceScaling",
useBias: true
}), tf.layers.dense({
units: 1,
useBias: false,
kernelInitializer: "Zeros",
activation: "linear"
})]
});
}
this.jointModel = tf.sequential();
this.jointModel.add(this.mobilenetFeatures); // mobilenet
this.jointModel.add(this.customModel); // transfer layer
optimizer = tf.train.adam(this.config.learningRate);
this.customModel.compile({ optimizer: optimizer, loss: this.loss });
batchSize = Math.floor(this.xs.shape[0] * this.config.batchSize);
if (batchSize > 0) {
_context6.next = 12;
break;
}
throw new Error("Batch size is 0 or NaN. Please choose a non-zero fraction.");
case 12:
return _context6.abrupt("return", this.customModel.fit(this.xs, this.ys, {
batchSize: batchSize,
epochs: this.config.epochs,
callbacks: {
onBatchEnd: function () {
var _ref6 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(batch, logs) {
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
onProgress(logs.loss.toFixed(5));
_context5.next = 3;
return tf.nextFrame();
case 3:
case "end":
return _context5.stop();
}
}
}, _callee5, _this2);
}));
function onBatchEnd(_x9, _x10) {
return _ref6.apply(this, arguments);
}
return onBatchEnd;
}(),
onTrainEnd: function onTrainEnd() {
return onProgress(null);
}
}
}));
case 13:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function train(_x8) {
return _ref5.apply(this, arguments);
}
return train;
}()
/**
* Classifies an an image based on a new retrained model.
* .classification() needs to be used with this.
* @param {HTMLVideoElement || p5.Video || function} inputOrCallback
* @param {function} cb
*/
/* eslint max-len: ["error", { "code": 180 }] */
}, {
key: "classify",
value: function () {
var _ref7 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee7(inputOrCallback, cb) {
var imgToPredict, callback;
return _regenerator2.default.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
imgToPredict = void 0;
callback = void 0;
if (inputOrCallback instanceof HTMLImageElement || inputOrCallback instanceof HTMLVideoElement || inputOrCallback instanceof HTMLCanvasElement || inputOrCallback instanceof ImageData) {
imgToPredict = inputOrCallback;
} else if ((typeof inputOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(inputOrCallback)) === "object" && (inputOrCallback.elt instanceof HTMLImageElement || inputOrCallback.elt instanceof HTMLVideoElement || inputOrCallback.elt instanceof HTMLCanvasElement || inputOrCallback.elt instanceof ImageData)) {
imgToPredict = inputOrCallback.elt; // p5.js image element
} else if (typeof inputOrCallback === "function") {
imgToPredict = this.video;
callback = inputOrCallback;
}
if (typeof cb === "function") {
callback = cb;
}
return _context7.abrupt("return", (0, _callcallback2.default)(this.classifyInternal(imgToPredict), callback));
case 5:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function classify(_x11, _x12) {
return _ref7.apply(this, arguments);
}
return classify;
}()
}, {
key: "classifyInternal",
value: function () {
var _ref8 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee8(imgToPredict) {
var _this3 = this;
var predictedClasses, results;
return _regenerator2.default.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
if (!(this.usageType !== "classifier")) {
_context8.next = 2;
break;
}
throw new Error("Mobilenet Feature Extraction has not been set to be a classifier.");
case 2:
_context8.next = 4;
return tf.nextFrame();
case 4:
this.isPredicting = true;
predictedClasses = tf.tidy(function () {
var imageResize = imgToPredict === _this3.video ? null : [IMAGE_SIZE, IMAGE_SIZE];
var processedImg = (0, _imageUtilities.imgToTensor)(imgToPredict, imageResize);
var predictions = _this3.jointModel.predict(processedImg);
return (0, _from2.default)(predictions.as1D().dataSync());
});
_context8.next = 8;
return predictedClasses.map(function (confidence, index) {
var label = _this3.mapStringToIndex.length > 0 && _this3.mapStringToIndex[index] ? _this3.mapStringToIndex[index] : index;
return {
label: label,
confidence: confidence
};
}).sort(function (a, b) {
return b.confidence - a.confidence;
});
case 8:
results = _context8.sent;
return _context8.abrupt("return", results);
case 10:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function classifyInternal(_x13) {
return _ref8.apply(this, arguments);
}
return classifyInternal;
}()
/**
* Predicts a continues values based on a new retrained model.
* .regression() needs to be used with this.
* @param {HTMLVideoElement || p5.Video || function} inputOrCallback
* @param {function} cb
*/
/* eslint max-len: ["error", { "code": 180 }] */
}, {
key: "predict",
value: function () {
var _ref9 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee9(inputOrCallback, cb) {
var imgToPredict, callback;
return _regenerator2.default.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
imgToPredict = void 0;
callback = void 0;
if (inputOrCallback instanceof HTMLImageElement || inputOrCallback instanceof HTMLVideoElement || inputOrCallback instanceof HTMLCanvasElement || inputOrCallback instanceof ImageData) {
imgToPredict = inputOrCallback;
} else if ((typeof inputOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(inputOrCallback)) === "object" && (inputOrCallback.elt instanceof HTMLImageElement || inputOrCallback.elt instanceof HTMLVideoElement || inputOrCallback.elt instanceof HTMLCanvasElement || inputOrCallback.elt instanceof ImageData)) {
imgToPredict = inputOrCallback.elt; // p5.js image element
} else if (typeof inputOrCallback === "function") {
imgToPredict = this.video;
callback = inputOrCallback;
}
if (typeof cb === "function") {
callback = cb;
}
return _context9.abrupt("return", (0, _callcallback2.default)(this.predictInternal(imgToPredict), callback));
case 5:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function predict(_x14, _x15) {
return _ref9.apply(this, arguments);
}
return predict;
}()
}, {
key: "predictInternal",
value: function () {
var _ref10 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee10(imgToPredict) {
var _this4 = this;
var predictedClass, prediction;
return _regenerator2.default.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (!(this.usageType !== "regressor")) {
_context10.next = 2;
break;
}
throw new Error("Mobilenet Feature Extraction has not been set to be a regressor.");
case 2:
_context10.next = 4;
return tf.nextFrame();
case 4:
this.isPredicting = true;
predictedClass = tf.tidy(function () {
var imageResize = imgToPredict === _this4.video ? null : [IMAGE_SIZE, IMAGE_SIZE];
var processedImg = (0, _imageUtilities.imgToTensor)(imgToPredict, imageResize);
var predictions = _this4.jointModel.predict(processedImg);
return predictions.as1D();
});
_context10.next = 8;
return predictedClass.data();
case 8:
prediction = _context10.sent;
predictedClass.dispose();
return _context10.abrupt("return", { value: prediction[0] });
case 11:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function predictInternal(_x16) {
return _ref10.apply(this, arguments);
}
return predictInternal;
}()
}, {
key: "load",
value: function () {
var _ref11 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee11() {
var _this5 = this;
var filesOrPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var callback = arguments[1];
var model, weights, fileResult, fileData;
return _regenerator2.default.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
if (!(typeof filesOrPath !== "string")) {
_context11.next = 9;
break;
}
model = null;
weights = null;
(0, _from2.default)(filesOrPath).forEach(function (file) {
if (file.name.includes(".json")) {
model = file;
var fr = new FileReader();
fr.onload = function (d) {
if (JSON.parse(d.target.result).ml5Specs) {
_this5.mapStringToIndex = JSON.parse(d.target.result).ml5Specs.mapStringToIndex;
}
};
fr.readAsText(file);
} else if (file.name.includes(".bin")) {
weights = file;
}
});
_context11.next = 6;
return tf.loadLayersModel(tf.io.browserFiles([model, weights]));
case 6:
this.jointModel = _context11.sent;
_context11.next = 18;
break;
case 9:
_context11.next = 11;
return _axios2.default.get(filesOrPath);
case 11:
fileResult = _context11.sent;
fileData = fileResult.data;
if (fileData.ml5Specs) {
this.mapStringToIndex = fileData.ml5Specs.mapStringToIndex;
}
_context11.next = 16;
return tf.loadLayersModel(filesOrPath);
case 16:
this.jointModel = _context11.sent;
if (callback) {
callback();
}
case 18:
return _context11.abrupt("return", this.jointModel);
case 19:
case "end":
return _context11.stop();
}
}
}, _callee11, this);
}));
function load() {
return _ref11.apply(this, arguments);
}
return load;
}()
}, {
key: "save",
value: function () {
var _ref12 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee13(callback, name) {
var _this6 = this;
return _regenerator2.default.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
if (this.jointModel) {
_context13.next = 2;
break;
}
throw new Error("No model found.");
case 2:
this.jointModel.save(tf.io.withSaveHandler(function () {
var _ref13 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee12(data) {
var modelName;
return _regenerator2.default.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
modelName = "model";
if (name) modelName = name;
_this6.weightsManifest = {
modelTopology: data.modelTopology,
weightsManifest: [{
paths: ["./" + modelName + ".weights.bin"],
weights: data.weightSpecs
}],
ml5Specs: {
mapStringToIndex: _this6.mapStringToIndex
}
};
_context12.next = 5;
return (0, _io.saveBlob)(data.weightData, modelName + ".weights.bin", "application/octet-stream");
case 5:
_context12.next = 7;
return (0, _io.saveBlob)((0, _stringify2.default)(_this6.weightsManifest), modelName + ".json", "text/plain");
case 7:
if (callback) {
callback();
}
case 8:
case "end":
return _context12.stop();
}
}
}, _callee12, _this6);
}));
return function (_x20) {
return _ref13.apply(this, arguments);
};
}()));
case 3:
case "end":
return _context13.stop();
}
}
}, _callee13, this);
}));
function save(_x18, _x19) {
return _ref12.apply(this, arguments);
}
return save;
}()
}, {
key: "mobilenetInfer",
value: function mobilenetInfer(input) {
var _this7 = this;
var embedding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var img = input;
if (img instanceof tf.Tensor || img instanceof ImageData || img instanceof HTMLImageElement || img instanceof HTMLCanvasElement || img instanceof HTMLVideoElement) {
return tf.tidy(function () {
if (!(img instanceof tf.Tensor)) {
img = tf.browser.fromPixels(img);
}
var normalized = img.toFloat().sub(_this7.normalizationOffset).div(_this7.normalizationOffset);
// Resize the image to
var resized = normalized;
if (img.shape[0] !== IMAGE_SIZE || img.shape[1] !== IMAGE_SIZE) {
var alignCorners = true;
resized = tf.image.resizeBilinear(normalized, [IMAGE_SIZE, IMAGE_SIZE], alignCorners);
}
// Reshape so we can pass it to predict.
var batched = resized.reshape([-1, IMAGE_SIZE, IMAGE_SIZE, 3]);
var result = void 0;
if (embedding) {
var embeddingName = EMBEDDING_NODES[_this7.config.version];
var internal = _this7.model.execute(batched, embeddingName);
result = internal.squeeze([1, 2]);
} else {
var logits1001 = _this7.model.predict(batched);
result = logits1001.slice([0, 1], [-1, 1000]);
}
return result;
});
}
return null;
}
}, {
key: "infer",
value: function infer(input, endpoint) {
var imgToPredict = void 0;
var endpointToPredict = void 0;
if (input instanceof HTMLImageElement || input instanceof HTMLVideoElement || input instanceof HTMLCanvasElement || input instanceof ImageData) {
imgToPredict = input;
} else if ((typeof input === "undefined" ? "undefined" : (0, _typeof3.default)(input)) === "object" && (input.elt instanceof HTMLImageElement || input.elt instanceof HTMLVideoElement || input.elt instanceof HTMLCanvasElement || input.elt instanceof ImageData)) {
imgToPredict = input.elt; // p5.js image/canvas/video element
} else {
throw new Error("No input image found.");
}
if (endpoint && typeof endpoint === "string") {
endpointToPredict = endpoint;
} else {
endpointToPredict = "conv_preds";
}
return this.mobilenetInfer(imgToPredict, endpointToPredict);
}
}]);
return Mobilenet;
}();
exports.default = Mobilenet;
/***/ }),
/* 363 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _Mobilenet = __webpack_require__(362);
var _Mobilenet2 = _interopRequireDefault(_Mobilenet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint max-len: ["error", { "code": 180 }] */
/**
* @typedef {Object} options
* @property {number} version - default 1
* @property {number} alpha - default 1.0
* @property {number} topk - default 3
* @property {number} learningRate - default 0.0001
* @property {number} hiddenUnits - default 100
* @property {number} epochs - default 20
* @property {number} numClasses - default 2
* @property {number} batchSize - default 0.4
*/
/**
* Create a featureExtractor.
* @param {model} model - The model from which extract the learned features. Case-insensitive
* @param {options || function} optionsOrCallback - Optional.
* @param {function} cb - Optional.
*/
var featureExtractor = function featureExtractor(model, optionsOrCallback, cb) {
var modelName = void 0;
if (typeof model !== 'string') {
throw new Error('Please specify a model to use. E.g: "MobileNet"');
} else {
modelName = model.toLowerCase();
}
var options = {};
var callback = cb;
if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object') {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
if (modelName === 'mobilenet') {
return new _Mobilenet2.default(options, callback);
}
throw new Error(modelName + ' is not a valid model.');
}; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
General Feature Extractor Manager
*/
exports.default = featureExtractor;
/***/ }),
/* 364 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KNNClassifier", function() { return KNNClassifier; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return create; });
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
// @tensorflow/tfjs-models Copyright 2019 Google
function __awaiter(t,a,e,s){return new(e||(e=Promise))(function(r,i){function n(t){try{o(s.next(t))}catch(t){i(t)}}function l(t){try{o(s.throw(t))}catch(t){i(t)}}function o(t){t.done?r(t.value):new e(function(a){a(t.value)}).then(n,l)}o((s=s.apply(t,a||[])).next())})}function __generator(t,a){var e,s,r,i,n={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function l(i){return function(l){return function(i){if(e)throw new TypeError("Generator is already executing.");for(;n;)try{if(e=1,s&&(r=2&i[0]?s.return:i[0]?s.throw||((r=s.return)&&r.call(s),0):s.next)&&!(r=r.call(s,i[1])).done)return r;switch(s=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return n.label++,{value:i[1],done:!1};case 5:n.label++,s=i[1],i=[0];continue;case 7:i=n.ops.pop(),n.trys.pop();continue;default:if(!(r=(r=n.trys).length>0&&r[r.length-1])&&(6===i[0]||2===i[0])){n=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){n.label=i[1];break}if(6===i[0]&&n.label<r[1]){n.label=r[1],r=i;break}if(r&&n.label<r[2]){n.label=r[2],n.ops.push(i);break}r[2]&&n.ops.pop(),n.trys.pop();continue}i=a.call(t,n)}catch(t){i=[6,t],s=0}finally{e=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,l])}}}function concatWithNulls(t,a){return null==t&&null==a?null:null==t?a.clone():null===a?t.clone():t.concat(a,0)}function topK(t,a){for(var e=[],s=0;s<t.length;s++)e.push({value:t[s],index:s});e.sort(function(t,a){return a.value-t.value});var r=new Float32Array(a),i=new Int32Array(a);for(s=0;s<a;s++)r[s]=e[s].value,i[s]=e[s].index;return{values:r,indices:i}}var KNNClassifier=function(){function t(){this.classDatasetMatrices={},this.classExampleCount={},this.labelToClassId={},this.nextClassId=0}return t.prototype.addExample=function(t,a){var e=this;if(null==this.exampleShape&&(this.exampleShape=t.shape),!_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["util"].arraysEqual(this.exampleShape,t.shape))throw new Error("Example shape provided, "+t.shape+" does not match previously provided example shapes "+this.exampleShape+".");this.clearTrainDatasetMatrix(),a in this.labelToClassId||(this.labelToClassId[a]=this.nextClassId++),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var s=e.normalizeVectorToUnitLength(t.flatten()),r=s.shape[0];if(null==e.classDatasetMatrices[a])e.classDatasetMatrices[a]=s.as2D(1,r);else{var i=e.classDatasetMatrices[a].as2D(e.classExampleCount[a],r).concat(s.as2D(1,r),0);e.classDatasetMatrices[a].dispose(),e.classDatasetMatrices[a]=i}Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["keep"])(e.classDatasetMatrices[a]),null==e.classExampleCount[a]&&(e.classExampleCount[a]=0),e.classExampleCount[a]++})},t.prototype.similarities=function(t){var a=this;return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var e=a.normalizeVectorToUnitLength(t.flatten()),s=e.shape[0];if(null==a.trainDatasetMatrix){var r=null;for(var i in a.classDatasetMatrices)r=concatWithNulls(r,a.classDatasetMatrices[i]);a.trainDatasetMatrix=r}if(null==a.trainDatasetMatrix)return console.warn("Cannot predict without providing training examples."),null;Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["keep"])(a.trainDatasetMatrix);var n=a.getNumExamples();return a.trainDatasetMatrix.as2D(n,s).matMul(e.as2D(s,1)).as1D()})},t.prototype.predictClass=function(t,a){return void 0===a&&(a=3),__awaiter(this,void 0,void 0,function(){var e,s,r,i,n=this;return __generator(this,function(l){switch(l.label){case 0:if(a<1)throw new Error("Please provide a positive integer k value to predictClass.");if(0===this.getNumExamples())throw new Error("You have not added any examples to the KNN classifier. Please add examples before calling predictClass.");return e=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return n.similarities(t).asType("float32")}),s=Math.min(a,this.getNumExamples()),i=topK,[4,e.data()];case 1:return r=i.apply(void 0,[l.sent(),s]).indices,e.dispose(),[2,this.calculateTopClass(r,s)]}})})},t.prototype.clearClass=function(t){if(null==this.classDatasetMatrices[t])throw new Error("Cannot clear invalid class "+t);delete this.classDatasetMatrices[t],delete this.classExampleCount[t],this.clearTrainDatasetMatrix()},t.prototype.clearAllClasses=function(){for(var t in this.classDatasetMatrices)this.clearClass(t)},t.prototype.getClassExampleCount=function(){return this.classExampleCount},t.prototype.getClassifierDataset=function(){return this.classDatasetMatrices},t.prototype.getNumClasses=function(){return Object.keys(this.classExampleCount).length},t.prototype.setClassifierDataset=function(t){for(var a in this.clearTrainDatasetMatrix(),this.classDatasetMatrices=t,t)this.classExampleCount[a]=t[a].shape[0]},t.prototype.calculateTopClass=function(t,a){var e,s={};if(null==t)return{classIndex:this.labelToClassId[e],label:e,confidences:s};var r={},i=0;for(var n in this.classDatasetMatrices)i+=this.classExampleCount[n],r[n]=i;var l={};for(var n in this.classDatasetMatrices)l[n]=0;for(var o=0;o<t.length;o++){var c=t[o];for(var n in this.classDatasetMatrices)if(c<r[n]){l[n]++;break}}var u=0;for(var n in this.classDatasetMatrices){var p=l[n]/a;p>u&&(u=p,e=n),s[n]=p}return{classIndex:this.labelToClassId[e],label:e,confidences:s}},t.prototype.clearTrainDatasetMatrix=function(){null!=this.trainDatasetMatrix&&(this.trainDatasetMatrix.dispose(),this.trainDatasetMatrix=null)},t.prototype.normalizeVectorToUnitLength=function(t){return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var a=t.norm();return Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__["div"])(t,a)})},t.prototype.getNumExamples=function(){var t=0;for(var a in this.classDatasetMatrices)t+=this.classExampleCount[a];return t},t.prototype.dispose=function(){for(var t in this.clearTrainDatasetMatrix(),this.classDatasetMatrices)this.classDatasetMatrices[t].dispose()},t}();function create(){return new KNNClassifier}
/***/ }),
/* 365 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(65);
var $keys = __webpack_require__(88);
__webpack_require__(209)('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/* 366 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(365);
module.exports = __webpack_require__(18).Object.keys;
/***/ }),
/* 367 */
/***/ (function(module, exports, __webpack_require__) {
var core = __webpack_require__(18);
var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify });
module.exports = function stringify(it) { // eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
};
/***/ }),
/* 368 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _stringify = __webpack_require__(99);
var _stringify2 = _interopRequireDefault(_stringify);
var _keys = __webpack_require__(54);
var _keys2 = _interopRequireDefault(_keys);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _knnClassifier = __webpack_require__(364);
var knnClassifier = _interopRequireWildcard(_knnClassifier);
var _io = __webpack_require__(115);
var io = _interopRequireWildcard(_io);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
* A K-nearest neighbors (KNN) classifier that allows fast
* custom model training on top of any tensor input. Useful for transfer
* learning with an embedding from another pretrained model.
*/
var KNN = function () {
/**
* Create a KNNClassifier instance.
*/
function KNN() {
(0, _classCallCheck3.default)(this, KNN);
this.knnClassifier = knnClassifier.create();
this.mapStringToIndex = [];
}
/**
* Adding an example to a class.
* @param {*} input - An example to add to the dataset, usually an activation from another model.
* @param {number || String} classIndexOrLabel The class index(number) or label(string) of the example.
*/
(0, _createClass3.default)(KNN, [{
key: 'addExample',
value: function addExample(input, classIndexOrLabel) {
var classIndex = void 0;
var example = void 0;
if (typeof classIndexOrLabel === 'string') {
if (!this.mapStringToIndex.includes(classIndexOrLabel)) {
classIndex = this.mapStringToIndex.push(classIndexOrLabel) - 1;
} else {
classIndex = this.mapStringToIndex.indexOf(classIndexOrLabel);
}
} else if (typeof classIndexOrLabel === 'number') {
classIndex = classIndexOrLabel;
}
if (Array.isArray(input)) {
example = tf.tensor(input);
} else {
example = input;
}
this.knnClassifier.addExample(example, classIndex);
}
/**
* Classify an new input. It returns an object with a top classIndex and label, confidences mapping all class indices to their confidence, and confidencesByLabel mapping all classes' confidence by label.
* @param {*} input - An example to make a prediction on, could be an activation from another model or an array of numbers.
* @param {number} k - Optional. The K value to use in K-nearest neighbors. The algorithm will first find the K nearest examples from those it was previously shown, and then choose the class that appears the most as the final prediction for the input example. Defaults to 3. If examples < k, k = examples.
* @param {function} callback - Optional. A function to be called once the input has been classified. If no callback is provided, it will return a promise that will be resolved once the model has classified the new input.
*/
}, {
key: 'classify',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(input, kOrCallback, cb) {
var k, callback, example;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
k = 3;
callback = cb;
example = void 0;
if (typeof kOrCallback === 'number') {
k = kOrCallback;
} else if (typeof kOrCallback === 'function') {
callback = kOrCallback;
}
if (Array.isArray(input)) {
example = tf.tensor(input);
} else {
example = input;
}
return _context.abrupt('return', (0, _callcallback2.default)(this.classifyInternal(example, k), callback));
case 6:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function classify(_x, _x2, _x3) {
return _ref.apply(this, arguments);
}
return classify;
}()
}, {
key: 'classifyInternal',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(input, k) {
var _this = this;
var numClass, res, label, confidences, indexes;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
numClass = this.knnClassifier.getNumClasses();
if (!(numClass <= 0)) {
_context2.next = 5;
break;
}
throw new Error('There is no example in any class');
case 5:
_context2.next = 7;
return this.knnClassifier.predictClass(input, k);
case 7:
res = _context2.sent;
if (this.mapStringToIndex.length > 0) {
if (res.classIndex || res.classIndex === 0) {
label = this.mapStringToIndex[res.classIndex];
if (label) res.label = label;
}
if (res.confidences) {
res.confidencesByLabel = {};
confidences = res.confidences;
indexes = (0, _keys2.default)(confidences);
indexes.forEach(function (index) {
var label = _this.mapStringToIndex[index];
res.confidencesByLabel[label] = confidences[index];
});
}
}
return _context2.abrupt('return', res);
case 10:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function classifyInternal(_x4, _x5) {
return _ref2.apply(this, arguments);
}
return classifyInternal;
}()
/**
* Clear all examples in a label.
* @param {number||number} labelIndex - The class index or label, a number or a string.
*/
}, {
key: 'clearLabel',
value: function clearLabel(labelIndex) {
var classIndex = void 0;
if (typeof labelIndex === 'string') {
if (this.mapStringToIndex.includes(labelIndex)) {
classIndex = this.mapStringToIndex.indexOf(labelIndex);
}
} else if (typeof labelIndex === 'number') {
classIndex = labelIndex;
}
this.knnClassifier.clearClass(classIndex);
}
}, {
key: 'clearAllLabels',
value: function clearAllLabels() {
this.mapStringToIndex = [];
this.knnClassifier.clearAllClasses();
}
/**
* Get the example count for each label. It returns an object that maps class label to example count for each class.
* @returns {Number}
*/
}, {
key: 'getCountByLabel',
value: function getCountByLabel() {
var _this2 = this;
var countByIndex = this.knnClassifier.getClassExampleCount();
if (this.mapStringToIndex.length > 0) {
var countByLabel = {};
(0, _keys2.default)(countByIndex).forEach(function (key) {
if (_this2.mapStringToIndex[key]) {
var label = _this2.mapStringToIndex[key];
countByLabel[label] = countByIndex[key];
}
});
return countByLabel;
}
return countByIndex;
}
/**
* Get the example count for each class. It returns an object that maps class index to example count for each class.
* @returns {Number}
*/
}, {
key: 'getCount',
value: function getCount() {
return this.knnClassifier.getClassExampleCount();
}
}, {
key: 'getClassifierDataset',
value: function getClassifierDataset() {
return this.knnClassifier.getClassifierDataset();
}
}, {
key: 'setClassifierDataset',
value: function setClassifierDataset(dataset) {
this.knnClassifier.setClassifierDataset(dataset);
}
/**
* It returns the total number of labels.
* @returns {String}
*/
}, {
key: 'getNumLabels',
value: function getNumLabels() {
return this.knnClassifier.getNumClasses();
}
}, {
key: 'dispose',
value: function dispose() {
this.knnClassifier.dispose();
}
/**
* Download the whole dataset as a JSON file. It's useful for saving state.
* @param {String} name - Optional. The name of the JSON file that will be downloaded. e.g. "myKNN" or "myKNN.json". If no fileName is provided, the default file name is "myKNN.json".
*/
}, {
key: 'save',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(name) {
var _this3 = this;
var dataset, tensors, fileName;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
dataset = this.knnClassifier.getClassifierDataset();
if (this.mapStringToIndex.length > 0) {
(0, _keys2.default)(dataset).forEach(function (key) {
if (_this3.mapStringToIndex[key]) {
dataset[key].label = _this3.mapStringToIndex[key];
}
});
}
tensors = (0, _keys2.default)(dataset).map(function (key) {
var t = dataset[key];
if (t) {
return t.dataSync();
}
return null;
});
fileName = 'myKNN.json';
if (name) {
fileName = name.endsWith('.json') ? name : name + '.json';
}
_context3.next = 7;
return io.saveBlob((0, _stringify2.default)({ dataset: dataset, tensors: tensors }), fileName, 'application/octet-stream');
case 7:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function save(_x6) {
return _ref3.apply(this, arguments);
}
return save;
}()
/**
* Load a dataset from a JSON file. It's useful for restoring state.
* @param {String} pathOrData - The path for a valid JSON file.
* @param {function} callback - Optional. A function to run once the dataset has been loaded. If no callback is provided, it will return a promise that will be resolved once the dataset has loaded.
*/
}, {
key: 'load',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(pathOrData, callback) {
var data, _data, dataset, tensors, tensorsData;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
data = void 0;
if (!((typeof pathOrData === 'undefined' ? 'undefined' : (0, _typeof3.default)(pathOrData)) === 'object')) {
_context4.next = 5;
break;
}
data = pathOrData;
_context4.next = 8;
break;
case 5:
_context4.next = 7;
return io.loadFile(pathOrData);
case 7:
data = _context4.sent;
case 8:
if (data) {
_data = data, dataset = _data.dataset, tensors = _data.tensors;
this.mapStringToIndex = (0, _keys2.default)(dataset).map(function (key) {
return dataset[key].label;
});
tensorsData = tensors.map(function (tensor, i) {
if (tensor) {
var values = (0, _keys2.default)(tensor).map(function (v) {
return tensor[v];
});
return tf.tensor(values, dataset[i].shape, dataset[i].dtype);
}
return null;
}).reduce(function (acc, cur, j) {
acc[j] = cur;
return acc;
}, {});
this.knnClassifier.setClassifierDataset(tensorsData);
if (callback) {
callback();
}
}
case 9:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function load(_x7, _x8) {
return _ref4.apply(this, arguments);
}
return load;
}()
}]);
return KNN;
}();
var KNNClassifier = function KNNClassifier() {
return new KNN();
};
exports.default = KNNClassifier;
/***/ }),
/* 369 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return create; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utils", function() { return utils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BACKGROUND_NOISE_TAG", function() { return BACKGROUND_NOISE_TAG; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Dataset", function() { return Dataset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMaxIntensityFrameIndex", function() { return getMaxIntensityFrameIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spectrogram2IntensityCurve", function() { return spectrogram2IntensityCurve; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteSavedTransferModel", function() { return deleteSavedTransferModel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "listSavedTransferModels", function() { return listSavedTransferModels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UNKNOWN_TAG", function() { return UNKNOWN_TAG; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "version", function() { return version; });
/* harmony import */ var _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/**
* @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 extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function __extends(e,t){function r(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var __assign=function(){return(__assign=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e}).apply(this,arguments)};function __awaiter(e,t,r,n){return new(r||(r=Promise))(function(a,i){function o(e){try{l(n.next(e))}catch(e){i(e)}}function s(e){try{l(n.throw(e))}catch(e){i(e)}}function l(e){e.done?a(e.value):new r(function(t){t(e.value)}).then(o,s)}l((n=n.apply(e,t||[])).next())})}function __generator(e,t){var r,n,a,i,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(a=2&i[0]?n.return:i[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,i[1])).done)return a;switch(n=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],n=0}finally{r=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}function __values(e){var t="function"==typeof Symbol&&e[Symbol.iterator],r=0;return t?t.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}function __read(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,a,i=r.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)o.push(n.value)}catch(e){a={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(a)throw a.error}}return o}function __spread(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(__read(arguments[t]));return e}function loadMetadataJson(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return[2,new Promise(function(t,r){if(0===e.indexOf("http://")||0===e.indexOf("https://"))fetch(e).then(function(e){e.json().then(function(e){return t(e)})});else if(0===e.indexOf("file://")){__webpack_require__(210).readFile(e.slice("file://".length),{encoding:"utf-8"},function(e,r){return t(JSON.parse(r))})}else r(new Error("Unsupported URL scheme in metadata URL: "+e+". Supported schemes are: http://, https://, and (node.js-only) file://"))})]})})}var EPSILON=null;function normalize(e){return null==EPSILON&&(EPSILON=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["backend"])().epsilon()),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var t=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["moments"])(e),r=t.mean,n=t.variance;return e.sub(r).div(n.sqrt().add(EPSILON))})}function normalizeFloat32Array(e){if(e.length<2)throw new Error("Cannot normalize a Float32Array with fewer than 2 elements.");return null==EPSILON&&(EPSILON=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["backend"])().epsilon()),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var t=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["moments"])(Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])(e)),r=t.mean,n=t.variance,a=r.arraySync(),i=Math.sqrt(n.arraySync()),o=Array.from(e).map(function(e){return(e-a)/(i+EPSILON)});return new Float32Array(o)})}function getAudioContextConstructor(){return window.AudioContext||window.webkitAudioContext}function getAudioMediaStream(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,navigator.mediaDevices.getUserMedia({audio:null==e||e,video:!1})];case 1:return[2,t.sent()]}})})}function playRawAudio(e,t){var r=new(window.AudioContext||window.webkitAudioContext),n=r.createBuffer(1,e.data.length,e.sampleRateHz);n.getChannelData(0).set(e.data);var a=r.createBufferSource();a.buffer=n,a.connect(r.destination),a.start(),a.onended=function(){null!=t&&t()}}var BrowserFftFeatureExtractor=function(){function e(e){var t=this;if(null==e)throw new Error("Required configuration object is missing for BrowserFftFeatureExtractor constructor");if(null==e.spectrogramCallback)throw new Error("spectrogramCallback cannot be null or undefined");if(!(e.numFramesPerSpectrogram>0))throw new Error("Invalid value in numFramesPerSpectrogram: "+e.numFramesPerSpectrogram);if(e.suppressionTimeMillis<0)throw new Error("Expected suppressionTimeMillis to be >= 0, but got "+e.suppressionTimeMillis);if(this.suppressionTimeMillis=e.suppressionTimeMillis,this.spectrogramCallback=e.spectrogramCallback,this.numFrames=e.numFramesPerSpectrogram,this.sampleRateHz=e.sampleRateHz||44100,this.fftSize=e.fftSize||1024,this.frameDurationMillis=this.fftSize/this.sampleRateHz*1e3,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.overlapFactor=e.overlapFactor,this.includeRawAudio=e.includeRawAudio,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(this.overlapFactor>=0&&this.overlapFactor<1,function(){return"Expected overlapFactor to be >= 0 and < 1, but got "+t.overlapFactor}),this.columnTruncateLength>this.fftSize)throw new Error("columnTruncateLength "+this.columnTruncateLength+" exceeds fftSize ("+this.fftSize+").");this.audioContextConstructor=getAudioContextConstructor()}return e.prototype.start=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n;return __generator(this,function(a){switch(a.label){case 0:if(null!=this.frameIntervalTask)throw new Error("Cannot start already-started BrowserFftFeatureExtractor");return t=this,[4,getAudioMediaStream(e)];case 1:return t.stream=a.sent(),this.audioContext=new this.audioContextConstructor,this.audioContext.sampleRate!==this.sampleRateHz&&console.warn("Mismatch in sampling rate: Expected: "+this.sampleRateHz+"; Actual: "+this.audioContext.sampleRate),r=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=0,r.connect(this.analyser),this.freqDataQueue=[],this.freqData=new Float32Array(this.fftSize),this.includeRawAudio&&(this.timeDataQueue=[],this.timeData=new Float32Array(this.fftSize)),n=Math.max(1,Math.round(this.numFrames*(1-this.overlapFactor))),this.tracker=new Tracker(n,Math.round(this.suppressionTimeMillis/this.frameDurationMillis)),this.frameIntervalTask=setInterval(this.onAudioFrame.bind(this),this.fftSize/this.sampleRateHz*1e3),[2]}})})},e.prototype.onAudioFrame=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n;return __generator(this,function(a){switch(a.label){case 0:return this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0?[2]:(this.freqDataQueue.push(this.freqData.slice(0,this.columnTruncateLength)),this.includeRawAudio&&(this.analyser.getFloatTimeDomainData(this.timeData),this.timeDataQueue.push(this.timeData.slice())),this.freqDataQueue.length>this.numFrames&&this.freqDataQueue.shift(),this.tracker.tick()?(e=flattenQueue(this.freqDataQueue),t=getInputTensorFromFrequencyData(e,[1,this.numFrames,this.columnTruncateLength,1]),r=void 0,this.includeRawAudio&&(n=flattenQueue(this.timeDataQueue),r=getInputTensorFromFrequencyData(n,[1,this.numFrames*this.fftSize])),[4,this.spectrogramCallback(t,r)]):[3,2]);case 1:a.sent()&&this.tracker.suppress(),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["dispose"])([t,r]),a.label=2;case 2:return[2]}})})},e.prototype.stop=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){if(null==this.frameIntervalTask)throw new Error("Cannot stop because there is no ongoing streaming activity.");return clearInterval(this.frameIntervalTask),this.frameIntervalTask=null,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop(),[2]})})},e.prototype.setConfig=function(e){throw new Error("setConfig() is not implemented for BrowserFftFeatureExtractor.")},e.prototype.getFeatures=function(){throw new Error("getFeatures() is not implemented for BrowserFftFeatureExtractor. Use the spectrogramCallback field of the constructor config instead.")},e}();function flattenQueue(e){var t=e[0].length,r=new Float32Array(e.length*t);return e.forEach(function(e,n){return r.set(e,n*t)}),r}function getInputTensorFromFrequencyData(e,t){var r=new Float32Array(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].sizeFromShape(t));return r.set(e,r.length-e.length),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor"])(r,t)}var Tracker=function(){function e(e,t){var r=this;this.period=e,this.suppressionTime=null==t?0:t,this.counter=0,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(this.period>0,function(){return"Expected period to be positive, but got "+r.period})}return e.prototype.tick=function(){return this.counter++,this.counter%this.period==0&&(null==this.suppressionOnset||this.counter-this.suppressionOnset>this.suppressionTime)},e.prototype.suppress=function(){this.suppressionOnset=this.counter},e}();function concatenateArrayBuffers(e){var t=0;e.forEach(function(e){t+=e.byteLength});var r=new Uint8Array(t),n=0;return e.forEach(function(e){r.set(new Uint8Array(e),n),n+=e.byteLength}),r.buffer}function concatenateFloat32Arrays(e){var t=0;e.forEach(function(e){return t+=e.length});var r=new Float32Array(t),n=0;return e.forEach(function(e){r.set(e,n),n+=e.length}),r}function string2ArrayBuffer(e){if(null==e)throw new Error("Received null or undefind string");for(var t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length),n=0;n<t.length;++n)r[n]=t.charCodeAt(n);return r.buffer}function arrayBuffer2String(e){if(null==e)throw new Error("Received null or undefind buffer");var t=new Uint8Array(e);return decodeURIComponent(escape(String.fromCharCode.apply(String,__spread(t))))}function getUID(){function e(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()}function getRandomInteger(e,t){return Math.floor((t-e)*Math.random())+e}function balancedTrainValSplit(e,t,r){return _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r>0&&r<1,function(){return"validationSplit is expected to be >0 and <1, but got "+r}),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){for(var n=t.argMax(-1).dataSync(),a=[],i=0;i<n.length;++i){var o=n[i];null==a[o]&&(a[o]=[]),a[o].push(i)}var s=a.length,l=[],u=[];a.map(function(e){return _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].shuffle(e)});for(i=0;i<s;++i)for(var c=a[i],h=Math.round(c.length*(1-r)),d=0;d<c.length;++d)d<h?l.push(c[d]):u.push(c[d]);return{trainXs:Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["gather"])(e,l),trainYs:Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["gather"])(t,l),valXs:Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["gather"])(e,u),valYs:Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["gather"])(t,u)}})}function balancedTrainValSplitNumArrays(e,t,r){var n,a,i,o,s,l,u,c;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r>0&&r<1,function(){return"validationSplit is expected to be >0 and <1, but got "+r});for(var h=!Array.isArray(e[0]),d=t,p=[],f=0;f<d.length;++f){var m=d[f];null==p[m]&&(p[m]=[]),p[m].push(f)}var g=p.length,v=[],y=[];p.map(function(e){return _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].shuffle(e)});for(f=0;f<g;++f)for(var w=p[f],b=Math.round(w.length*(1-r)),_=0;_<w.length;++_)_<b?v.push(w[_]):y.push(w[_]);if(h){var S=[],x=[],E=[],A=[];try{for(var T=__values(v),I=T.next();!I.done;I=T.next()){var D=I.value;S.push(e[D]),x.push(t[D])}}catch(e){n={error:e}}finally{try{I&&!I.done&&(a=T.return)&&a.call(T)}finally{if(n)throw n.error}}try{for(var F=__values(y),M=F.next();!M.done;M=F.next()){D=M.value;E.push(e[D]),A.push(t[D])}}catch(e){i={error:e}}finally{try{M&&!M.done&&(o=F.return)&&o.call(F)}finally{if(i)throw i.error}}return{trainXs:S,trainYs:x,valXs:E,valYs:A}}S=[],x=[],E=[],A=[];try{for(var O=__values(v),R=O.next();!R.done;R=O.next()){D=R.value;S.push(e[D]),x.push(t[D])}}catch(e){s={error:e}}finally{try{R&&!R.done&&(l=O.return)&&l.call(O)}finally{if(s)throw s.error}}try{for(var z=__values(y),L=z.next();!L.done;L=z.next()){D=L.value;E.push(e[D]),A.push(t[D])}}catch(e){u={error:e}}finally{try{L&&!L.done&&(c=z.return)&&c.call(z)}finally{if(u)throw u.error}}return{trainXs:S,trainYs:x,valXs:E,valYs:A}}var DATASET_SERIALIZATION_DESCRIPTOR="TFJSSCDS",DATASET_SERIALIZATION_VERSION=1,BACKGROUND_NOISE_TAG="_background_noise_",Dataset=function(){function e(e){if(this.examples={},this.label2Ids={},null!=e)for(var t=arrayBuffer2SerializedExamples(e),r=0,n=0;n<t.manifest.length;++n){var a=t.manifest[n],i=a.spectrogramNumFrames*a.spectrogramFrameSize;null!=a.rawAudioNumSamples&&(i+=a.rawAudioNumSamples),i*=4,this.addExample(deserializeExample({spec:a,data:t.data.slice(r,r+i)})),r+=i}}return e.prototype.addExample=function(e){_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e,function(){return"Got null or undefined example"}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e.label&&e.label.length>0,function(){return"Expected label to be a non-empty string, but got "+JSON.stringify(e.label)});var t=getUID();return this.examples[t]=e,e.label in this.label2Ids||(this.label2Ids[e.label]=[]),this.label2Ids[e.label].push(t),t},e.prototype.merge=function(e){var t,r,n,a;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(e!==this,function(){return"Cannot merge a dataset into itself"});var i=e.getVocabulary();try{for(var o=__values(i),s=o.next();!s.done;s=o.next()){var l=s.value,u=e.getExamples(l);try{for(var c=__values(u),h=c.next();!h.done;h=c.next()){var d=h.value;this.addExample(d.example)}}catch(e){n={error:e}}finally{try{h&&!h.done&&(a=c.return)&&a.call(c)}finally{if(n)throw n.error}}}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},e.prototype.getExampleCounts=function(){var e={};for(var t in this.examples){var r=this.examples[t];r.label in e||(e[r.label]=0),e[r.label]++}return e},e.prototype.getExamples=function(e){var t=this;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e,function(){return"Expected label to be a string, but got "+JSON.stringify(e)}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(e in this.label2Ids,function(){return'No example of label "'+e+'" exists in dataset'});var r=[];return this.label2Ids[e].forEach(function(e){r.push({uid:e,example:t.examples[e]})}),r},e.prototype.getData=function(e,t){var r=this;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(this.size()>0,function(){return"Cannot get spectrograms as tensors because the dataset is empty"});var n=this.getVocabulary();null!=e?_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(-1!==n.indexOf(e),function(){return"Label "+e+" is not in the vocabulary ("+JSON.stringify(n)+")"}):_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(n.length>1,function(){return"One-hot encoding of labels requires the vocabulary to have at least two words, but it has only "+n.length+" word."}),null==t&&(t={});var a,i,o=this.getSortedUniqueNumFrames();1===o.length?(a=null==t.numFrames?o[0]:t.numFrames,i=null==t.hopFrames?1:t.hopFrames):(a=t.numFrames,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=a&&Number.isInteger(a)&&a>0,function(){return"There are "+o.length+" unique lengths among the "+r.size()+" examples of this Dataset, hence numFrames is required. But it is not provided."}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(a<=o[0],function(){return"numFrames ("+a+") exceeds the minimum numFrames ("+o[0]+") among the examples of the Dataset."}),i=t.hopFrames,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=i&&Number.isInteger(i)&&i>0,function(){return"There are "+o.length+" unique lengths among the "+r.size()+" examples of this Dataset, hence hopFrames is required. But it is not provided."}));var s=null==t.normalize||t.normalize;return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){for(var o,l,u,c=[],h=[],d=[],p=0;p<n.length;++p){var f=n[p];if(null==e||f===e){var m=r.label2Ids[f],g=function(n){var o,l,m=r.examples[n].spectrogram,g=m.frameSize;null==u?u=g:_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(g===u,function(){return"Mismatch in frameSize ("+g+" vs "+u+")"});var v=m.data.length/g,y=null;f!==BACKGROUND_NOISE_TAG&&(y=null==m.keyFrameIndex?getMaxIntensityFrameIndex(m).dataSync()[0]:m.keyFrameIndex);var w=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor3d"])(m.data,[v,g,1]),b=getValidWindows(v,y,a,i),_=function(r){var n=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var e=w.slice([r[0],0,0],[r[1]-r[0],-1,-1]);return s?normalize(e):e});t.getDataset?h.push(n.dataSync()):c.push(n),null==e&&d.push(p)};try{for(var S=__values(b),x=S.next();!x.done;x=S.next()){_(x.value)}}catch(e){o={error:e}}finally{try{x&&!x.done&&(l=S.return)&&l.call(S)}finally{if(o)throw o.error}}Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["dispose"])(w)};try{for(var v=__values(m),y=v.next();!y.done;y=v.next()){g(y.value)}}catch(e){o={error:e}}finally{try{y&&!y.done&&(l=v.return)&&l.call(v)}finally{if(o)throw o.error}}}}null!=t.augmentByMixingNoiseRatio&&r.augmentByMixingNoise(t.getDataset?h:c,d,t.augmentByMixingNoiseRatio);var w=null==t.shuffle||t.shuffle;if(t.getDataset){var b=null==t.datasetBatchSize?32:t.datasetBatchSize,_=null==t.datasetValidationSplit?.15:t.datasetValidationSplit;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(_>0&&_<1,function(){return"Invalid dataset validation split: "+_});var S=h.map(function(e,t){return[e,d[t]]});_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].shuffle(S),h=S.map(function(e){return e[0]});var x=S.map(function(e){return e[1]}),E=balancedTrainValSplitNumArrays(h,x,_),A=E.trainXs,T=E.trainYs,I=E.valXs,D=E.valYs,F=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["data"].array(A).map(function(e){return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor3d"])(e,[a,u,1])}),M=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["data"].array(T).map(function(e){return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["oneHot"])([e],n.length).squeeze([0])}),O=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["data"].zip({xs:F,ys:M});w&&(O=O.shuffle(h.length)),O=O.batch(b).prefetch(4);var R=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["data"].array(I).map(function(e){return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor3d"])(e,[a,u,1])}),z=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["data"].array(D).map(function(e){return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["oneHot"])([e],n.length).squeeze([0])}),L=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["data"].zip({xs:R,ys:z});return[O,L=L.batch(b).prefetch(4)]}if(w){var N=[];c.forEach(function(e,t){N.push({x:e,y:d[t]})}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].shuffle(N),c=N.map(function(e){return e.x}),d=N.map(function(e){return e.y})}var C=null==e?Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["oneHot"])(Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])(d,"int32"),n.length).asType("float32"):void 0;return{xs:Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["stack"])(c),ys:C}})},e.prototype.augmentByMixingNoise=function(e,t,r){var n,a;if(null==e||0===e.length)throw new Error("Cannot perform augmentation because data is null or empty");for(var i=e[0]instanceof Float32Array,o=this.getVocabulary(),s=[],l=[],u=0;u<t.length;++u)o[t[u]]===BACKGROUND_NOISE_TAG?s.push(u):l.push(u);if(0===s.length)throw new Error("Cannot perform augmentation by mixing with noise when there is no example with label "+BACKGROUND_NOISE_TAG);var c=[],h=[],d=function(n){var a=s[getRandomInteger(0,s.length)],o=i?Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])(e[n]):e[n],l=i?Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor1d"])(e[a]):e[a],u=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return normalize(o.add(l.mul(r)))});i?c.push(u.dataSync()):c.push(u),h.push(t[n])};try{for(var p=__values(l),f=p.next();!f.done;f=p.next()){d(f.value)}}catch(e){n={error:e}}finally{try{f&&!f.done&&(a=p.return)&&a.call(p)}finally{if(n)throw n.error}}console.log("Data augmentation: mixing noise: added "+c.length+" examples"),c.forEach(function(t){return e.push(t)}),t.push.apply(t,__spread(h))},e.prototype.getSortedUniqueNumFrames=function(){for(var e,t,r=new Set,n=this.getVocabulary(),a=0;a<n.length;++a){var i=n[a],o=this.label2Ids[i];try{for(var s=__values(o),l=s.next();!l.done;l=s.next()){var u=l.value,c=this.examples[u].spectrogram,h=c.data.length/c.frameSize;r.add(h)}}catch(t){e={error:t}}finally{try{l&&!l.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}}var d=__spread(r);return d.sort(),d},e.prototype.removeExample=function(e){if(!(e in this.examples))throw new Error("Nonexistent example UID: "+e);var t=this.examples[e].label;delete this.examples[e];var r=this.label2Ids[t].indexOf(e);this.label2Ids[t].splice(r,1),0===this.label2Ids[t].length&&delete this.label2Ids[t]},e.prototype.setExampleKeyFrameIndex=function(e,t){if(!(e in this.examples))throw new Error("Nonexistent example UID: "+e);var r=this.examples[e].spectrogram,n=r.data.length/r.frameSize;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t>=0&&t<n&&Number.isInteger(t),function(){return"Invalid keyFrameIndex: "+t+". Must be >= 0, < "+n+", and an integer."}),r.keyFrameIndex=t},e.prototype.size=function(){return Object.keys(this.examples).length},e.prototype.durationMillis=function(){var e=0;for(var t in this.examples){var r=this.examples[t].spectrogram,n=23.22|r.frameDurationMillis;e+=r.data.length/r.frameSize*n}return e},e.prototype.empty=function(){return 0===this.size()},e.prototype.clear=function(){this.examples={}},e.prototype.getVocabulary=function(){var e=new Set;for(var t in this.examples){var r=this.examples[t];e.add(r.label)}var n=__spread(e);return n.sort(),n},e.prototype.serialize=function(e){var t,r,n,a,i=this.getVocabulary();_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(!this.empty(),function(){return"Cannot serialize empty Dataset"}),null!=e&&(Array.isArray(e)||(e=[e]),e.forEach(function(e){if(-1===i.indexOf(e))throw new Error('Word label "'+e+'" does not exist in the vocabulary of this dataset. The vocabulary is: '+JSON.stringify(i)+".")}));var o=[],s=[];try{for(var l=__values(i),u=l.next();!u.done;u=l.next()){var c=u.value;if(null==e||-1!==e.indexOf(c)){var h=this.label2Ids[c];try{for(var d=__values(h),p=d.next();!p.done;p=d.next()){var f=p.value,m=serializeExample(this.examples[f]);o.push(m.spec),s.push(m.data)}}catch(e){n={error:e}}finally{try{p&&!p.done&&(a=d.return)&&a.call(d)}finally{if(n)throw n.error}}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=l.return)&&r.call(l)}finally{if(t)throw t.error}}return serializedExamples2ArrayBuffer({manifest:o,data:concatenateArrayBuffers(s)})},e}();function serializeExample(e){var t=null!=e.rawAudio,r={label:e.label,spectrogramNumFrames:e.spectrogram.data.length/e.spectrogram.frameSize,spectrogramFrameSize:e.spectrogram.frameSize};null!=e.spectrogram.keyFrameIndex&&(r.spectrogramKeyFrameIndex=e.spectrogram.keyFrameIndex);var n=e.spectrogram.data.buffer.slice(0);return t&&(r.rawAudioNumSamples=e.rawAudio.data.length,r.rawAudioSampleRateHz=e.rawAudio.sampleRateHz,n=concatenateArrayBuffers([n,e.rawAudio.data.buffer])),{spec:r,data:n}}function deserializeExample(e){var t={frameSize:e.spec.spectrogramFrameSize,data:new Float32Array(e.data.slice(0,4*e.spec.spectrogramFrameSize*e.spec.spectrogramNumFrames))};null!=e.spec.spectrogramKeyFrameIndex&&(t.keyFrameIndex=e.spec.spectrogramKeyFrameIndex);var r={label:e.spec.label,spectrogram:t};return null!=e.spec.rawAudioNumSamples&&(r.rawAudio={sampleRateHz:e.spec.rawAudioSampleRateHz,data:new Float32Array(e.data.slice(4*e.spec.spectrogramFrameSize*e.spec.spectrogramNumFrames))}),r}function serializedExamples2ArrayBuffer(e){var t=string2ArrayBuffer(JSON.stringify(e.manifest)),r=string2ArrayBuffer(DATASET_SERIALIZATION_DESCRIPTOR),n=new Uint32Array([DATASET_SERIALIZATION_VERSION]),a=new Uint32Array([t.byteLength]);return concatenateArrayBuffers([concatenateArrayBuffers([r,n.buffer,a.buffer]),t,e.data])}function arrayBuffer2SerializedExamples(e){_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e,function(){return"Received null or undefined buffer"});var t=0,r=arrayBuffer2String(e.slice(t,DATASET_SERIALIZATION_DESCRIPTOR.length));_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r===DATASET_SERIALIZATION_DESCRIPTOR,function(){return"Deserialization error: Invalid descriptor"}),t+=DATASET_SERIALIZATION_DESCRIPTOR.length,t+=4;var n=new Uint32Array(e,t,1),a=t+=4;t=a+n[0];var i=arrayBuffer2String(e.slice(a,t));return{manifest:JSON.parse(i),data:e.slice(t)}}function getValidWindows(e,t,r,n){if(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(Number.isInteger(e)&&e>0,function(){return"snippetLength must be a positive integer, but got "+e}),null!=t&&_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(Number.isInteger(t)&&t>=0,function(){return"focusIndex must be a non-negative integer, but got "+t}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(Number.isInteger(r)&&r>0,function(){return"windowLength must be a positive integer, but got "+r}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(Number.isInteger(n)&&n>0,function(){return"windowHop must be a positive integer, but got "+n}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r<=e,function(){return"windowLength ("+r+") exceeds snippetLength ("+e+")"}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t<e,function(){return"focusIndex ("+t+") equals or exceeds snippetLength ("+e+")"}),r===e)return[[0,e]];var a=[];if(null==t){for(var i=0;i+r<=e;)a.push([i,i+r]),i+=n;return a}var o=Math.floor(r/2),s=t-o;for(s<0?s=0:s+r>e&&(s=e-r);!(s-n<0||t>=s-n+r);)s-=n;for(;s+r<=e&&!(t<s);)a.push([s,s+r]),s+=n;return a}function spectrogram2IntensityCurve(e){return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){var t=e.data.length/e.frameSize;return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor2d"])(e.data,[t,e.frameSize]).mean(-1)})}function getMaxIntensityFrameIndex(e){return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){return spectrogram2IntensityCurve(e).argMax()})}var version="0.3.9",UNKNOWN_TAG="_unknown_",SAVED_MODEL_METADATA_KEY="tfjs-speech-commands-saved-model-metadata",SAVE_PATH_PREFIX="indexeddb://tfjs-speech-commands-model/",localStorageWrapper={localStorage:"undefined"==typeof window?null:window.localStorage};function getMajorAndMinorVersion(e){return e.split(".").slice(0,2).join(".")}var DEFAULT_WINDOW_HOP_RATIO=.25,BrowserFftSpeechCommandRecognizer=function(){function e(t,r,n){this.MODEL_URL_PREFIX="https://storage.googleapis.com/tfjs-models/tfjs/speech-commands/v"+getMajorAndMinorVersion(version)+"/browser_fft",this.SAMPLE_RATE_HZ=44100,this.FFT_SIZE=1024,this.DEFAULT_SUPPRESSION_TIME_MILLIS=0,this.streaming=!1,this.transferRecognizers={},_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null==r&&null==n||null!=r&&null!=n,function(){return"modelURL and metadataURL must be both provided or both not provided."}),null==r?(null==t?t=e.DEFAULT_VOCABULARY_NAME:_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(-1!==e.VALID_VOCABULARY_NAMES.indexOf(t),function(){return"Invalid vocabulary name: '"+t+"'"}),this.vocabulary=t,this.modelArtifactsOrURL=this.MODEL_URL_PREFIX+"/"+this.vocabulary+"/model.json",this.metadataOrURL=this.MODEL_URL_PREFIX+"/"+this.vocabulary+"/metadata.json"):(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null==t,function(){return"vocabulary name must be null or undefined when modelURL is provided"}),this.modelArtifactsOrURL=r,this.metadataOrURL=n),this.parameters={sampleRateHz:this.SAMPLE_RATE_HZ,fftSize:this.FFT_SIZE}}return e.prototype.listen=function(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a,i,o,s=this;return __generator(this,function(l){switch(l.label){case 0:if(this.streaming)throw new Error("Cannot start streaming again when streaming is ongoing.");return[4,this.ensureModelLoaded()];case 1:if(l.sent(),null==t&&(t={}),r=null==t.probabilityThreshold?0:t.probabilityThreshold,t.includeEmbedding&&(r=0),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(r>=0&&r<=1,function(){return"Invalid probabilityThreshold value: "+r}),n=null!=t.invokeCallbackOnNoiseAndUnknown&&t.invokeCallbackOnNoiseAndUnknown,t.includeEmbedding&&(n=!0),t.suppressionTimeMillis<0)throw new Error("suppressionTimeMillis is expected to be >= 0, but got "+t.suppressionTimeMillis);return a=null==t.overlapFactor?.5:t.overlapFactor,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(a>=0&&a<1,function(){return"Expected overlapFactor to be >= 0 and < 1, but got "+a}),i=function(a,i){return __awaiter(s,void 0,void 0,function(){var i,o,s,l,u,c,h,d,p,f,m;return __generator(this,function(g){switch(g.label){case 0:return o=normalize(a),t.includeEmbedding?[4,this.ensureModelWithEmbeddingOutputCreated()]:[3,2];case 1:return g.sent(),i=__read(this.modelWithEmbeddingOutput.predict(o),2),s=i[0],l=i[1],[3,3];case 2:s=this.model.predict(o),g.label=3;case 3:return[4,s.data()];case 4:return u=g.sent(),[4,(c=s.argMax(-1)).data()];case 5:return h=g.sent()[0],d=Math.max.apply(Math,__spread(u)),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["dispose"])([s,c,o]),d<r?[2,!1]:[3,6];case 6:return p=void 0,t.includeSpectrogram?(f={},[4,a.data()]):[3,8];case 7:f.data=g.sent(),f.frameSize=this.nonBatchInputShape[1],p=f,g.label=8;case 8:return m=!0,n||this.words[h]!==BACKGROUND_NOISE_TAG&&this.words[h]!==UNKNOWN_TAG||(m=!1),m&&e({scores:u,spectrogram:p,embedding:l}),[2,m]}})})},o=null==t.suppressionTimeMillis?this.DEFAULT_SUPPRESSION_TIME_MILLIS:t.suppressionTimeMillis,this.audioDataExtractor=new BrowserFftFeatureExtractor({sampleRateHz:this.parameters.sampleRateHz,numFramesPerSpectrogram:this.nonBatchInputShape[0],columnTruncateLength:this.nonBatchInputShape[1],suppressionTimeMillis:o,spectrogramCallback:i,overlapFactor:a}),[4,this.audioDataExtractor.start(t.audioTrackConstraints)];case 2:return l.sent(),this.streaming=!0,[2]}})})},e.prototype.ensureModelLoaded=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r,n,a=this;return __generator(this,function(i){switch(i.label){case 0:return null!=this.model?[2]:[4,this.ensureMetadataLoaded()];case 1:return i.sent(),"string"!=typeof this.modelArtifactsOrURL?[3,3]:[4,Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["loadLayersModel"])(this.modelArtifactsOrURL)];case 2:return e=i.sent(),[3,5];case 3:return[4,Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["loadLayersModel"])(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["io"].fromMemory(this.modelArtifactsOrURL.modelTopology,this.modelArtifactsOrURL.weightSpecs,this.modelArtifactsOrURL.weightData))];case 4:e=i.sent(),i.label=5;case 5:if(1!==e.inputs.length)throw new Error("Expected model to have 1 input, but got a model with "+e.inputs.length+" inputs");if(4!==e.inputs[0].shape.length)throw new Error("Expected model to have an input shape of rank 4, but got an input shape of rank "+e.inputs[0].shape.length);if(1!==e.inputs[0].shape[3])throw new Error("Expected model to have an input shape with 1 as the last dimension, but got input shape"+JSON.stringify(e.inputs[0].shape[3])+"}");if(2!==(t=e.outputShape).length)throw new Error("Expected loaded model to have an output shape of rank 2,but received shape "+JSON.stringify(t));if(t[1]!==this.words.length)throw new Error("Mismatch between the last dimension of model's output shape ("+t[1]+") and number of words ("+this.words.length+").");return this.model=e,this.freezeModel(),this.nonBatchInputShape=e.inputs[0].shape.slice(1),this.elementsPerExample=1,e.inputs[0].shape.slice(1).forEach(function(e){return a.elementsPerExample*=e}),this.warmUpModel(),r=this.parameters.fftSize/this.parameters.sampleRateHz*1e3,n=e.inputs[0].shape[1],this.parameters.spectrogramDurationMillis=n*r,[2]}})})},e.prototype.ensureModelWithEmbeddingOutputCreated=function(){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(r){switch(r.label){case 0:return null!=this.modelWithEmbeddingOutput?[2]:[4,this.ensureModelLoaded()];case 1:for(r.sent(),t=this.model.layers.length-2;t>=0;--t)if("Dense"===this.model.layers[t].getClassName()){e=this.model.layers[t];break}if(null==e)throw new Error("Failed to find second last dense layer in the original model.");return this.modelWithEmbeddingOutput=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["model"])({inputs:this.model.inputs,outputs:[this.model.outputs[0],e.output]}),[2]}})})},e.prototype.warmUpModel=function(){var e=this;Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){for(var t=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["zeros"])([1].concat(e.nonBatchInputShape)),r=0;r<3;++r)e.model.predict(t)})},e.prototype.ensureMetadataLoaded=function(){return __awaiter(this,void 0,void 0,function(){var e,t,r;return __generator(this,function(n){switch(n.label){case 0:return null!=this.words?[2]:"string"!=typeof this.metadataOrURL?[3,2]:[4,loadMetadataJson(this.metadataOrURL)];case 1:return t=n.sent(),[3,3];case 2:t=this.metadataOrURL,n.label=3;case 3:if(null==(e=t).wordLabels){if(null==(r=e.words))throw new Error('Cannot find field "words" or "wordLabels" in metadata JSON file');this.words=r}else this.words=e.wordLabels;return[2]}})})},e.prototype.stopListening=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){switch(e.label){case 0:if(!this.streaming)throw new Error("Cannot stop streaming when streaming is not ongoing.");return[4,this.audioDataExtractor.stop()];case 1:return e.sent(),this.streaming=!1,[2]}})})},e.prototype.isListening=function(){return this.streaming},e.prototype.wordLabels=function(){return this.words},e.prototype.params=function(){return this.parameters},e.prototype.modelInputShape=function(){if(null==this.model)throw new Error("Model has not been loaded yet. Load model by calling ensureModelLoaded(), recognize(), or listen().");return this.model.inputs[0].shape},e.prototype.recognize=function(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a,i,o,s,l,u,c,h,d,p,f;return __generator(this,function(m){switch(m.label){case 0:return null==t&&(t={}),[4,this.ensureModelLoaded()];case 1:return m.sent(),null!=e?[3,3]:[4,this.recognizeOnline()];case 2:r=m.sent(),e=r.data,m.label=3;case 3:if(e instanceof _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["Tensor"])this.checkInputTensorShape(e),a=e,n=e.shape[0];else{if((e=e).length%this.elementsPerExample)throw new Error("The length of the input Float32Array "+e.length+" is not divisible by the number of tensor elements per per example expected by the model "+this.elementsPerExample+".");n=e.length/this.elementsPerExample,a=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tensor4d"])(e,[n].concat(this.nonBatchInputShape))}return o={scores:null},t.includeEmbedding?[4,this.ensureModelWithEmbeddingOutputCreated()]:[3,5];case 4:return m.sent(),s=this.modelWithEmbeddingOutput.predict(a),i=s[0],o.embedding=s[1],[3,6];case 5:i=this.model.predict(a),m.label=6;case 6:return 1!==n?[3,8]:(l=o,[4,i.data()]);case 7:return l.scores=m.sent(),[3,10];case 8:return u=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["unstack"])(i),c=u.map(function(e){return e.data()}),h=o,[4,Promise.all(c)];case 9:h.scores=m.sent(),Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["dispose"])(u),m.label=10;case 10:return t.includeSpectrogram?(d=o,p={},e instanceof _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["Tensor"]?[4,e.data()]:[3,12]):[3,14];case 11:return f=m.sent(),[3,13];case 12:f=e,m.label=13;case 13:d.spectrogram=(p.data=f,p.frameSize=this.nonBatchInputShape[1],p),m.label=14;case 14:return[2,o]}})})},e.prototype.recognizeOnline=function(){return __awaiter(this,void 0,void 0,function(){var e=this;return __generator(this,function(t){return[2,new Promise(function(t,r){e.audioDataExtractor=new BrowserFftFeatureExtractor({sampleRateHz:e.parameters.sampleRateHz,numFramesPerSpectrogram:e.nonBatchInputShape[0],columnTruncateLength:e.nonBatchInputShape[1],suppressionTimeMillis:0,spectrogramCallback:function(r){return __awaiter(e,void 0,void 0,function(){var e,n,a;return __generator(this,function(i){switch(i.label){case 0:return e=normalize(r),[4,this.audioDataExtractor.stop()];case 1:return i.sent(),n=t,a={},[4,e.data()];case 2:return n.apply(void 0,[(a.data=i.sent(),a.frameSize=this.nonBatchInputShape[1],a)]),e.dispose(),[2,!1]}})})},overlapFactor:0}),e.audioDataExtractor.start()})]})})},e.prototype.createTransfer=function(e){if(null==this.model)throw new Error("Model has not been loaded yet. Load model by calling ensureModelLoaded(), recognizer(), or listen().");_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e&&"string"==typeof e&&e.length>1,function(){return"Expected the name for a transfer-learning recognized to be a non-empty string, but got "+JSON.stringify(e)}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null==this.transferRecognizers[e],function(){return"There is already a transfer-learning model named '"+e+"'"});var t=new TransferBrowserFftSpeechCommandRecognizer(e,this.parameters,this.model);return this.transferRecognizers[e]=t,t},e.prototype.freezeModel=function(){var e,t;try{for(var r=__values(this.model.layers),n=r.next();!n.done;n=r.next()){n.value.trainable=!1}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.checkInputTensorShape=function(e){var t=this.model.inputs[0].shape.length;if(e.shape.length!==t)throw new Error("Expected input Tensor to have rank "+t+", but got rank "+e.shape.length+" that differs ");var r=e.shape.slice(1),n=this.model.inputs[0].shape.slice(1);if(!_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].arraysEqual(r,n))throw new Error("Expected input to have shape [null,"+n+"], but got shape [null,"+r+"]")},e.VALID_VOCABULARY_NAMES=["18w","directional4w"],e.DEFAULT_VOCABULARY_NAME="18w",e}(),TransferBrowserFftSpeechCommandRecognizer=function(e){function t(t,r,n){var a=e.call(this)||this;return a.name=t,a.parameters=r,a.baseModel=n,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=t&&"string"==typeof t&&t.length>0,function(){return"The name of a transfer model must be a non-empty string, but got "+JSON.stringify(t)}),a.nonBatchInputShape=a.baseModel.inputs[0].shape.slice(1),a.words=null,a.dataset=new Dataset,a}return __extends(t,e),t.prototype.collectExample=function(e,t){return __awaiter(this,void 0,void 0,function(){var r,n,a,i,o=this;return __generator(this,function(s){if(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(!this.streaming,function(){return"Cannot start collection of transfer-learning example because a streaming recognition or transfer-learning example collection is ongoing"}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e&&"string"==typeof e&&e.length>0,function(){return"Must provide a non-empty string when collecting transfer-learning example"}),null==t&&(t={}),null!=t.durationMultiplier&&null!=t.durationSec)throw new Error("durationMultiplier and durationSec are mutually exclusive, but are both specified.");return null!=t.durationSec?(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t.durationSec>0,function(){return"Expected durationSec to be > 0, but got "+t.durationSec}),n=this.parameters.fftSize/this.parameters.sampleRateHz,r=Math.ceil(t.durationSec/n)):null!=t.durationMultiplier?(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t.durationMultiplier>=1,function(){return"Expected duration multiplier to be >= 1, but got "+t.durationMultiplier}),r=Math.round(this.nonBatchInputShape[0]*t.durationMultiplier)):r=this.nonBatchInputShape[0],null!=t.snippetDurationSec&&(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(t.snippetDurationSec>0,function(){return"snippetDurationSec is expected to be > 0, but got "+t.snippetDurationSec}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=t.onSnippet,function(){return"onSnippet must be provided if snippetDurationSec is provided."})),null!=t.onSnippet&&_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=t.snippetDurationSec,function(){return"snippetDurationSec must be provided if onSnippet is provided."}),a=this.parameters.fftSize/this.parameters.sampleRateHz,i=a*r,this.streaming=!0,[2,new Promise(function(n){var a=null==t.snippetDurationSec?1:t.snippetDurationSec/i,s=1-a,l=Math.round(1/a),u=0,c=-1,h=[];o.audioDataExtractor=new BrowserFftFeatureExtractor({sampleRateHz:o.parameters.sampleRateHz,numFramesPerSpectrogram:r,columnTruncateLength:o.nonBatchInputShape[1],suppressionTimeMillis:0,spectrogramCallback:function(r,a){return __awaiter(o,void 0,void 0,function(){var i,o,s,d,p,f,m,g,v,y,w,b,_,S,x,E,A,T,I,D;return __generator(this,function(F){switch(F.label){case 0:return null!=t.onSnippet?[3,7]:(i=normalize(r),s=(o=this.dataset).addExample,d={label:e},p={},[4,i.data()]);case 1:return d.spectrogram=(p.data=F.sent(),p.frameSize=this.nonBatchInputShape[1],p),t.includeRawAudio?(m={},[4,a.data()]):[3,3];case 2:return m.data=F.sent(),m.sampleRateHz=this.audioDataExtractor.sampleRateHz,f=m,[3,4];case 3:f=void 0,F.label=4;case 4:return s.apply(o,[(d.rawAudio=f,d)]),i.dispose(),[4,this.audioDataExtractor.stop()];case 5:return F.sent(),this.streaming=!1,this.collateTransferWords(),g=n,v={},[4,r.data()];case 6:return g.apply(void 0,[(v.data=F.sent(),v.frameSize=this.nonBatchInputShape[1],v)]),[3,13];case 7:return[4,r.data()];case 8:for(y=F.sent(),-1===c&&(c=y.length),w=c-1;0!==y[w]&&w>=0;)w--;return b=c-w-1,c=w+1,_=y.slice(y.length-b,y.length),h.push(_),null!=t.onSnippet&&t.onSnippet({data:_,frameSize:this.nonBatchInputShape[1]}),u++!==l?[3,13]:[4,this.audioDataExtractor.stop()];case 9:return F.sent(),this.streaming=!1,this.collateTransferWords(),S=normalizeFloat32Array(concatenateFloat32Arrays(h)),x={data:S,frameSize:this.nonBatchInputShape[1]},A=(E=this.dataset).addExample,T={label:e,spectrogram:x},t.includeRawAudio?(D={},[4,a.data()]):[3,11];case 10:return D.data=F.sent(),D.sampleRateHz=this.audioDataExtractor.sampleRateHz,I=D,[3,12];case 11:I=void 0,F.label=12;case 12:A.apply(E,[(T.rawAudio=I,T)]),n(x),F.label=13;case 13:return[2,!1]}})})},overlapFactor:s,includeRawAudio:t.includeRawAudio}),o.audioDataExtractor.start(t.audioTrackConstraints)})]})})},t.prototype.clearExamples=function(){var e=this;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=this.words&&this.words.length>0&&!this.dataset.empty(),function(){return"No transfer learning examples exist for model name "+e.name}),this.dataset.clear(),this.words=null},t.prototype.countExamples=function(){if(this.dataset.empty())throw new Error("No examples have been collected for transfer-learning model named '"+this.name+"' yet.");return this.dataset.getExampleCounts()},t.prototype.getExamples=function(e){return this.dataset.getExamples(e)},t.prototype.setExampleKeyFrameIndex=function(e,t){this.dataset.setExampleKeyFrameIndex(e,t)},t.prototype.removeExample=function(e){this.dataset.removeExample(e),this.collateTransferWords()},t.prototype.isDatasetEmpty=function(){return this.dataset.empty()},t.prototype.loadExamples=function(e,t){var r,n,a,i;void 0===t&&(t=!1);var o=new Dataset(e);t&&this.clearExamples();var s=o.getVocabulary();try{for(var l=__values(s),u=l.next();!u.done;u=l.next()){var c=u.value,h=o.getExamples(c);try{for(var d=__values(h),p=d.next();!p.done;p=d.next()){var f=p.value;this.dataset.addExample(f.example)}}catch(e){a={error:e}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(a)throw a.error}}}}catch(e){r={error:e}}finally{try{u&&!u.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}this.collateTransferWords()},t.prototype.serializeExamples=function(e){return this.dataset.serialize(e)},t.prototype.collateTransferWords=function(){this.words=this.dataset.getVocabulary()},t.prototype.collectTransferDataAsTensors=function(e,t){var r=this.nonBatchInputShape[0];e=e||DEFAULT_WINDOW_HOP_RATIO;var n=Math.round(e*r),a=this.dataset.getData(null,__assign({numFrames:r,hopFrames:n},t));return{xs:a.xs,ys:a.ys}},t.prototype.collectTransferDataAsTfDataset=function(e,t,r,n){void 0===t&&(t=.15),void 0===r&&(r=32);var a=this.nonBatchInputShape[0];e=e||DEFAULT_WINDOW_HOP_RATIO;var i=Math.round(e*a);return this.dataset.getData(null,__assign({numFrames:a,hopFrames:i,getDataset:!0,datasetBatchSize:r,datasetValidationSplit:t},n))},t.prototype.train=function(e){return __awaiter(this,void 0,void 0,function(){var t,r=this;return __generator(this,function(n){switch(n.label){case 0:return _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=this.words&&this.words.length>0,function(){return"Cannot train transfer-learning model '"+r.name+"' because no transfer learning example has been collected."}),_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(this.words.length>1,function(){return"Cannot train transfer-learning model '"+r.name+"' because only 1 word label ('"+JSON.stringify(r.words)+"') has been collected for transfer learning. Requires at least 2."}),null!=e.fineTuningEpochs&&_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(e.fineTuningEpochs>=0&&Number.isInteger(e.fineTuningEpochs),function(){return"If specified, fineTuningEpochs must be a non-negative integer, but received "+e.fineTuningEpochs}),null==e&&(e={}),null==this.model&&this.createTransferModelFromBaseModel(),this.secondLastBaseDenseLayer.trainable=!1,this.model.compile({loss:"categoricalCrossentropy",optimizer:e.optimizer||"sgd",metrics:["acc"]}),t=null==e.fitDatasetDurationMillisThreshold?6e4:e.fitDatasetDurationMillisThreshold,this.dataset.durationMillis()>t?(console.log("Detected large dataset: total duration = "+this.dataset.durationMillis()+" ms > "+t+" ms. Training transfer model using fitDataset() instead of fit()"),[4,this.trainOnDataset(e)]):[3,2];case 1:return[2,n.sent()];case 2:return[4,this.trainOnTensors(e)];case 3:return[2,n.sent()]}})})},t.prototype.trainOnDataset=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a,i,o,s,l,u;return __generator(this,function(c){switch(c.label){case 0:return _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(e.epochs>0,function(){return"Invalid config.epochs"}),t=null==e.batchSize?32:e.batchSize,r=e.windowHopRatio||DEFAULT_WINDOW_HOP_RATIO,n=__read(this.collectTransferDataAsTfDataset(r,e.validationSplit,t,{augmentByMixingNoiseRatio:e.augmentByMixingNoiseRatio}),2),a=n[0],i=n[1],o=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].now(),[4,this.model.fitDataset(a,{epochs:e.epochs,validationData:e.validationSplit>0?i:null,callbacks:null==e.callback?null:[e.callback]})];case 1:return s=c.sent(),console.log("fitDataset() took "+(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].now()-o).toFixed(2)+" ms"),null!=e.fineTuningEpochs&&e.fineTuningEpochs>0?(l=_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].now(),[4,this.fineTuningUsingTfDatasets(e,a,i)]):[3,3];case 2:return u=c.sent(),console.log("fitDataset() (fine-tuning) took "+(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].now()-l).toFixed(2)+" ms"),[2,[s,u]];case 3:return[2,s]}})})},t.prototype.trainOnTensors=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n,a,i,o,s,l,u,c;return __generator(this,function(h){switch(h.label){case 0:t=e.windowHopRatio||DEFAULT_WINDOW_HOP_RATIO,r=this.collectTransferDataAsTensors(t,{augmentByMixingNoiseRatio:e.augmentByMixingNoiseRatio}),n=r.xs,a=r.ys,console.log("Training data: xs.shape = "+n.shape+", ys.shape = "+a.shape),h.label=1;case 1:return h.trys.push([1,,6,7]),null!=e.validationSplit?(l=balancedTrainValSplit(n,a,e.validationSplit),i=l.trainXs,o=l.trainYs,s=[l.valXs,l.valYs]):(i=n,o=a),[4,this.model.fit(i,o,{epochs:null==e.epochs?20:e.epochs,validationData:s,batchSize:e.batchSize,callbacks:null==e.callback?null:[e.callback]})];case 2:return u=h.sent(),null!=e.fineTuningEpochs&&e.fineTuningEpochs>0?[4,this.fineTuningUsingTensors(e,i,o,s)]:[3,4];case 3:return c=h.sent(),[2,[u,c]];case 4:return[2,u];case 5:return[3,7];case 6:return Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["dispose"])([n,a,i,o,s]),[7];case 7:return[2]}})})},t.prototype.fineTuningUsingTfDatasets=function(e,t,r){return __awaiter(this,void 0,void 0,function(){var n,a,i;return __generator(this,function(o){switch(o.label){case 0:return n=this.secondLastBaseDenseLayer.trainable,this.secondLastBaseDenseLayer.trainable=!0,a=null==e.fineTuningOptimizer?"sgd":e.fineTuningOptimizer,this.model.compile({loss:"categoricalCrossentropy",optimizer:a,metrics:["acc"]}),[4,this.model.fitDataset(t,{epochs:e.fineTuningEpochs,validationData:r,callbacks:null==e.callback?null:[e.callback]})];case 1:return i=o.sent(),this.secondLastBaseDenseLayer.trainable=n,[2,i]}})})},t.prototype.fineTuningUsingTensors=function(e,t,r,n){return __awaiter(this,void 0,void 0,function(){var a,i,o;return __generator(this,function(s){switch(s.label){case 0:return a=this.secondLastBaseDenseLayer.trainable,this.secondLastBaseDenseLayer.trainable=!0,i=null==e.fineTuningOptimizer?"sgd":e.fineTuningOptimizer,this.model.compile({loss:"categoricalCrossentropy",optimizer:i,metrics:["acc"]}),[4,this.model.fit(t,r,{epochs:e.fineTuningEpochs,validationData:n,batchSize:e.batchSize,callbacks:null==e.fineTuningCallback?null:[e.fineTuningCallback]})];case 1:return o=s.sent(),this.secondLastBaseDenseLayer.trainable=a,[2,o]}})})},t.prototype.evaluate=function(e){return __awaiter(this,void 0,void 0,function(){var t,r=this;return __generator(this,function(n){return _tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=e.wordProbThresholds&&e.wordProbThresholds.length>0,function(){return"Received null or empty wordProbThresholds"}),t=0,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(this.words[t]===BACKGROUND_NOISE_TAG,function(){return"Cannot perform evaluation when the first tag is not "+BACKGROUND_NOISE_TAG}),[2,Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["tidy"])(function(){for(var n=[],a=0,i=r.collectTransferDataAsTensors(e.windowHopRatio),o=i.xs,s=i.ys.argMax(-1).dataSync(),l=r.model.predict(o),u=l.slice([0,1],[l.shape[0],l.shape[1]-1]).max(-1),c=l.shape[0],h=0;h<e.wordProbThresholds.length;++h){for(var d=e.wordProbThresholds[h],p=u.greater(Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["scalar"])(d)).dataSync(),f=0,m=0,g=0,v=0,y=0;y<c;++y)s[y]===t?(f++,p[y]&&g++):(m++,p[y]&&v++);var w=g/f,b=v/m;n.push({probThreshold:d,fpr:w,tpr:b}),console.log("ROC thresh="+d+": fpr="+w.toFixed(4)+", tpr="+b.toFixed(4)),h>0&&(a+=Math.abs(n[h-1].fpr-n[h].fpr)*(n[h-1].tpr+n[h].tpr)/2)}return{rocCurve:n,auc:a}})]})})},t.prototype.createTransferModelFromBaseModel=function(){var e=this;_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null!=this.words,function(){return"No word example is available for tranfer-learning model of name "+e.name});for(var t=this.baseModel.layers,r=t.length-2;r>=0&&"dense"!==t[r].getClassName().toLowerCase();)r--;if(r<0)throw new Error("Cannot find a hidden dense layer in the base model.");this.secondLastBaseDenseLayer=t[r];var n=this.secondLastBaseDenseLayer.output;this.transferHead=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["sequential"])(),this.transferHead.add(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["layers"].dense({units:this.words.length,activation:"softmax",inputShape:n.shape.slice(1),name:"NewHeadDense"}));var a=this.transferHead.apply(n);this.model=Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["model"])({inputs:this.baseModel.inputs,outputs:a})},t.prototype.modelInputShape=function(){return this.baseModel.inputs[0].shape},t.prototype.getMetadata=function(){return{tfjsSpeechCommandsVersion:version,modelName:this.name,timeStamp:(new Date).toISOString(),wordLabels:this.wordLabels()}},t.prototype.save=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n;return __generator(this,function(a){return t=null!=e,e=e||getCanonicalSavePath(this.name),t||(r=localStorageWrapper.localStorage.getItem(SAVED_MODEL_METADATA_KEY),(n=null==r?{}:JSON.parse(r))[this.name]=this.getMetadata(),localStorageWrapper.localStorage.setItem(SAVED_MODEL_METADATA_KEY,JSON.stringify(n))),console.log("Saving model to "+e),[2,this.model.save(e)]})})},t.prototype.load=function(e){return __awaiter(this,void 0,void 0,function(){var t,r,n;return __generator(this,function(a){switch(a.label){case 0:if(t=null!=e,e=e||getCanonicalSavePath(this.name),!t){if(null==(r=JSON.parse(localStorageWrapper.localStorage.getItem(SAVED_MODEL_METADATA_KEY)))||null==r[this.name])throw new Error("Cannot find metadata for transfer model named "+this.name+'"');this.words=r[this.name].wordLabels,console.log("Loaded word list for model named "+this.name+": "+this.words)}return n=this,[4,Object(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["loadLayersModel"])(e)];case 1:return n.model=a.sent(),console.log("Loaded model from "+e+":"),this.model.summary(),[2]}})})},t.prototype.createTransfer=function(e){throw new Error("Creating transfer-learned recognizer from a transfer-learned recognizer is not supported.")},t}(BrowserFftSpeechCommandRecognizer);function getCanonicalSavePath(e){return""+SAVE_PATH_PREFIX+e}function listSavedTransferModels(){return __awaiter(this,void 0,void 0,function(){var e,t,r;return __generator(this,function(n){switch(n.label){case 0:return[4,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["io"].listModels()];case 1:for(r in e=n.sent(),t=[],e)r.startsWith(SAVE_PATH_PREFIX)&&t.push(r.slice(SAVE_PATH_PREFIX.length));return[2,t]}})})}function deleteSavedTransferModel(e){return __awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(r){switch(r.label){case 0:return null==(t=JSON.parse(localStorageWrapper.localStorage.getItem(SAVED_MODEL_METADATA_KEY)))&&(t={}),null!=t[e]&&delete t[e],localStorageWrapper.localStorage.setItem(SAVED_MODEL_METADATA_KEY,JSON.stringify(t)),[4,_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["io"].removeModel(getCanonicalSavePath(e))];case 1:return r.sent(),[2]}})})}function create(e,t,r,n){if(_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null==r&&null==n||null!=r&&null!=n,function(){return"customModelURL and customMetadataURL must be both provided or both not provided."}),null!=r&&_tensorflow_tfjs__WEBPACK_IMPORTED_MODULE_0__["util"].assert(null==t,function(){return"vocabulary name must be null or undefined when modelURL is provided."}),"BROWSER_FFT"===e)return new BrowserFftSpeechCommandRecognizer(t,r,n);throw"SOFT_FFT"===e?new Error("SOFT_FFT SpeechCommandRecognizer has not been implemented yet."):new Error("Invalid fftType: '"+e+"'")}var utils={concatenateFloat32Arrays:concatenateFloat32Arrays,playRawAudio:playRawAudio};
//# sourceMappingURL=speech-commands.esm.js.map
/***/ }),
/* 370 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.load = exports.SpeechCommands = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var load = exports.load = function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(options, url) {
var speechCommandsModel;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
speechCommandsModel = new SpeechCommands(options);
_context2.next = 3;
return speechCommandsModel.load(url);
case 3:
return _context2.abrupt('return', speechCommandsModel);
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function load(_x3, _x4) {
return _ref2.apply(this, arguments);
};
}();
var _speechCommands = __webpack_require__(369);
var tfjsSpeechCommands = _interopRequireWildcard(_speechCommands);
var _gettopkclasses = __webpack_require__(144);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var SpeechCommands = exports.SpeechCommands = function () {
function SpeechCommands(options) {
(0, _classCallCheck3.default)(this, SpeechCommands);
this.options = options;
}
(0, _createClass3.default)(SpeechCommands, [{
key: 'load',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(url) {
var split, prefix, metadataJson;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (url) {
split = url.split("/");
prefix = split.slice(0, split.length - 1).join("/");
metadataJson = prefix + '/metadata.json';
this.model = tfjsSpeechCommands.create('BROWSER_FFT', undefined, url, metadataJson);
} else this.model = tfjsSpeechCommands.create('BROWSER_FFT');
_context.next = 3;
return this.model.ensureModelLoaded();
case 3:
this.allLabels = this.model.wordLabels();
case 4:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function load(_x) {
return _ref.apply(this, arguments);
}
return load;
}()
}, {
key: 'classify',
value: function classify() {
var _this = this;
var topk = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.allLabels.length;
var cb = arguments[1];
return this.model.listen(function (result) {
if (result.scores) {
var classes = (0, _gettopkclasses.getTopKClassesFromArray)(result.scores, topk, _this.allLabels).map(function (c) {
return { label: c.className, confidence: c.probability };
});
return cb(null, classes);
}
return cb('ERROR: Cannot find scores in result: ' + result);
}, this.options).catch(function (err) {
return cb('ERROR: ' + err.message);
});
}
}]);
return SpeechCommands;
}();
/***/ }),
/* 371 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _speechcommands = __webpack_require__(370);
var speechCommands = _interopRequireWildcard(_speechcommands);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MODEL_OPTIONS = ['speechcommands18w']; // Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
Sound Classifier using pre-trained networks
*/
var SoundClassifier = function () {
/**
* Create an SoundClassifier.
* @param {modelNameOrUrl} modelNameOrUrl - The name or the URL of the model to use. Current name options
* are: 'SpeechCommands18w'.
* @param {object} options - An object with options.
* @param {function} callback - A callback to be called when the model is ready.
*/
function SoundClassifier(modelNameOrUrl, options, callback) {
(0, _classCallCheck3.default)(this, SoundClassifier);
this.model = null;
this.options = options;
if (typeof modelNameOrUrl === 'string') {
if (MODEL_OPTIONS.includes(modelNameOrUrl)) {
this.modelName = modelNameOrUrl;
this.modelUrl = null;
switch (this.modelName) {
case 'speechcommands18w':
this.modelToUse = speechCommands;
break;
default:
this.modelToUse = null;
}
} else {
// Default to speechCommands for now
this.modelToUse = speechCommands;
this.modelUrl = modelNameOrUrl;
}
}
// Load the model
this.ready = (0, _callcallback2.default)(this.loadModel(options, this.modelUrl), callback);
}
(0, _createClass3.default)(SoundClassifier, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(options) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.modelToUse.load(options, this.modelUrl);
case 2:
this.model = _context.sent;
return _context.abrupt('return', this);
case 4:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel(_x) {
return _ref.apply(this, arguments);
}
return loadModel;
}()
}, {
key: 'classifyInternal',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(numberOfClasses, callback) {
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.ready;
case 2:
_context2.next = 4;
return tf.nextFrame();
case 4:
return _context2.abrupt('return', this.model.classify(numberOfClasses, callback));
case 5:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function classifyInternal(_x2, _x3) {
return _ref2.apply(this, arguments);
}
return classifyInternal;
}()
/**
* Classifies the audio from microphone and takes a callback to handle the results
* @param {function | number} numOrCallback -
* takes any of the following params
* @param {function} cb - a callback function that handles the results of the function.
* @return {function} a promise or the results of a given callback, cb.
*/
}, {
key: 'classify',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() {
var numOrCallback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var cb = arguments[1];
var numberOfClasses, callback;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
numberOfClasses = this.topk;
callback = void 0;
if (typeof numOrCallback === 'number') {
numberOfClasses = numOrCallback;
} else if (typeof numOrCallback === 'function') {
callback = numOrCallback;
}
if (typeof cb === 'function') {
callback = cb;
}
return _context3.abrupt('return', this.classifyInternal(numberOfClasses, callback));
case 5:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function classify() {
return _ref3.apply(this, arguments);
}
return classify;
}()
}]);
return SoundClassifier;
}();
var soundClassifier = function soundClassifier(modelName, optionsOrCallback, cb) {
var options = {};
var callback = cb;
var model = modelName;
if (typeof model !== 'string') {
throw new Error('Please specify a model to use. E.g: "SpeechCommands18w"');
} else if (model.indexOf('http') === -1) {
model = modelName.toLowerCase();
}
if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object') {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
var instance = new SoundClassifier(model, options, callback);
return callback ? instance : instance.ready;
};
exports.default = soundClassifier;
/***/ }),
/* 372 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint-disable */
exports.default = ["flashlight", "belt", "mushroom", "pond", "strawberry", "pineapple", "sun", "cow", "ear", "bush", "pliers", "watermelon", "apple", "baseball", "feather", "shoe", "leaf", "lollipop", "crown", "ocean", "horse", "mountain", "mosquito", "mug", "hospital", "saw", "castle", "angel", "underwear", "traffic_light", "cruise_ship", "marker", "blueberry", "flamingo", "face", "hockey_stick", "bucket", "campfire", "asparagus", "skateboard", "door", "suitcase", "skull", "cloud", "paint_can", "hockey_puck", "steak", "house_plant", "sleeping_bag", "bench", "snowman", "arm", "crayon", "fan", "shovel", "leg", "washing_machine", "harp", "toothbrush", "tree", "bear", "rake", "megaphone", "knee", "guitar", "calculator", "hurricane", "grapes", "paintbrush", "couch", "nose", "square", "wristwatch", "penguin", "bridge", "octagon", "submarine", "screwdriver", "rollerskates", "ladder", "wine_bottle", "cake", "bracelet", "broom", "yoga", "finger", "fish", "line", "truck", "snake", "bus", "stitches", "snorkel", "shorts", "bowtie", "pickup_truck", "tooth", "snail", "foot", "crab", "school_bus", "train", "dresser", "sock", "tractor", "map", "hedgehog", "coffee_cup", "computer", "matches", "beard", "frog", "crocodile", "bathtub", "rain", "moon", "bee", "knife", "boomerang", "lighthouse", "chandelier", "jail", "pool", "stethoscope", "frying_pan", "cell_phone", "binoculars", "purse", "lantern", "birthday_cake", "clarinet", "palm_tree", "aircraft_carrier", "vase", "eraser", "shark", "skyscraper", "bicycle", "sink", "teapot", "circle", "tornado", "bird", "stereo", "mouth", "key", "hot_dog", "spoon", "laptop", "cup", "bottlecap", "The_Great_Wall_of_China", "The_Mona_Lisa", "smiley_face", "waterslide", "eyeglasses", "ceiling_fan", "lobster", "moustache", "carrot", "garden", "police_car", "postcard", "necklace", "helmet", "blackberry", "beach", "golf_club", "car", "panda", "alarm_clock", "t-shirt", "dog", "bread", "wine_glass", "lighter", "flower", "bandage", "drill", "butterfly", "swan", "owl", "raccoon", "squiggle", "calendar", "giraffe", "elephant", "trumpet", "rabbit", "trombone", "sheep", "onion", "church", "flip_flops", "spreadsheet", "pear", "clock", "roller_coaster", "parachute", "kangaroo", "duck", "remote_control", "compass", "monkey", "rainbow", "tennis_racquet", "lion", "pencil", "string_bean", "oven", "star", "cat", "pizza", "soccer_ball", "syringe", "flying_saucer", "eye", "cookie", "floor_lamp", "mouse", "toilet", "toaster", "The_Eiffel_Tower", "airplane", "stove", "cello", "stop_sign", "tent", "diving_board", "light_bulb", "hammer", "scorpion", "headphones", "basket", "spider", "paper_clip", "sweater", "ice_cream", "envelope", "sea_turtle", "donut", "hat", "hourglass", "broccoli", "jacket", "backpack", "book", "lightning", "drums", "snowflake", "radio", "banana", "camel", "canoe", "toothpaste", "chair", "picture_frame", "parrot", "sandwich", "lipstick", "pants", "violin", "brain", "power_outlet", "triangle", "hamburger", "dragon", "bulldozer", "cannon", "dolphin", "zebra", "animal_migration", "camouflage", "scissors", "basketball", "elbow", "umbrella", "windmill", "table", "rifle", "hexagon", "potato", "anvil", "sword", "peanut", "axe", "television", "rhinoceros", "baseball_bat", "speedboat", "sailboat", "zigzag", "garden_hose", "river", "house", "pillow", "ant", "tiger", "stairs", "cooler", "see_saw", "piano", "fireplace", "popsicle", "dumbbell", "mailbox", "barn", "hot_tub", "teddy-bear", "fork", "dishwasher", "peas", "hot_air_balloon", "keyboard", "microwave", "wheel", "fire_hydrant", "van", "camera", "whale", "candle", "octopus", "pig", "swing_set", "helicopter", "saxophone", "passport", "bat", "ambulance", "diamond", "goatee", "fence", "grass", "mermaid", "motorbike", "microphone", "toe", "cactus", "nail", "telephone", "hand", "squirrel", "streetlight", "bed", "firetruck"];
/***/ }),
/* 373 */
/***/ (function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(48);
var get = __webpack_require__(150);
module.exports = __webpack_require__(18).getIterator = function (it) {
var iterFn = get(it);
if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
/***/ }),
/* 374 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(101);
__webpack_require__(85);
module.exports = __webpack_require__(373);
/***/ }),
/* 375 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(374), __esModule: true };
/***/ }),
/* 376 */
/***/ (function(module, exports, __webpack_require__) {
var classof = __webpack_require__(116);
var ITERATOR = __webpack_require__(25)('iterator');
var Iterators = __webpack_require__(84);
module.exports = __webpack_require__(18).isIterable = function (it) {
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
// eslint-disable-next-line no-prototype-builtins
|| Iterators.hasOwnProperty(classof(O));
};
/***/ }),
/* 377 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(101);
__webpack_require__(85);
module.exports = __webpack_require__(376);
/***/ }),
/* 378 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(377), __esModule: true };
/***/ }),
/* 379 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.load = exports.Doodlenet = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _slicedToArray2 = __webpack_require__(64);
var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var load = exports.load = function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3() {
var doodlenet;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
doodlenet = new Doodlenet();
_context3.next = 3;
return doodlenet.load();
case 3:
return _context3.abrupt('return', doodlenet);
case 4:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
return function load() {
return _ref3.apply(this, arguments);
};
}();
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _gettopkclasses = __webpack_require__(144);
var _DOODLENET_CLASSES = __webpack_require__(372);
var _DOODLENET_CLASSES2 = _interopRequireDefault(_DOODLENET_CLASSES);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
DOODLENET_URL: 'https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models@master/models/doodlenet/model.json',
IMAGE_SIZE_DOODLENET: 28
}; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
function preProcess(img, size) {
var image = void 0;
if (!(img instanceof tf.Tensor)) {
if (img instanceof HTMLImageElement || img instanceof HTMLVideoElement || img instanceof HTMLCanvasElement || img instanceof ImageData) {
image = tf.browser.fromPixels(img);
} else if ((typeof img === 'undefined' ? 'undefined' : (0, _typeof3.default)(img)) === 'object' && (img.elt instanceof HTMLImageElement || img.elt instanceof HTMLVideoElement || img.elt instanceof HTMLCanvasElement || img.elt instanceof ImageData)) {
image = tf.browser.fromPixels(img.elt); // Handle p5.js image, video and canvas.
}
} else {
image = img;
}
var normalized = tf.scalar(1).sub(image.toFloat().div(tf.scalar(255)));
var resized = normalized;
if (normalized.shape[0] !== size || normalized.shape[1] !== size) {
resized = tf.image.resizeBilinear(normalized, [size, size]);
}
var _tf$split = tf.split(resized, 3, 3),
_tf$split2 = (0, _slicedToArray3.default)(_tf$split, 3),
r = _tf$split2[0],
g = _tf$split2[1],
b = _tf$split2[2];
var gray = r.add(g).add(b).div(tf.scalar(3)).floor(); // Get average r,g,b color value and round to 0 or 1
var batched = gray.reshape([1, size, size, 1]);
return batched;
}
var Doodlenet = exports.Doodlenet = function () {
function Doodlenet() {
(0, _classCallCheck3.default)(this, Doodlenet);
this.imgSize = DEFAULTS.IMAGE_SIZE_DOODLENET;
}
(0, _createClass3.default)(Doodlenet, [{
key: 'load',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this = this;
var result;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return tf.loadLayersModel(DEFAULTS.DOODLENET_URL);
case 2:
this.model = _context.sent;
// Warmup the model.
result = tf.tidy(function () {
return _this.model.predict(tf.zeros([1, _this.imgSize, _this.imgSize, 1]));
});
_context.next = 6;
return result.data();
case 6:
result.dispose();
case 7:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function load() {
return _ref.apply(this, arguments);
}
return load;
}()
}, {
key: 'classify',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(img) {
var _this2 = this;
var topk = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
var logits, classes;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
logits = tf.tidy(function () {
var imgData = preProcess(img, _this2.imgSize);
var predictions = _this2.model.predict(imgData);
return predictions;
});
_context2.next = 3;
return (0, _gettopkclasses.getTopKClassesFromTensor)(logits, topk, _DOODLENET_CLASSES2.default);
case 3:
classes = _context2.sent;
logits.dispose();
return _context2.abrupt('return', classes);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function classify(_x2) {
return _ref2.apply(this, arguments);
}
return classify;
}()
}]);
return Doodlenet;
}();
/***/ }),
/* 380 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/* eslint-disable */
exports.default = ["kit fox", "English setter", "Siberian husky", "Australian terrier", "English springer", "grey whale", "lesser panda", "Egyptian cat", "ibex", "Persian cat", "cougar", "gazelle", "porcupine", "sea lion", "malamute", "badger", "Great Dane", "Walker hound", "Welsh springer spaniel", "whippet", "Scottish deerhound", "killer whale", "mink", "African elephant", "Weimaraner", "soft-coated wheaten terrier", "Dandie Dinmont", "red wolf", "Old English sheepdog", "jaguar", "otterhound", "bloodhound", "Airedale", "hyena", "meerkat", "giant schnauzer", "titi", "three-toed sloth", "sorrel", "black-footed ferret", "dalmatian", "black-and-tan coonhound", "papillon", "skunk", "Staffordshire bullterrier", "Mexican hairless", "Bouvier des Flandres", "weasel", "miniature poodle", "Cardigan", "malinois", "bighorn", "fox squirrel", "colobus", "tiger cat", "Lhasa", "impala", "coyote", "Yorkshire terrier", "Newfoundland", "brown bear", "red fox", "Norwegian elkhound", "Rottweiler", "hartebeest", "Saluki", "grey fox", "schipperke", "Pekinese", "Brabancon griffon", "West Highland white terrier", "Sealyham terrier", "guenon", "mongoose", "indri", "tiger", "Irish wolfhound", "wild boar", "EntleBucher", "zebra", "ram", "French bulldog", "orangutan", "basenji", "leopard", "Bernese mountain dog", "Maltese dog", "Norfolk terrier", "toy terrier", "vizsla", "cairn", "squirrel monkey", "groenendael", "clumber", "Siamese cat", "chimpanzee", "komondor", "Afghan hound", "Japanese spaniel", "proboscis monkey", "guinea pig", "white wolf", "ice bear", "gorilla", "borzoi", "toy poodle", "Kerry blue terrier", "ox", "Scotch terrier", "Tibetan mastiff", "spider monkey", "Doberman", "Boston bull", "Greater Swiss Mountain dog", "Appenzeller", "Shih-Tzu", "Irish water spaniel", "Pomeranian", "Bedlington terrier", "warthog", "Arabian camel", "siamang", "miniature schnauzer", "collie", "golden retriever", "Irish terrier", "affenpinscher", "Border collie", "hare", "boxer", "silky terrier", "beagle", "Leonberg", "German short-haired pointer", "patas", "dhole", "baboon", "macaque", "Chesapeake Bay retriever", "bull mastiff", "kuvasz", "capuchin", "pug", "curly-coated retriever", "Norwich terrier", "flat-coated retriever", "hog", "keeshond", "Eskimo dog", "Brittany spaniel", "standard poodle", "Lakeland terrier", "snow leopard", "Gordon setter", "dingo", "standard schnauzer", "hamster", "Tibetan terrier", "Arctic fox", "wire-haired fox terrier", "basset", "water buffalo", "American black bear", "Angora", "bison", "howler monkey", "hippopotamus", "chow", "giant panda", "American Staffordshire terrier", "Shetland sheepdog", "Great Pyrenees", "Chihuahua", "tabby", "marmoset", "Labrador retriever", "Saint Bernard", "armadillo", "Samoyed", "bluetick", "redbone", "polecat", "marmot", "kelpie", "gibbon", "llama", "miniature pinscher", "wood rabbit", "Italian greyhound", "lion", "cocker spaniel", "Irish setter", "dugong", "Indian elephant", "beaver", "Sussex spaniel", "Pembroke", "Blenheim spaniel", "Madagascar cat", "Rhodesian ridgeback", "lynx", "African hunting dog", "langur", "Ibizan hound", "timber wolf", "cheetah", "English foxhound", "briard", "sloth bear", "Border terrier", "German shepherd", "otter", "koala", "tusker", "echidna", "wallaby", "platypus", "wombat", "revolver", "umbrella", "schooner", "soccer ball", "accordion", "ant", "starfish", "chambered nautilus", "grand piano", "laptop", "strawberry", "airliner", "warplane", "airship", "balloon", "space shuttle", "fireboat", "gondola", "speedboat", "lifeboat", "canoe", "yawl", "catamaran", "trimaran", "container ship", "liner", "pirate", "aircraft carrier", "submarine", "wreck", "half track", "tank", "missile", "bobsled", "dogsled", "bicycle-built-for-two", "mountain bike", "freight car", "passenger car", "barrow", "shopping cart", "motor scooter", "forklift", "electric locomotive", "steam locomotive", "amphibian", "ambulance", "beach wagon", "cab", "convertible", "jeep", "limousine", "minivan", "Model T", "racer", "sports car", "go-kart", "golfcart", "moped", "snowplow", "fire engine", "garbage truck", "pickup", "tow truck", "trailer truck", "moving van", "police van", "recreational vehicle", "streetcar", "snowmobile", "tractor", "mobile home", "tricycle", "unicycle", "horse cart", "jinrikisha", "oxcart", "bassinet", "cradle", "crib", "four-poster", "bookcase", "china cabinet", "medicine chest", "chiffonier", "table lamp", "file", "park bench", "barber chair", "throne", "folding chair", "rocking chair", "studio couch", "toilet seat", "desk", "pool table", "dining table", "entertainment center", "wardrobe", "Granny Smith", "orange", "lemon", "fig", "pineapple", "banana", "jackfruit", "custard apple", "pomegranate", "acorn", "hip", "ear", "rapeseed", "corn", "buckeye", "organ", "upright", "chime", "drum", "gong", "maraca", "marimba", "steel drum", "banjo", "cello", "violin", "harp", "acoustic guitar", "electric guitar", "cornet", "French horn", "trombone", "harmonica", "ocarina", "panpipe", "bassoon", "oboe", "sax", "flute", "daisy", "yellow lady's slipper", "cliff", "valley", "alp", "volcano", "promontory", "sandbar", "coral reef", "lakeside", "seashore", "geyser", "hatchet", "cleaver", "letter opener", "plane", "power drill", "lawn mower", "hammer", "corkscrew", "can opener", "plunger", "screwdriver", "shovel", "plow", "chain saw", "cock", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "robin", "bulbul", "jay", "magpie", "chickadee", "water ouzel", "kite", "bald eagle", "vulture", "great grey owl", "black grouse", "ptarmigan", "ruffed grouse", "prairie chicken", "peacock", "quail", "partridge", "African grey", "macaw", "sulphur-crested cockatoo", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "drake", "red-breasted merganser", "goose", "black swan", "white stork", "black stork", "spoonbill", "flamingo", "American egret", "little blue heron", "bittern", "crane", "limpkin", "American coot", "bustard", "ruddy turnstone", "red-backed sandpiper", "redshank", "dowitcher", "oystercatcher", "European gallinule", "pelican", "king penguin", "albatross", "great white shark", "tiger shark", "hammerhead", "electric ray", "stingray", "barracouta", "coho", "tench", "goldfish", "eel", "rock beauty", "anemone fish", "lionfish", "puffer", "sturgeon", "gar", "loggerhead", "leatherback turtle", "mud turtle", "terrapin", "box turtle", "banded gecko", "common iguana", "American chameleon", "whiptail", "agama", "frilled lizard", "alligator lizard", "Gila monster", "green lizard", "African chameleon", "Komodo dragon", "triceratops", "African crocodile", "American alligator", "thunder snake", "ringneck snake", "hognose snake", "green snake", "king snake", "garter snake", "water snake", "vine snake", "night snake", "boa constrictor", "rock python", "Indian cobra", "green mamba", "sea snake", "horned viper", "diamondback", "sidewinder", "European fire salamander", "common newt", "eft", "spotted salamander", "axolotl", "bullfrog", "tree frog", "tailed frog", "whistle", "wing", "paintbrush", "hand blower", "oxygen mask", "snorkel", "loudspeaker", "microphone", "screen", "mouse", "electric fan", "oil filter", "strainer", "space heater", "stove", "guillotine", "barometer", "rule", "odometer", "scale", "analog clock", "digital clock", "wall clock", "hourglass", "sundial", "parking meter", "stopwatch", "digital watch", "stethoscope", "syringe", "magnetic compass", "binoculars", "projector", "sunglasses", "loupe", "radio telescope", "bow", "cannon", "assault rifle", "rifle", "projectile", "computer keyboard", "typewriter keyboard", "crane", "lighter", "abacus", "cash machine", "slide rule", "desktop computer", "hand-held computer", "notebook", "web site", "harvester", "thresher", "printer", "slot", "vending machine", "sewing machine", "joystick", "switch", "hook", "car wheel", "paddlewheel", "pinwheel", "potter's wheel", "gas pump", "carousel", "swing", "reel", "radiator", "puck", "hard disc", "sunglass", "pick", "car mirror", "solar dish", "remote control", "disk brake", "buckle", "hair slide", "knot", "combination lock", "padlock", "nail", "safety pin", "screw", "muzzle", "seat belt", "ski", "candle", "jack-o'-lantern", "spotlight", "torch", "neck brace", "pier", "tripod", "maypole", "mousetrap", "spider web", "trilobite", "harvestman", "scorpion", "black and gold garden spider", "barn spider", "garden spider", "black widow", "tarantula", "wolf spider", "tick", "centipede", "isopod", "Dungeness crab", "rock crab", "fiddler crab", "king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", "tiger beetle", "ladybug", "ground beetle", "long-horned beetle", "leaf beetle", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "grasshopper", "cricket", "walking stick", "cockroach", "mantis", "cicada", "leafhopper", "lacewing", "dragonfly", "damselfly", "admiral", "ringlet", "monarch", "cabbage butterfly", "sulphur butterfly", "lycaenid", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", "snail", "slug", "sea slug", "chiton", "sea urchin", "sea cucumber", "iron", "espresso maker", "microwave", "Dutch oven", "rotisserie", "toaster", "waffle iron", "vacuum", "dishwasher", "refrigerator", "washer", "Crock Pot", "frying pan", "wok", "caldron", "coffeepot", "teapot", "spatula", "altar", "triumphal arch", "patio", "steel arch bridge", "suspension bridge", "viaduct", "barn", "greenhouse", "palace", "monastery", "library", "apiary", "boathouse", "church", "mosque", "stupa", "planetarium", "restaurant", "cinema", "home theater", "lumbermill", "coil", "obelisk", "totem pole", "castle", "prison", "grocery store", "bakery", "barbershop", "bookshop", "butcher shop", "confectionery", "shoe shop", "tobacco shop", "toyshop", "fountain", "cliff dwelling", "yurt", "dock", "brass", "megalith", "bannister", "breakwater", "dam", "chainlink fence", "picket fence", "worm fence", "stone wall", "grille", "sliding door", "turnstile", "mountain tent", "scoreboard", "honeycomb", "plate rack", "pedestal", "beacon", "mashed potato", "bell pepper", "head cabbage", "broccoli", "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", "artichoke", "cardoon", "mushroom", "shower curtain", "jean", "carton", "handkerchief", "sandal", "ashcan", "safe", "plate", "necklace", "croquet ball", "fur coat", "thimble", "pajama", "running shoe", "cocktail shaker", "chest", "manhole cover", "modem", "tub", "tray", "balance beam", "bagel", "prayer rug", "kimono", "hot pot", "whiskey jug", "knee pad", "book jacket", "spindle", "ski mask", "beer bottle", "crash helmet", "bottlecap", "tile roof", "mask", "maillot", "Petri dish", "football helmet", "bathing cap", "teddy", "holster", "pop bottle", "photocopier", "vestment", "crossword puzzle", "golf ball", "trifle", "suit", "water tower", "feather boa", "cloak", "red wine", "drumstick", "shield", "Christmas stocking", "hoopskirt", "menu", "stage", "bonnet", "meat loaf", "baseball", "face powder", "scabbard", "sunscreen", "beer glass", "hen-of-the-woods", "guacamole", "lampshade", "wool", "hay", "bow tie", "mailbag", "water jug", "bucket", "dishrag", "soup bowl", "eggnog", "mortar", "trench coat", "paddle", "chain", "swab", "mixing bowl", "potpie", "wine bottle", "shoji", "bulletproof vest", "drilling platform", "binder", "cardigan", "sweatshirt", "pot", "birdhouse", "hamper", "ping-pong ball", "pencil box", "pay-phone", "consomme", "apron", "punching bag", "backpack", "groom", "bearskin", "pencil sharpener", "broom", "mosquito net", "abaya", "mortarboard", "poncho", "crutch", "Polaroid camera", "space bar", "cup", "racket", "traffic light", "quill", "radio", "dough", "cuirass", "military uniform", "lipstick", "shower cap", "monitor", "oscilloscope", "mitten", "brassiere", "French loaf", "vase", "milk can", "rugby ball", "paper towel", "earthstar", "envelope", "miniskirt", "cowboy hat", "trolleybus", "perfume", "bathtub", "hotdog", "coral fungus", "bullet train", "pillow", "toilet tissue", "cassette", "carpenter's kit", "ladle", "stinkhorn", "lotion", "hair spray", "academic gown", "dome", "crate", "wig", "burrito", "pill bottle", "chain mail", "theater curtain", "window shade", "barrel", "washbasin", "ballpoint", "basketball", "bath towel", "cowboy boot", "gown", "window screen", "agaric", "cellular telephone", "nipple", "barbell", "mailbox", "lab coat", "fire screen", "minibus", "packet", "maze", "pole", "horizontal bar", "sombrero", "pickelhaube", "rain barrel", "wallet", "cassette player", "comic book", "piggy bank", "street sign", "bell cote", "fountain pen", "Windsor tie", "volleyball", "overskirt", "sarong", "purse", "bolo tie", "bib", "parachute", "sleeping bag", "television", "swimming trunks", "measuring cup", "espresso", "pizza", "breastplate", "shopping basket", "wooden spoon", "saltshaker", "chocolate sauce", "ballplayer", "goblet", "gyromitra", "stretcher", "water bottle", "dial telephone", "soap dispenser", "jersey", "school bus", "jigsaw puzzle", "plastic bag", "reflex camera", "diaper", "Band Aid", "ice lolly", "velvet", "tennis ball", "gasmask", "doormat", "Loafer", "ice cream", "pretzel", "quilt", "maillot", "tape player", "clog", "iPod", "bolete", "scuba diver", "pitcher", "matchstick", "bikini", "sock", "CD player", "lens cap", "thatch", "vault", "beaker", "bubble", "cheeseburger", "parallel bars", "flagpole", "coffee mug", "rubber eraser", "stole", "carbonara", "dumbbell"];
/***/ }),
/* 381 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.load = exports.Darknet = undefined;
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var load = exports.load = function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(version) {
var darknet;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(version !== "reference" && version !== "tiny")) {
_context3.next = 2;
break;
}
throw new Error("Please select a version: darknet-reference or darknet-tiny");
case 2:
darknet = new Darknet(version);
_context3.next = 5;
return darknet.load();
case 5:
return _context3.abrupt("return", darknet);
case 6:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
return function load(_x3) {
return _ref3.apply(this, arguments);
};
}();
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _gettopkclasses = __webpack_require__(144);
var _IMAGENET_CLASSES_DARKNET = __webpack_require__(380);
var _IMAGENET_CLASSES_DARKNET2 = _interopRequireDefault(_IMAGENET_CLASSES_DARKNET);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULTS = {
DARKNET_URL: "https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models@master/models/darknetclassifier/darknetreference/model.json",
DARKNET_TINY_URL: "https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models@master/models/darknetclassifier/darknettiny/model.json",
IMAGE_SIZE_DARKNET: 256,
IMAGE_SIZE_DARKNET_TINY: 224
}; // Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
function preProcess(img, size) {
var image = void 0;
if (!(img instanceof tf.Tensor)) {
if (img instanceof HTMLImageElement || img instanceof HTMLVideoElement || img instanceof HTMLCanvasElement || img instanceof ImageData) {
image = tf.browser.fromPixels(img);
} else if ((typeof img === "undefined" ? "undefined" : (0, _typeof3.default)(img)) === "object" && (img.elt instanceof HTMLImageElement || img.elt instanceof HTMLVideoElement || img.elt instanceof HTMLCanvasElement || img.elt instanceof ImageData)) {
image = tf.browser.fromPixels(img.elt); // Handle p5.js image and video.
}
} else {
image = img;
}
var normalized = image.toFloat().div(tf.scalar(255));
var resized = normalized;
if (normalized.shape[0] !== size || normalized.shape[1] !== size) {
var alignCorners = true;
resized = tf.image.resizeBilinear(normalized, [size, size], alignCorners);
}
var batched = resized.reshape([1, size, size, 3]);
return batched;
}
var Darknet = exports.Darknet = function () {
function Darknet(version) {
(0, _classCallCheck3.default)(this, Darknet);
this.version = version;
switch (this.version) {
case "reference":
this.imgSize = DEFAULTS.IMAGE_SIZE_DARKNET;
break;
case "tiny":
this.imgSize = DEFAULTS.IMAGE_SIZE_DARKNET_TINY;
break;
default:
break;
}
}
(0, _createClass3.default)(Darknet, [{
key: "load",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
var _this = this;
var result;
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.t0 = this.version;
_context.next = _context.t0 === "reference" ? 3 : _context.t0 === "tiny" ? 7 : 11;
break;
case 3:
_context.next = 5;
return tf.loadLayersModel(DEFAULTS.DARKNET_URL);
case 5:
this.model = _context.sent;
return _context.abrupt("break", 12);
case 7:
_context.next = 9;
return tf.loadLayersModel(DEFAULTS.DARKNET_TINY_URL);
case 9:
this.model = _context.sent;
return _context.abrupt("break", 12);
case 11:
return _context.abrupt("break", 12);
case 12:
// Warmup the model.
result = tf.tidy(function () {
return _this.model.predict(tf.zeros([1, _this.imgSize, _this.imgSize, 3]));
});
_context.next = 15;
return result.data();
case 15:
result.dispose();
case 16:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function load() {
return _ref.apply(this, arguments);
}
return load;
}()
}, {
key: "classify",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(img) {
var _this2 = this;
var topk = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
var logits, classes;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
logits = tf.tidy(function () {
var imgData = preProcess(img, _this2.imgSize);
var predictions = _this2.model.predict(imgData);
return tf.softmax(predictions);
});
_context2.next = 3;
return (0, _gettopkclasses.getTopKClassesFromTensor)(logits, topk, _IMAGENET_CLASSES_DARKNET2.default);
case 3:
classes = _context2.sent;
logits.dispose();
return _context2.abrupt("return", classes);
case 6:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function classify(_x2) {
return _ref2.apply(this, arguments);
}
return classify;
}()
}]);
return Darknet;
}();
/***/ }),
/* 382 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; });
/* harmony import */ var _tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20);
/* harmony import */ var _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/**
* @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.
* =============================================================================
*/
function __awaiter(e,a,r,o){return new(r||(r=Promise))(function(i,t){function n(e){try{s(o.next(e))}catch(e){t(e)}}function l(e){try{s(o.throw(e))}catch(e){t(e)}}function s(e){e.done?i(e.value):new r(function(a){a(e.value)}).then(n,l)}s((o=o.apply(e,a||[])).next())})}function __generator(e,a){var r,o,i,t,n={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return t={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(t[Symbol.iterator]=function(){return this}),t;function l(t){return function(l){return function(t){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,o&&(i=2&t[0]?o.return:t[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,t[1])).done)return i;switch(o=0,i&&(t=[2&t[0],i.value]),t[0]){case 0:case 1:i=t;break;case 4:return n.label++,{value:t[1],done:!1};case 5:n.label++,o=t[1],t=[0];continue;case 7:t=n.ops.pop(),n.trys.pop();continue;default:if(!(i=(i=n.trys).length>0&&i[i.length-1])&&(6===t[0]||2===t[0])){n=0;continue}if(3===t[0]&&(!i||t[1]>i[0]&&t[1]<i[3])){n.label=t[1];break}if(6===t[0]&&n.label<i[1]){n.label=i[1],i=t;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(t);break}i[2]&&n.ops.pop(),n.trys.pop();continue}t=a.call(e,n)}catch(e){t=[6,e],o=0}finally{r=i=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,l])}}}var IMAGENET_CLASSES={0:"tench, Tinca tinca",1:"goldfish, Carassius auratus",2:"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",3:"tiger shark, Galeocerdo cuvieri",4:"hammerhead, hammerhead shark",5:"electric ray, crampfish, numbfish, torpedo",6:"stingray",7:"cock",8:"hen",9:"ostrich, Struthio camelus",10:"brambling, Fringilla montifringilla",11:"goldfinch, Carduelis carduelis",12:"house finch, linnet, Carpodacus mexicanus",13:"junco, snowbird",14:"indigo bunting, indigo finch, indigo bird, Passerina cyanea",15:"robin, American robin, Turdus migratorius",16:"bulbul",17:"jay",18:"magpie",19:"chickadee",20:"water ouzel, dipper",21:"kite",22:"bald eagle, American eagle, Haliaeetus leucocephalus",23:"vulture",24:"great grey owl, great gray owl, Strix nebulosa",25:"European fire salamander, Salamandra salamandra",26:"common newt, Triturus vulgaris",27:"eft",28:"spotted salamander, Ambystoma maculatum",29:"axolotl, mud puppy, Ambystoma mexicanum",30:"bullfrog, Rana catesbeiana",31:"tree frog, tree-frog",32:"tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",33:"loggerhead, loggerhead turtle, Caretta caretta",34:"leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",35:"mud turtle",36:"terrapin",37:"box turtle, box tortoise",38:"banded gecko",39:"common iguana, iguana, Iguana iguana",40:"American chameleon, anole, Anolis carolinensis",41:"whiptail, whiptail lizard",42:"agama",43:"frilled lizard, Chlamydosaurus kingi",44:"alligator lizard",45:"Gila monster, Heloderma suspectum",46:"green lizard, Lacerta viridis",47:"African chameleon, Chamaeleo chamaeleon",48:"Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",49:"African crocodile, Nile crocodile, Crocodylus niloticus",50:"American alligator, Alligator mississipiensis",51:"triceratops",52:"thunder snake, worm snake, Carphophis amoenus",53:"ringneck snake, ring-necked snake, ring snake",54:"hognose snake, puff adder, sand viper",55:"green snake, grass snake",56:"king snake, kingsnake",57:"garter snake, grass snake",58:"water snake",59:"vine snake",60:"night snake, Hypsiglena torquata",61:"boa constrictor, Constrictor constrictor",62:"rock python, rock snake, Python sebae",63:"Indian cobra, Naja naja",64:"green mamba",65:"sea snake",66:"horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",67:"diamondback, diamondback rattlesnake, Crotalus adamanteus",68:"sidewinder, horned rattlesnake, Crotalus cerastes",69:"trilobite",70:"harvestman, daddy longlegs, Phalangium opilio",71:"scorpion",72:"black and gold garden spider, Argiope aurantia",73:"barn spider, Araneus cavaticus",74:"garden spider, Aranea diademata",75:"black widow, Latrodectus mactans",76:"tarantula",77:"wolf spider, hunting spider",78:"tick",79:"centipede",80:"black grouse",81:"ptarmigan",82:"ruffed grouse, partridge, Bonasa umbellus",83:"prairie chicken, prairie grouse, prairie fowl",84:"peacock",85:"quail",86:"partridge",87:"African grey, African gray, Psittacus erithacus",88:"macaw",89:"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",90:"lorikeet",91:"coucal",92:"bee eater",93:"hornbill",94:"hummingbird",95:"jacamar",96:"toucan",97:"drake",98:"red-breasted merganser, Mergus serrator",99:"goose",100:"black swan, Cygnus atratus",101:"tusker",102:"echidna, spiny anteater, anteater",103:"platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",104:"wallaby, brush kangaroo",105:"koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",106:"wombat",107:"jelly fish",108:"sea anemone, anemone",109:"brain coral",110:"flatworm, platyhelminth",111:"nematode, nematode worm, roundworm",112:"conch",113:"snail",114:"slug",115:"sea slug, nudibranch",116:"chiton, coat-of-mail shell, sea cradle, polyplacophore",117:"chambered nautilus, pearly nautilus, nautilus",118:"Dungeness crab, Cancer magister",119:"rock crab, Cancer irroratus",120:"fiddler crab",121:"king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",122:"American lobster, Northern lobster, Maine lobster, Homarus americanus",123:"spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",124:"crayfish, crawfish, crawdad, crawdaddy",125:"hermit crab",126:"isopod",127:"white stork, Ciconia ciconia",128:"black stork, Ciconia nigra",129:"spoonbill",130:"flamingo",131:"little blue heron, Egretta caerulea",132:"American egret, great white heron, Egretta albus",133:"bittern",134:"crane",135:"limpkin, Aramus pictus",136:"European gallinule, Porphyrio porphyrio",137:"American coot, marsh hen, mud hen, water hen, Fulica americana",138:"bustard",139:"ruddy turnstone, Arenaria interpres",140:"red-backed sandpiper, dunlin, Erolia alpina",141:"redshank, Tringa totanus",142:"dowitcher",143:"oystercatcher, oyster catcher",144:"pelican",145:"king penguin, Aptenodytes patagonica",146:"albatross, mollymawk",147:"grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",148:"killer whale, killer, orca, grampus, sea wolf, Orcinus orca",149:"dugong, Dugong dugon",150:"sea lion",151:"Chihuahua",152:"Japanese spaniel",153:"Maltese dog, Maltese terrier, Maltese",154:"Pekinese, Pekingese, Peke",155:"Shih-Tzu",156:"Blenheim spaniel",157:"papillon",158:"toy terrier",159:"Rhodesian ridgeback",160:"Afghan hound, Afghan",161:"basset, basset hound",162:"beagle",163:"bloodhound, sleuthhound",164:"bluetick",165:"black-and-tan coonhound",166:"Walker hound, Walker foxhound",167:"English foxhound",168:"redbone",169:"borzoi, Russian wolfhound",170:"Irish wolfhound",171:"Italian greyhound",172:"whippet",173:"Ibizan hound, Ibizan Podenco",174:"Norwegian elkhound, elkhound",175:"otterhound, otter hound",176:"Saluki, gazelle hound",177:"Scottish deerhound, deerhound",178:"Weimaraner",179:"Staffordshire bullterrier, Staffordshire bull terrier",180:"American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",181:"Bedlington terrier",182:"Border terrier",183:"Kerry blue terrier",184:"Irish terrier",185:"Norfolk terrier",186:"Norwich terrier",187:"Yorkshire terrier",188:"wire-haired fox terrier",189:"Lakeland terrier",190:"Sealyham terrier, Sealyham",191:"Airedale, Airedale terrier",192:"cairn, cairn terrier",193:"Australian terrier",194:"Dandie Dinmont, Dandie Dinmont terrier",195:"Boston bull, Boston terrier",196:"miniature schnauzer",197:"giant schnauzer",198:"standard schnauzer",199:"Scotch terrier, Scottish terrier, Scottie",200:"Tibetan terrier, chrysanthemum dog",201:"silky terrier, Sydney silky",202:"soft-coated wheaten terrier",203:"West Highland white terrier",204:"Lhasa, Lhasa apso",205:"flat-coated retriever",206:"curly-coated retriever",207:"golden retriever",208:"Labrador retriever",209:"Chesapeake Bay retriever",210:"German short-haired pointer",211:"vizsla, Hungarian pointer",212:"English setter",213:"Irish setter, red setter",214:"Gordon setter",215:"Brittany spaniel",216:"clumber, clumber spaniel",217:"English springer, English springer spaniel",218:"Welsh springer spaniel",219:"cocker spaniel, English cocker spaniel, cocker",220:"Sussex spaniel",221:"Irish water spaniel",222:"kuvasz",223:"schipperke",224:"groenendael",225:"malinois",226:"briard",227:"kelpie",228:"komondor",229:"Old English sheepdog, bobtail",230:"Shetland sheepdog, Shetland sheep dog, Shetland",231:"collie",232:"Border collie",233:"Bouvier des Flandres, Bouviers des Flandres",234:"Rottweiler",235:"German shepherd, German shepherd dog, German police dog, alsatian",236:"Doberman, Doberman pinscher",237:"miniature pinscher",238:"Greater Swiss Mountain dog",239:"Bernese mountain dog",240:"Appenzeller",241:"EntleBucher",242:"boxer",243:"bull mastiff",244:"Tibetan mastiff",245:"French bulldog",246:"Great Dane",247:"Saint Bernard, St Bernard",248:"Eskimo dog, husky",249:"malamute, malemute, Alaskan malamute",250:"Siberian husky",251:"dalmatian, coach dog, carriage dog",252:"affenpinscher, monkey pinscher, monkey dog",253:"basenji",254:"pug, pug-dog",255:"Leonberg",256:"Newfoundland, Newfoundland dog",257:"Great Pyrenees",258:"Samoyed, Samoyede",259:"Pomeranian",260:"chow, chow chow",261:"keeshond",262:"Brabancon griffon",263:"Pembroke, Pembroke Welsh corgi",264:"Cardigan, Cardigan Welsh corgi",265:"toy poodle",266:"miniature poodle",267:"standard poodle",268:"Mexican hairless",269:"timber wolf, grey wolf, gray wolf, Canis lupus",270:"white wolf, Arctic wolf, Canis lupus tundrarum",271:"red wolf, maned wolf, Canis rufus, Canis niger",272:"coyote, prairie wolf, brush wolf, Canis latrans",273:"dingo, warrigal, warragal, Canis dingo",274:"dhole, Cuon alpinus",275:"African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",276:"hyena, hyaena",277:"red fox, Vulpes vulpes",278:"kit fox, Vulpes macrotis",279:"Arctic fox, white fox, Alopex lagopus",280:"grey fox, gray fox, Urocyon cinereoargenteus",281:"tabby, tabby cat",282:"tiger cat",283:"Persian cat",284:"Siamese cat, Siamese",285:"Egyptian cat",286:"cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",287:"lynx, catamount",288:"leopard, Panthera pardus",289:"snow leopard, ounce, Panthera uncia",290:"jaguar, panther, Panthera onca, Felis onca",291:"lion, king of beasts, Panthera leo",292:"tiger, Panthera tigris",293:"cheetah, chetah, Acinonyx jubatus",294:"brown bear, bruin, Ursus arctos",295:"American black bear, black bear, Ursus americanus, Euarctos americanus",296:"ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",297:"sloth bear, Melursus ursinus, Ursus ursinus",298:"mongoose",299:"meerkat, mierkat",300:"tiger beetle",301:"ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",302:"ground beetle, carabid beetle",303:"long-horned beetle, longicorn, longicorn beetle",304:"leaf beetle, chrysomelid",305:"dung beetle",306:"rhinoceros beetle",307:"weevil",308:"fly",309:"bee",310:"ant, emmet, pismire",311:"grasshopper, hopper",312:"cricket",313:"walking stick, walkingstick, stick insect",314:"cockroach, roach",315:"mantis, mantid",316:"cicada, cicala",317:"leafhopper",318:"lacewing, lacewing fly",319:"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",320:"damselfly",321:"admiral",322:"ringlet, ringlet butterfly",323:"monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",324:"cabbage butterfly",325:"sulphur butterfly, sulfur butterfly",326:"lycaenid, lycaenid butterfly",327:"starfish, sea star",328:"sea urchin",329:"sea cucumber, holothurian",330:"wood rabbit, cottontail, cottontail rabbit",331:"hare",332:"Angora, Angora rabbit",333:"hamster",334:"porcupine, hedgehog",335:"fox squirrel, eastern fox squirrel, Sciurus niger",336:"marmot",337:"beaver",338:"guinea pig, Cavia cobaya",339:"sorrel",340:"zebra",341:"hog, pig, grunter, squealer, Sus scrofa",342:"wild boar, boar, Sus scrofa",343:"warthog",344:"hippopotamus, hippo, river horse, Hippopotamus amphibius",345:"ox",346:"water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",347:"bison",348:"ram, tup",349:"bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",350:"ibex, Capra ibex",351:"hartebeest",352:"impala, Aepyceros melampus",353:"gazelle",354:"Arabian camel, dromedary, Camelus dromedarius",355:"llama",356:"weasel",357:"mink",358:"polecat, fitch, foulmart, foumart, Mustela putorius",359:"black-footed ferret, ferret, Mustela nigripes",360:"otter",361:"skunk, polecat, wood pussy",362:"badger",363:"armadillo",364:"three-toed sloth, ai, Bradypus tridactylus",365:"orangutan, orang, orangutang, Pongo pygmaeus",366:"gorilla, Gorilla gorilla",367:"chimpanzee, chimp, Pan troglodytes",368:"gibbon, Hylobates lar",369:"siamang, Hylobates syndactylus, Symphalangus syndactylus",370:"guenon, guenon monkey",371:"patas, hussar monkey, Erythrocebus patas",372:"baboon",373:"macaque",374:"langur",375:"colobus, colobus monkey",376:"proboscis monkey, Nasalis larvatus",377:"marmoset",378:"capuchin, ringtail, Cebus capucinus",379:"howler monkey, howler",380:"titi, titi monkey",381:"spider monkey, Ateles geoffroyi",382:"squirrel monkey, Saimiri sciureus",383:"Madagascar cat, ring-tailed lemur, Lemur catta",384:"indri, indris, Indri indri, Indri brevicaudatus",385:"Indian elephant, Elephas maximus",386:"African elephant, Loxodonta africana",387:"lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",388:"giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",389:"barracouta, snoek",390:"eel",391:"coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",392:"rock beauty, Holocanthus tricolor",393:"anemone fish",394:"sturgeon",395:"gar, garfish, garpike, billfish, Lepisosteus osseus",396:"lionfish",397:"puffer, pufferfish, blowfish, globefish",398:"abacus",399:"abaya",400:"academic gown, academic robe, judge's robe",401:"accordion, piano accordion, squeeze box",402:"acoustic guitar",403:"aircraft carrier, carrier, flattop, attack aircraft carrier",404:"airliner",405:"airship, dirigible",406:"altar",407:"ambulance",408:"amphibian, amphibious vehicle",409:"analog clock",410:"apiary, bee house",411:"apron",412:"ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",413:"assault rifle, assault gun",414:"backpack, back pack, knapsack, packsack, rucksack, haversack",415:"bakery, bakeshop, bakehouse",416:"balance beam, beam",417:"balloon",418:"ballpoint, ballpoint pen, ballpen, Biro",419:"Band Aid",420:"banjo",421:"bannister, banister, balustrade, balusters, handrail",422:"barbell",423:"barber chair",424:"barbershop",425:"barn",426:"barometer",427:"barrel, cask",428:"barrow, garden cart, lawn cart, wheelbarrow",429:"baseball",430:"basketball",431:"bassinet",432:"bassoon",433:"bathing cap, swimming cap",434:"bath towel",435:"bathtub, bathing tub, bath, tub",436:"beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",437:"beacon, lighthouse, beacon light, pharos",438:"beaker",439:"bearskin, busby, shako",440:"beer bottle",441:"beer glass",442:"bell cote, bell cot",443:"bib",444:"bicycle-built-for-two, tandem bicycle, tandem",445:"bikini, two-piece",446:"binder, ring-binder",447:"binoculars, field glasses, opera glasses",448:"birdhouse",449:"boathouse",450:"bobsled, bobsleigh, bob",451:"bolo tie, bolo, bola tie, bola",452:"bonnet, poke bonnet",453:"bookcase",454:"bookshop, bookstore, bookstall",455:"bottlecap",456:"bow",457:"bow tie, bow-tie, bowtie",458:"brass, memorial tablet, plaque",459:"brassiere, bra, bandeau",460:"breakwater, groin, groyne, mole, bulwark, seawall, jetty",461:"breastplate, aegis, egis",462:"broom",463:"bucket, pail",464:"buckle",465:"bulletproof vest",466:"bullet train, bullet",467:"butcher shop, meat market",468:"cab, hack, taxi, taxicab",469:"caldron, cauldron",470:"candle, taper, wax light",471:"cannon",472:"canoe",473:"can opener, tin opener",474:"cardigan",475:"car mirror",476:"carousel, carrousel, merry-go-round, roundabout, whirligig",477:"carpenter's kit, tool kit",478:"carton",479:"car wheel",480:"cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",481:"cassette",482:"cassette player",483:"castle",484:"catamaran",485:"CD player",486:"cello, violoncello",487:"cellular telephone, cellular phone, cellphone, cell, mobile phone",488:"chain",489:"chainlink fence",490:"chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",491:"chain saw, chainsaw",492:"chest",493:"chiffonier, commode",494:"chime, bell, gong",495:"china cabinet, china closet",496:"Christmas stocking",497:"church, church building",498:"cinema, movie theater, movie theatre, movie house, picture palace",499:"cleaver, meat cleaver, chopper",500:"cliff dwelling",501:"cloak",502:"clog, geta, patten, sabot",503:"cocktail shaker",504:"coffee mug",505:"coffeepot",506:"coil, spiral, volute, whorl, helix",507:"combination lock",508:"computer keyboard, keypad",509:"confectionery, confectionary, candy store",510:"container ship, containership, container vessel",511:"convertible",512:"corkscrew, bottle screw",513:"cornet, horn, trumpet, trump",514:"cowboy boot",515:"cowboy hat, ten-gallon hat",516:"cradle",517:"crane",518:"crash helmet",519:"crate",520:"crib, cot",521:"Crock Pot",522:"croquet ball",523:"crutch",524:"cuirass",525:"dam, dike, dyke",526:"desk",527:"desktop computer",528:"dial telephone, dial phone",529:"diaper, nappy, napkin",530:"digital clock",531:"digital watch",532:"dining table, board",533:"dishrag, dishcloth",534:"dishwasher, dish washer, dishwashing machine",535:"disk brake, disc brake",536:"dock, dockage, docking facility",537:"dogsled, dog sled, dog sleigh",538:"dome",539:"doormat, welcome mat",540:"drilling platform, offshore rig",541:"drum, membranophone, tympan",542:"drumstick",543:"dumbbell",544:"Dutch oven",545:"electric fan, blower",546:"electric guitar",547:"electric locomotive",548:"entertainment center",549:"envelope",550:"espresso maker",551:"face powder",552:"feather boa, boa",553:"file, file cabinet, filing cabinet",554:"fireboat",555:"fire engine, fire truck",556:"fire screen, fireguard",557:"flagpole, flagstaff",558:"flute, transverse flute",559:"folding chair",560:"football helmet",561:"forklift",562:"fountain",563:"fountain pen",564:"four-poster",565:"freight car",566:"French horn, horn",567:"frying pan, frypan, skillet",568:"fur coat",569:"garbage truck, dustcart",570:"gasmask, respirator, gas helmet",571:"gas pump, gasoline pump, petrol pump, island dispenser",572:"goblet",573:"go-kart",574:"golf ball",575:"golfcart, golf cart",576:"gondola",577:"gong, tam-tam",578:"gown",579:"grand piano, grand",580:"greenhouse, nursery, glasshouse",581:"grille, radiator grille",582:"grocery store, grocery, food market, market",583:"guillotine",584:"hair slide",585:"hair spray",586:"half track",587:"hammer",588:"hamper",589:"hand blower, blow dryer, blow drier, hair dryer, hair drier",590:"hand-held computer, hand-held microcomputer",591:"handkerchief, hankie, hanky, hankey",592:"hard disc, hard disk, fixed disk",593:"harmonica, mouth organ, harp, mouth harp",594:"harp",595:"harvester, reaper",596:"hatchet",597:"holster",598:"home theater, home theatre",599:"honeycomb",600:"hook, claw",601:"hoopskirt, crinoline",602:"horizontal bar, high bar",603:"horse cart, horse-cart",604:"hourglass",605:"iPod",606:"iron, smoothing iron",607:"jack-o'-lantern",608:"jean, blue jean, denim",609:"jeep, landrover",610:"jersey, T-shirt, tee shirt",611:"jigsaw puzzle",612:"jinrikisha, ricksha, rickshaw",613:"joystick",614:"kimono",615:"knee pad",616:"knot",617:"lab coat, laboratory coat",618:"ladle",619:"lampshade, lamp shade",620:"laptop, laptop computer",621:"lawn mower, mower",622:"lens cap, lens cover",623:"letter opener, paper knife, paperknife",624:"library",625:"lifeboat",626:"lighter, light, igniter, ignitor",627:"limousine, limo",628:"liner, ocean liner",629:"lipstick, lip rouge",630:"Loafer",631:"lotion",632:"loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",633:"loupe, jeweler's loupe",634:"lumbermill, sawmill",635:"magnetic compass",636:"mailbag, postbag",637:"mailbox, letter box",638:"maillot",639:"maillot, tank suit",640:"manhole cover",641:"maraca",642:"marimba, xylophone",643:"mask",644:"matchstick",645:"maypole",646:"maze, labyrinth",647:"measuring cup",648:"medicine chest, medicine cabinet",649:"megalith, megalithic structure",650:"microphone, mike",651:"microwave, microwave oven",652:"military uniform",653:"milk can",654:"minibus",655:"miniskirt, mini",656:"minivan",657:"missile",658:"mitten",659:"mixing bowl",660:"mobile home, manufactured home",661:"Model T",662:"modem",663:"monastery",664:"monitor",665:"moped",666:"mortar",667:"mortarboard",668:"mosque",669:"mosquito net",670:"motor scooter, scooter",671:"mountain bike, all-terrain bike, off-roader",672:"mountain tent",673:"mouse, computer mouse",674:"mousetrap",675:"moving van",676:"muzzle",677:"nail",678:"neck brace",679:"necklace",680:"nipple",681:"notebook, notebook computer",682:"obelisk",683:"oboe, hautboy, hautbois",684:"ocarina, sweet potato",685:"odometer, hodometer, mileometer, milometer",686:"oil filter",687:"organ, pipe organ",688:"oscilloscope, scope, cathode-ray oscilloscope, CRO",689:"overskirt",690:"oxcart",691:"oxygen mask",692:"packet",693:"paddle, boat paddle",694:"paddlewheel, paddle wheel",695:"padlock",696:"paintbrush",697:"pajama, pyjama, pj's, jammies",698:"palace",699:"panpipe, pandean pipe, syrinx",700:"paper towel",701:"parachute, chute",702:"parallel bars, bars",703:"park bench",704:"parking meter",705:"passenger car, coach, carriage",706:"patio, terrace",707:"pay-phone, pay-station",708:"pedestal, plinth, footstall",709:"pencil box, pencil case",710:"pencil sharpener",711:"perfume, essence",712:"Petri dish",713:"photocopier",714:"pick, plectrum, plectron",715:"pickelhaube",716:"picket fence, paling",717:"pickup, pickup truck",718:"pier",719:"piggy bank, penny bank",720:"pill bottle",721:"pillow",722:"ping-pong ball",723:"pinwheel",724:"pirate, pirate ship",725:"pitcher, ewer",726:"plane, carpenter's plane, woodworking plane",727:"planetarium",728:"plastic bag",729:"plate rack",730:"plow, plough",731:"plunger, plumber's helper",732:"Polaroid camera, Polaroid Land camera",733:"pole",734:"police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",735:"poncho",736:"pool table, billiard table, snooker table",737:"pop bottle, soda bottle",738:"pot, flowerpot",739:"potter's wheel",740:"power drill",741:"prayer rug, prayer mat",742:"printer",743:"prison, prison house",744:"projectile, missile",745:"projector",746:"puck, hockey puck",747:"punching bag, punch bag, punching ball, punchball",748:"purse",749:"quill, quill pen",750:"quilt, comforter, comfort, puff",751:"racer, race car, racing car",752:"racket, racquet",753:"radiator",754:"radio, wireless",755:"radio telescope, radio reflector",756:"rain barrel",757:"recreational vehicle, RV, R.V.",758:"reel",759:"reflex camera",760:"refrigerator, icebox",761:"remote control, remote",762:"restaurant, eating house, eating place, eatery",763:"revolver, six-gun, six-shooter",764:"rifle",765:"rocking chair, rocker",766:"rotisserie",767:"rubber eraser, rubber, pencil eraser",768:"rugby ball",769:"rule, ruler",770:"running shoe",771:"safe",772:"safety pin",773:"saltshaker, salt shaker",774:"sandal",775:"sarong",776:"sax, saxophone",777:"scabbard",778:"scale, weighing machine",779:"school bus",780:"schooner",781:"scoreboard",782:"screen, CRT screen",783:"screw",784:"screwdriver",785:"seat belt, seatbelt",786:"sewing machine",787:"shield, buckler",788:"shoe shop, shoe-shop, shoe store",789:"shoji",790:"shopping basket",791:"shopping cart",792:"shovel",793:"shower cap",794:"shower curtain",795:"ski",796:"ski mask",797:"sleeping bag",798:"slide rule, slipstick",799:"sliding door",800:"slot, one-armed bandit",801:"snorkel",802:"snowmobile",803:"snowplow, snowplough",804:"soap dispenser",805:"soccer ball",806:"sock",807:"solar dish, solar collector, solar furnace",808:"sombrero",809:"soup bowl",810:"space bar",811:"space heater",812:"space shuttle",813:"spatula",814:"speedboat",815:"spider web, spider's web",816:"spindle",817:"sports car, sport car",818:"spotlight, spot",819:"stage",820:"steam locomotive",821:"steel arch bridge",822:"steel drum",823:"stethoscope",824:"stole",825:"stone wall",826:"stopwatch, stop watch",827:"stove",828:"strainer",829:"streetcar, tram, tramcar, trolley, trolley car",830:"stretcher",831:"studio couch, day bed",832:"stupa, tope",833:"submarine, pigboat, sub, U-boat",834:"suit, suit of clothes",835:"sundial",836:"sunglass",837:"sunglasses, dark glasses, shades",838:"sunscreen, sunblock, sun blocker",839:"suspension bridge",840:"swab, swob, mop",841:"sweatshirt",842:"swimming trunks, bathing trunks",843:"swing",844:"switch, electric switch, electrical switch",845:"syringe",846:"table lamp",847:"tank, army tank, armored combat vehicle, armoured combat vehicle",848:"tape player",849:"teapot",850:"teddy, teddy bear",851:"television, television system",852:"tennis ball",853:"thatch, thatched roof",854:"theater curtain, theatre curtain",855:"thimble",856:"thresher, thrasher, threshing machine",857:"throne",858:"tile roof",859:"toaster",860:"tobacco shop, tobacconist shop, tobacconist",861:"toilet seat",862:"torch",863:"totem pole",864:"tow truck, tow car, wrecker",865:"toyshop",866:"tractor",867:"trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",868:"tray",869:"trench coat",870:"tricycle, trike, velocipede",871:"trimaran",872:"tripod",873:"triumphal arch",874:"trolleybus, trolley coach, trackless trolley",875:"trombone",876:"tub, vat",877:"turnstile",878:"typewriter keyboard",879:"umbrella",880:"unicycle, monocycle",881:"upright, upright piano",882:"vacuum, vacuum cleaner",883:"vase",884:"vault",885:"velvet",886:"vending machine",887:"vestment",888:"viaduct",889:"violin, fiddle",890:"volleyball",891:"waffle iron",892:"wall clock",893:"wallet, billfold, notecase, pocketbook",894:"wardrobe, closet, press",895:"warplane, military plane",896:"washbasin, handbasin, washbowl, lavabo, wash-hand basin",897:"washer, automatic washer, washing machine",898:"water bottle",899:"water jug",900:"water tower",901:"whiskey jug",902:"whistle",903:"wig",904:"window screen",905:"window shade",906:"Windsor tie",907:"wine bottle",908:"wing",909:"wok",910:"wooden spoon",911:"wool, woolen, woollen",912:"worm fence, snake fence, snake-rail fence, Virginia fence",913:"wreck",914:"yawl",915:"yurt",916:"web site, website, internet site, site",917:"comic book",918:"crossword puzzle, crossword",919:"street sign",920:"traffic light, traffic signal, stoplight",921:"book jacket, dust cover, dust jacket, dust wrapper",922:"menu",923:"plate",924:"guacamole",925:"consomme",926:"hot pot, hotpot",927:"trifle",928:"ice cream, icecream",929:"ice lolly, lolly, lollipop, popsicle",930:"French loaf",931:"bagel, beigel",932:"pretzel",933:"cheeseburger",934:"hotdog, hot dog, red hot",935:"mashed potato",936:"head cabbage",937:"broccoli",938:"cauliflower",939:"zucchini, courgette",940:"spaghetti squash",941:"acorn squash",942:"butternut squash",943:"cucumber, cuke",944:"artichoke, globe artichoke",945:"bell pepper",946:"cardoon",947:"mushroom",948:"Granny Smith",949:"strawberry",950:"orange",951:"lemon",952:"fig",953:"pineapple, ananas",954:"banana",955:"jackfruit, jak, jack",956:"custard apple",957:"pomegranate",958:"hay",959:"carbonara",960:"chocolate sauce, chocolate syrup",961:"dough",962:"meat loaf, meatloaf",963:"pizza, pizza pie",964:"potpie",965:"burrito",966:"red wine",967:"espresso",968:"cup",969:"eggnog",970:"alp",971:"bubble",972:"cliff, drop, drop-off",973:"coral reef",974:"geyser",975:"lakeside, lakeshore",976:"promontory, headland, head, foreland",977:"sandbar, sand bar",978:"seashore, coast, seacoast, sea-coast",979:"valley, vale",980:"volcano",981:"ballplayer, baseball player",982:"groom, bridegroom",983:"scuba diver",984:"rapeseed",985:"daisy",986:"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",987:"corn",988:"acorn",989:"hip, rose hip, rosehip",990:"buckeye, horse chestnut, conker",991:"coral fungus",992:"agaric",993:"gyromitra",994:"stinkhorn, carrion fungus",995:"earthstar",996:"hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",997:"bolete",998:"ear, spike, capitulum",999:"toilet tissue, toilet paper, bathroom tissue"},IMAGE_SIZE=224,EMBEDDING_NODES={"1.00":"module_apply_default/MobilenetV1/Logits/global_pool","2.00":"module_apply_default/MobilenetV2/Logits/AvgPool"},MODEL_INFO={"1.00":{.25:{url:"https://tfhub.dev/google/imagenet/mobilenet_v1_025_224/classification/1",inputRange:[0,1]},"0.50":{url:"https://tfhub.dev/google/imagenet/mobilenet_v1_050_224/classification/1",inputRange:[0,1]},.75:{url:"https://tfhub.dev/google/imagenet/mobilenet_v1_075_224/classification/1",inputRange:[0,1]},"1.00":{url:"https://tfhub.dev/google/imagenet/mobilenet_v1_100_224/classification/1",inputRange:[0,1]}},"2.00":{"0.50":{url:"https://tfhub.dev/google/imagenet/mobilenet_v2_050_224/classification/2",inputRange:[0,1]},.75:{url:"https://tfhub.dev/google/imagenet/mobilenet_v2_075_224/classification/2",inputRange:[0,1]},"1.00":{url:"https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/2",inputRange:[0,1]}}};function load(e){return void 0===e&&(e={version:1,alpha:1}),__awaiter(this,void 0,void 0,function(){var a,r,o,i,t,n;return __generator(this,function(l){switch(l.label){case 0:if(null==_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");if(r=e.version.toFixed(2),o=e.alpha?e.alpha.toFixed(2):"",i=-1,t=1,null==e.modelUrl){if(!(r in MODEL_INFO))throw new Error("Invalid version of MobileNet. Valid versions are: "+Object.keys(MODEL_INFO));if(!(o in MODEL_INFO[r]))throw new Error("MobileNet constructed with invalid alpha "+e.alpha+". Valid multipliers for this version are: "+Object.keys(MODEL_INFO[r])+".");a=MODEL_INFO[r][o].inputRange,i=a[0],t=a[1]}return[4,(n=new MobileNetImpl(r,o,e.modelUrl,i,t)).load()];case 1:return l.sent(),[2,n]}})})}var MobileNetImpl=function(){function e(e,a,r,o,i){void 0===o&&(o=-1),void 0===i&&(i=1),this.version=e,this.alpha=a,this.modelUrl=r,this.inputMin=o,this.inputMax=i,this.inputRange=i-o}return e.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var e,a,r,o,i=this;return __generator(this,function(t){switch(t.label){case 0:return this.modelUrl?(e=this,[4,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__[/* loadGraphModel */ "c"])(this.modelUrl)]):[3,2];case 1:return e.model=t.sent(),[3,4];case 2:return a=MODEL_INFO[this.version][this.alpha].url,r=this,[4,Object(_tensorflow_tfjs_converter__WEBPACK_IMPORTED_MODULE_0__[/* loadGraphModel */ "c"])(a,{fromTFHub:!0})];case 3:r.model=t.sent(),t.label=4;case 4:return[4,(o=Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tidy"])(function(){return i.model.predict(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["zeros"])([1,IMAGE_SIZE,IMAGE_SIZE,3]))})).data()];case 5:return t.sent(),o.dispose(),[2]}})})},e.prototype.infer=function(e,a){var r=this;return void 0===a&&(a=!1),Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["tidy"])(function(){e instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["Tensor"]||(e=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["browser"].fromPixels(e));var o=e.toFloat().mul(r.inputRange).add(r.inputMin),i=o;if(e.shape[0]!==IMAGE_SIZE||e.shape[1]!==IMAGE_SIZE){i=_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_1__["image"].resizeBilinear(o,[IMAGE_SIZE,IMAGE_SIZE],!0)}var t,n=i.reshape([-1,IMAGE_SIZE,IMAGE_SIZE,3]);if(a){var l=EMBEDDING_NODES[r.version];t=r.model.execute(n,l).squeeze([1,2])}else{t=r.model.predict(n).slice([0,1],[-1,1e3])}return t})},e.prototype.classify=function(e,a){return void 0===a&&(a=3),__awaiter(this,void 0,void 0,function(){var r,o;return __generator(this,function(i){switch(i.label){case 0:return[4,getTopKClasses(r=this.infer(e),a)];case 1:return o=i.sent(),r.dispose(),[2,o]}})})},e}();function getTopKClasses(e,a){return __awaiter(this,void 0,void 0,function(){var r,o,i,t,n,l,s;return __generator(this,function(c){switch(c.label){case 0:return[4,(r=e.softmax()).data()];case 1:for(o=c.sent(),r.dispose(),i=[],s=0;s<o.length;s++)i.push({value:o[s],index:s});for(i.sort(function(e,a){return a.value-e.value}),t=new Float32Array(a),n=new Int32Array(a),s=0;s<a;s++)t[s]=i[s].value,n[s]=i[s].index;for(l=[],s=0;s<n.length;s++)l.push({className:IMAGENET_CLASSES[n[s]],probability:t[s]});return[2,l]}})})}
/***/ }),
/* 383 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Cancel = __webpack_require__(211);
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 386 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/ }),
/* 389 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ }),
/* 390 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isAbsoluteURL = __webpack_require__(389);
var combineURLs = __webpack_require__(388);
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
/***/ }),
/* 391 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
/***/ }),
/* 392 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var createError = __webpack_require__(213);
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
/***/ }),
/* 393 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/* 394 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ }),
/* 395 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
var transformData = __webpack_require__(394);
var isCancel = __webpack_require__(216);
var defaults = __webpack_require__(215);
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData(
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData(
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/ }),
/* 396 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
var buildURL = __webpack_require__(217);
var InterceptorManager = __webpack_require__(396);
var dispatchRequest = __webpack_require__(395);
var mergeConfig = __webpack_require__(212);
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
/***/ }),
/* 398 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(28);
var bind = __webpack_require__(218);
var Axios = __webpack_require__(397);
var mergeConfig = __webpack_require__(212);
var defaults = __webpack_require__(215);
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = __webpack_require__(211);
axios.CancelToken = __webpack_require__(384);
axios.isCancel = __webpack_require__(216);
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(383);
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
/***/ }),
/* 399 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $defineProperty = __webpack_require__(39);
var createDesc = __webpack_require__(108);
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ctx = __webpack_require__(56);
var $export = __webpack_require__(23);
var toObject = __webpack_require__(65);
var call = __webpack_require__(230);
var isArrayIter = __webpack_require__(229);
var toLength = __webpack_require__(122);
var createProperty = __webpack_require__(399);
var getIterFn = __webpack_require__(150);
$export($export.S + $export.F * !__webpack_require__(223)(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(85);
__webpack_require__(400);
module.exports = __webpack_require__(18).Array.from;
/***/ }),
/* 402 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(145)('observable');
/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(145)('asyncIterator');
/***/ }),
/* 404 */
/***/ (function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(66);
var gOPN = __webpack_require__(220).f;
var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(88);
var gOPS = __webpack_require__(157);
var pIE = __webpack_require__(105);
module.exports = function (it) {
var result = getKeys(it);
var getSymbols = gOPS.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = pIE.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
/***/ }),
/* 406 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// ECMAScript 6 symbols shim
var global = __webpack_require__(26);
var has = __webpack_require__(67);
var DESCRIPTORS = __webpack_require__(32);
var $export = __webpack_require__(23);
var redefine = __webpack_require__(234);
var META = __webpack_require__(146).KEY;
var $fails = __webpack_require__(68);
var shared = __webpack_require__(159);
var setToStringTag = __webpack_require__(102);
var uid = __webpack_require__(121);
var wks = __webpack_require__(25);
var wksExt = __webpack_require__(147);
var wksDefine = __webpack_require__(145);
var enumKeys = __webpack_require__(405);
var isArray = __webpack_require__(221);
var anObject = __webpack_require__(48);
var isObject = __webpack_require__(38);
var toObject = __webpack_require__(65);
var toIObject = __webpack_require__(66);
var toPrimitive = __webpack_require__(164);
var createDesc = __webpack_require__(108);
var _create = __webpack_require__(117);
var gOPNExt = __webpack_require__(404);
var $GOPD = __webpack_require__(219);
var $GOPS = __webpack_require__(157);
var $DP = __webpack_require__(39);
var $keys = __webpack_require__(88);
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if (has(AllSymbols, key)) {
if (!D.enumerable) {
if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
anObject(it);
var keys = enumKeys(P = toIObject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = toIObject(it);
key = toPrimitive(key, true);
if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN(toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto) $set.call(OPSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(220).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(105).f = $propertyIsEnumerable;
$GOPS.f = $getOwnPropertySymbols;
if (DESCRIPTORS && !__webpack_require__(106)) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function (name) {
return wrap(wks(name));
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });
$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return $GOPS.f(toObject(it));
}
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(60)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ }),
/* 407 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(406);
__webpack_require__(153);
__webpack_require__(403);
__webpack_require__(402);
module.exports = __webpack_require__(18).Symbol;
/***/ }),
/* 408 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(407), __esModule: true };
/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(85);
__webpack_require__(101);
module.exports = __webpack_require__(147).f('iterator');
/***/ }),
/* 410 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(409), __esModule: true };
/***/ }),
/* 411 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = __webpack_require__(14);
var _typeof3 = _interopRequireDefault(_typeof2);
var _from = __webpack_require__(47);
var _from2 = _interopRequireDefault(_from);
var _promise = __webpack_require__(24);
var _promise2 = _interopRequireDefault(_promise);
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _axios = __webpack_require__(55);
var _axios2 = _interopRequireDefault(_axios);
var _mobilenet = __webpack_require__(382);
var mobilenet = _interopRequireWildcard(_mobilenet);
var _darknet = __webpack_require__(381);
var darknet = _interopRequireWildcard(_darknet);
var _doodlenet = __webpack_require__(379);
var doodlenet = _interopRequireWildcard(_doodlenet);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
var _imageUtilities = __webpack_require__(46);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line no-unused-vars
var DEFAULTS = {
mobilenet: {
version: 2,
alpha: 1.0,
topk: 3
}
}; // Copyright (c) 2019 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
Image Classifier using pre-trained networks
*/
var IMAGE_SIZE = 224;
var MODEL_OPTIONS = ["mobilenet", "darknet", "darknet-tiny", "doodlenet"];
var ImageClassifier = function () {
/**
* Create an ImageClassifier.
* @param {string} modelNameOrUrl - The name or the URL of the model to use. Current model name options
* are: 'mobilenet', 'darknet', 'darknet-tiny', and 'doodlenet'.
* @param {HTMLVideoElement} video - An HTMLVideoElement.
* @param {object} options - An object with options.
* @param {function} callback - A callback to be called when the model is ready.
*/
function ImageClassifier(modelNameOrUrl, video, options, callback) {
(0, _classCallCheck3.default)(this, ImageClassifier);
this.video = video;
this.model = null;
this.mapStringToIndex = [];
if (typeof modelNameOrUrl === "string") {
if (MODEL_OPTIONS.includes(modelNameOrUrl)) {
this.modelName = modelNameOrUrl;
this.modelUrl = null;
switch (this.modelName) {
case "mobilenet":
this.modelToUse = mobilenet;
this.version = options.version || DEFAULTS.mobilenet.version;
this.alpha = options.alpha || DEFAULTS.mobilenet.alpha;
this.topk = options.topk || DEFAULTS.mobilenet.topk;
break;
case "darknet":
this.version = "reference"; // this a 28mb model
this.modelToUse = darknet;
break;
case "darknet-tiny":
this.version = "tiny"; // this a 4mb model
this.modelToUse = darknet;
break;
case "doodlenet":
this.modelToUse = doodlenet;
break;
default:
this.modelToUse = null;
}
} else {
this.modelUrl = modelNameOrUrl;
}
}
// Load the model
this.ready = (0, _callcallback2.default)(this.loadModel(this.modelUrl), callback);
}
/**
* Load the model and set it to this.model
* @return {this} The ImageClassifier.
*/
(0, _createClass3.default)(ImageClassifier, [{
key: "loadModel",
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(modelUrl) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!modelUrl) {
_context.next = 6;
break;
}
_context.next = 3;
return this.loadModelFrom(modelUrl);
case 3:
this.model = _context.sent;
_context.next = 9;
break;
case 6:
_context.next = 8;
return this.modelToUse.load({ version: this.version, alpha: this.alpha });
case 8:
this.model = _context.sent;
case 9:
return _context.abrupt("return", this);
case 10:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel(_x) {
return _ref.apply(this, arguments);
}
return loadModel;
}()
}, {
key: "loadModelFrom",
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var data, result, split, prefix, metadataUrl, metadataResponse, metadata;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
data = void 0;
if (!(path !== null)) {
_context2.next = 7;
break;
}
_context2.next = 5;
return _axios2.default.get(path);
case 5:
result = _context2.sent;
// eslint-disable-next-line prefer-destructuring
data = result.data;
case 7:
if (data.ml5Specs) {
this.mapStringToIndex = data.ml5Specs.mapStringToIndex;
}
if (!(this.mapStringToIndex.length === 0)) {
_context2.next = 16;
break;
}
split = path.split("/");
prefix = split.slice(0, split.length - 1).join("/");
metadataUrl = prefix + "/metadata.json";
_context2.next = 14;
return _axios2.default.get(metadataUrl).catch(function (metadataError) {
console.log("Tried to fetch metadata.json, but it seems to be missing.", metadataError);
});
case 14:
metadataResponse = _context2.sent;
if (metadataResponse) {
metadata = metadataResponse.data;
if (metadata.labels) {
this.mapStringToIndex = metadata.labels;
}
}
case 16:
_context2.next = 18;
return tf.loadLayersModel(path);
case 18:
this.model = _context2.sent;
return _context2.abrupt("return", this.model);
case 22:
_context2.prev = 22;
_context2.t0 = _context2["catch"](0);
console.error(_context2.t0);
return _context2.abrupt("return", _context2.t0);
case 26:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[0, 22]]);
}));
function loadModelFrom() {
return _ref2.apply(this, arguments);
}
return loadModelFrom;
}()
/**
* Classifies the given input and returns an object with labels and confidence
* @param {HTMLImageElement | HTMLCanvasElement | HTMLVideoElement} imgToPredict -
* takes an image to run the classification on.
* @param {number} numberOfClasses - a number of labels to return for the image
* classification.
* @return {object} an object with {label, confidence}.
*/
}, {
key: "classifyInternal",
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(imgToPredict, numberOfClasses) {
var _this = this;
var video, imageResize, predictedClasses, _results, processedImg, results;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.ready;
case 2:
_context3.next = 4;
return tf.nextFrame();
case 4:
if (!(imgToPredict instanceof HTMLVideoElement && imgToPredict.readyState === 0)) {
_context3.next = 8;
break;
}
video = imgToPredict;
// Wait for the video to be ready
_context3.next = 8;
return new _promise2.default(function (resolve) {
video.onloadeddata = function () {
return resolve();
};
});
case 8:
if (!(this.video && this.video.readyState === 0)) {
_context3.next = 11;
break;
}
_context3.next = 11;
return new _promise2.default(function (resolve) {
_this.video.onloadeddata = function () {
return resolve();
};
});
case 11:
// Process the images
imageResize = [IMAGE_SIZE, IMAGE_SIZE];
if (!this.modelUrl) {
_context3.next = 20;
break;
}
_context3.next = 15;
return tf.nextFrame();
case 15:
predictedClasses = tf.tidy(function () {
var processedImg = (0, _imageUtilities.imgToTensor)(imgToPredict, imageResize);
var predictions = _this.model.predict(processedImg);
return (0, _from2.default)(predictions.as1D().dataSync());
});
_context3.next = 18;
return predictedClasses.map(function (confidence, index) {
var label = _this.mapStringToIndex.length > 0 && _this.mapStringToIndex[index] ? _this.mapStringToIndex[index] : index;
return {
label: label,
confidence: confidence
};
}).sort(function (a, b) {
return b.confidence - a.confidence;
});
case 18:
_results = _context3.sent;
return _context3.abrupt("return", _results);
case 20:
processedImg = (0, _imageUtilities.imgToTensor)(imgToPredict, imageResize);
results = this.model.classify(processedImg, numberOfClasses).then(function (classes) {
return classes.map(function (c) {
return { label: c.className, confidence: c.probability };
});
});
processedImg.dispose();
return _context3.abrupt("return", results);
case 24:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function classifyInternal(_x3, _x4) {
return _ref3.apply(this, arguments);
}
return classifyInternal;
}()
/**
* Classifies the given input and takes a callback to handle the results
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} inputNumOrCallback -
* takes any of the following params
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} numOrCallback -
* takes any of the following params
* @param {function} cb - a callback function that handles the results of the function.
* @return {function} a promise or the results of a given callback, cb.
*/
}, {
key: "classify",
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(inputNumOrCallback) {
var numOrCallback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var cb = arguments[2];
var imgToPredict, numberOfClasses, callback;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
imgToPredict = this.video;
numberOfClasses = this.topk;
callback = void 0;
// Handle the image to predict
if (!(typeof inputNumOrCallback === "function")) {
_context4.next = 8;
break;
}
imgToPredict = this.video;
callback = inputNumOrCallback;
_context4.next = 27;
break;
case 8:
if (!(typeof inputNumOrCallback === "number")) {
_context4.next = 13;
break;
}
imgToPredict = this.video;
numberOfClasses = inputNumOrCallback;
_context4.next = 27;
break;
case 13:
if (!(inputNumOrCallback instanceof HTMLVideoElement || inputNumOrCallback instanceof HTMLImageElement || inputNumOrCallback instanceof HTMLCanvasElement || inputNumOrCallback instanceof ImageData)) {
_context4.next = 17;
break;
}
imgToPredict = inputNumOrCallback;
_context4.next = 27;
break;
case 17:
if (!((typeof inputNumOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(inputNumOrCallback)) === "object" && (inputNumOrCallback.elt instanceof HTMLVideoElement || inputNumOrCallback.elt instanceof HTMLImageElement || inputNumOrCallback.elt instanceof HTMLCanvasElement || inputNumOrCallback.elt instanceof ImageData))) {
_context4.next = 21;
break;
}
imgToPredict = inputNumOrCallback.elt; // Handle p5.js image
_context4.next = 27;
break;
case 21:
if (!((typeof inputNumOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(inputNumOrCallback)) === "object" && inputNumOrCallback.canvas instanceof HTMLCanvasElement)) {
_context4.next = 25;
break;
}
imgToPredict = inputNumOrCallback.canvas; // Handle p5.js image
_context4.next = 27;
break;
case 25:
if (this.video instanceof HTMLVideoElement) {
_context4.next = 27;
break;
}
throw new Error("No input image provided. If you want to classify a video, pass the video element in the constructor. ");
case 27:
if (typeof numOrCallback === "number") {
numberOfClasses = numOrCallback;
} else if (typeof numOrCallback === "function") {
callback = numOrCallback;
}
if (typeof cb === "function") {
callback = cb;
}
return _context4.abrupt("return", (0, _callcallback2.default)(this.classifyInternal(imgToPredict, numberOfClasses), callback));
case 30:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function classify(_x6) {
return _ref4.apply(this, arguments);
}
return classify;
}()
/**
* Will be deprecated soon in favor of ".classify()" - does the same as .classify()
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} inputNumOrCallback - takes any of the following params
* @param {HTMLImageElement | HTMLCanvasElement | object | function | number} numOrCallback - takes any of the following params
* @param {function} cb - a callback function that handles the results of the function.
* @return {function} a promise or the results of a given callback, cb.
*/
}, {
key: "predict",
value: function () {
var _ref5 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee5(inputNumOrCallback, numOrCallback, cb) {
return _regenerator2.default.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
return _context5.abrupt("return", this.classify(inputNumOrCallback, numOrCallback || null, cb));
case 1:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function predict(_x7, _x8, _x9) {
return _ref5.apply(this, arguments);
}
return predict;
}()
}]);
return ImageClassifier;
}();
var imageClassifier = function imageClassifier(modelName, videoOrOptionsOrCallback, optionsOrCallback, cb) {
var video = void 0;
var options = {};
var callback = cb;
var model = modelName;
if (typeof model !== "string") {
throw new Error('Please specify a model to use. E.g: "MobileNet"');
} else if (model.indexOf("http") === -1) {
model = modelName.toLowerCase();
}
if (videoOrOptionsOrCallback instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback;
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object" && videoOrOptionsOrCallback.elt instanceof HTMLVideoElement) {
video = videoOrOptionsOrCallback.elt; // Handle a p5.js video element
} else if ((typeof videoOrOptionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(videoOrOptionsOrCallback)) === "object") {
options = videoOrOptionsOrCallback;
} else if (typeof videoOrOptionsOrCallback === "function") {
callback = videoOrOptionsOrCallback;
}
if ((typeof optionsOrCallback === "undefined" ? "undefined" : (0, _typeof3.default)(optionsOrCallback)) === "object") {
options = optionsOrCallback;
} else if (typeof optionsOrCallback === "function") {
callback = optionsOrCallback;
}
var instance = new ImageClassifier(model, video, options, callback);
return callback ? instance : instance.ready;
};
exports.default = imageClassifier;
/***/ }),
/* 412 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(23);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(32), 'Object', { defineProperty: __webpack_require__(39).f });
/***/ }),
/* 413 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(412);
var $Object = __webpack_require__(18).Object;
module.exports = function defineProperty(it, key, desc) {
return $Object.defineProperty(it, key, desc);
};
/***/ }),
/* 414 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-promise-try
var $export = __webpack_require__(23);
var newPromiseCapability = __webpack_require__(149);
var perform = __webpack_require__(226);
$export($export.S, 'Promise', { 'try': function (callbackfn) {
var promiseCapability = newPromiseCapability.f(this);
var result = perform(callbackfn);
(result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
return promiseCapability.promise;
} });
/***/ }),
/* 415 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-promise-finally
var $export = __webpack_require__(23);
var core = __webpack_require__(18);
var global = __webpack_require__(26);
var speciesConstructor = __webpack_require__(228);
var promiseResolve = __webpack_require__(225);
$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
var C = speciesConstructor(this, core.Promise || global.Promise);
var isFunction = typeof onFinally == 'function';
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
} });
/***/ }),
/* 416 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(26);
var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';
/***/ }),
/* 417 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(26);
var macrotask = __webpack_require__(227).set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = __webpack_require__(107)(process) == 'process';
module.exports = function () {
var head, last, notify;
var flush = function () {
var parent, fn;
if (isNode && (parent = process.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (e) {
if (head) notify();
else last = undefined;
throw e;
}
} last = undefined;
if (parent) parent.enter();
};
// Node.js
if (isNode) {
notify = function () {
process.nextTick(flush);
};
// browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
} else if (Observer && !(global.navigator && global.navigator.standalone)) {
var toggle = true;
var node = document.createTextNode('');
new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (Promise && Promise.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
var promise = Promise.resolve(undefined);
notify = function () {
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
};
/***/ }),
/* 418 */
/***/ (function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
var un = that === undefined;
switch (args.length) {
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(106);
var global = __webpack_require__(26);
var ctx = __webpack_require__(56);
var classof = __webpack_require__(116);
var $export = __webpack_require__(23);
var isObject = __webpack_require__(38);
var aFunction = __webpack_require__(109);
var anInstance = __webpack_require__(151);
var forOf = __webpack_require__(100);
var speciesConstructor = __webpack_require__(228);
var task = __webpack_require__(227).set;
var microtask = __webpack_require__(417)();
var newPromiseCapabilityModule = __webpack_require__(149);
var perform = __webpack_require__(226);
var userAgent = __webpack_require__(416);
var promiseResolve = __webpack_require__(225);
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var FakePromise = (promise.constructor = {})[__webpack_require__(25)('species')] = function (exec) {
exec(empty, empty);
};
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function')
&& promise.then(empty) instanceof FakePromise
// v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// we can't detect it synchronously, so just check versions
&& v8.indexOf('6.6') !== 0
&& userAgent.indexOf('Chrome/66') === -1;
} catch (e) { /* empty */ }
}();
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // may throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (e) {
if (domain && !exited) domain.exit();
reject(e);
}
};
while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if (isReject && !promise._h) onUnhandled(promise);
});
};
var onUnhandled = function (promise) {
task.call(global, function () {
var value = promise._v;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = perform(function () {
if (isNode) {
process.emit('unhandledRejection', value, promise);
} else if (handler = global.onunhandledrejection) {
handler({ promise: promise, reason: value });
} else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global, function () {
var handler;
if (isNode) {
process.emit('rejectionHandled', promise);
} else if (handler = global.onrejectionhandled) {
handler({ promise: promise, reason: promise._v });
}
});
};
var $reject = function (value) {
var promise = this;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function (value) {
var promise = this;
var then;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if (promise === value) throw TypeError("Promise can't be resolved itself");
if (then = isThenable(value)) {
microtask(function () {
var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch (e) {
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch (e) {
$reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch (err) {
$reject.call(this, err);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(148)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected) {
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if (this._a) this._a.push(reaction);
if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__(102)($Promise, PROMISE);
__webpack_require__(224)(PROMISE);
Wrapper = __webpack_require__(18)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r) {
var capability = newPromiseCapability(this);
var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(223)(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
/***/ }),
/* 420 */
/***/ (function(module, exports) {
module.exports = function () { /* empty */ };
/***/ }),
/* 421 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var addToUnscopables = __webpack_require__(420);
var step = __webpack_require__(231);
var Iterators = __webpack_require__(84);
var toIObject = __webpack_require__(66);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(152)(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(39);
var anObject = __webpack_require__(48);
var getKeys = __webpack_require__(88);
module.exports = __webpack_require__(32) ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ }),
/* 423 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var create = __webpack_require__(117);
var descriptor = __webpack_require__(108);
var setToStringTag = __webpack_require__(102);
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(60)(IteratorPrototype, __webpack_require__(25)('iterator'), function () { return this; });
module.exports = function (Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ }),
/* 424 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(161);
var defined = __webpack_require__(162);
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ }),
/* 425 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(153);
__webpack_require__(85);
__webpack_require__(101);
__webpack_require__(419);
__webpack_require__(415);
__webpack_require__(414);
module.exports = __webpack_require__(18).Promise;
/***/ }),
/* 426 */
/***/ (function(module, exports) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
!(function(global) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
runtime.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
resolve(result);
}, reject);
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
if (delegate.iterator.return) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
})(
// In sloppy mode, unbound `this` refers to the global object, fallback to
// Function constructor if we're in global strict mode. That is sadly a form
// of indirect eval which violates Content Security Policy.
(function() { return this })() || Function("return this")()
);
/***/ }),
/* 427 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// This method of obtaining a reference to the global object needs to be
// kept identical to the way it is obtained in runtime.js
var g = (function() { return this })() || Function("return this")();
// Use `getOwnPropertyNames` because not all browsers support calling
// `hasOwnProperty` on the global `self` object in a worker. See #183.
var hadRuntime = g.regeneratorRuntime &&
Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0;
// Save the old regeneratorRuntime in case it needs to be restored later.
var oldRuntime = hadRuntime && g.regeneratorRuntime;
// Force reevalutation of runtime.js.
g.regeneratorRuntime = undefined;
module.exports = __webpack_require__(426);
if (hadRuntime) {
// Restore the original runtime.
g.regeneratorRuntime = oldRuntime;
} else {
// Remove the global property added by runtime.js.
try {
delete g.regeneratorRuntime;
} catch(e) {
g.regeneratorRuntime = undefined;
}
}
/***/ }),
/* 428 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _regenerator = __webpack_require__(9);
var _regenerator2 = _interopRequireDefault(_regenerator);
var _asyncToGenerator2 = __webpack_require__(8);
var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
var _classCallCheck2 = __webpack_require__(7);
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = __webpack_require__(10);
var _createClass3 = _interopRequireDefault(_createClass2);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _callcallback = __webpack_require__(15);
var _callcallback2 = _interopRequireDefault(_callcallback);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
/*
Crepe Pitch Detection model
Based on https://github.com/marl/crepe/tree/gh-pages
Original model and code: https://marl.github.io/crepe/crepe.js
*/
var PitchDetection = function () {
/**
* Create a pitchDetection.
* @param {Object} model - The path to the trained model. Only CREPE is available for now. Case insensitive.
* @param {AudioContext} audioContext - The browser audioContext to use.
* @param {MediaStream} stream - The media stream to use.
* @param {function} callback - Optional. A callback to be called once the model has loaded. If no callback is provided, it will return a promise that will be resolved once the model has loaded.
*/
function PitchDetection(model, audioContext, stream, callback) {
(0, _classCallCheck3.default)(this, PitchDetection);
/**
* The pitch detection model.
* @type {model}
* @public
*/
this.model = model;
/**
* The AudioContext instance. Contains sampleRate, currentTime, state, baseLatency.
* @type {AudioContext}
* @public
*/
this.audioContext = audioContext;
/**
* The MediaStream instance. Contains an id and a boolean active value.
* @type {MediaStream}
* @public
*/
this.stream = stream;
this.frequency = null;
this.ready = (0, _callcallback2.default)(this.loadModel(model), callback);
}
(0, _createClass3.default)(PitchDetection, [{
key: 'loadModel',
value: function () {
var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(model) {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return tf.loadLayersModel(model + '/model.json');
case 2:
this.model = _context.sent;
if (!this.audioContext) {
_context.next = 8;
break;
}
_context.next = 6;
return this.processStream();
case 6:
_context.next = 9;
break;
case 8:
throw new Error('Could not access microphone - getUserMedia not available');
case 9:
return _context.abrupt('return', this);
case 10:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function loadModel(_x) {
return _ref.apply(this, arguments);
}
return loadModel;
}()
}, {
key: 'processStream',
value: function () {
var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2() {
var mic, minBufferSize, bufferSize, scriptNode, gain;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return tf.nextFrame();
case 2:
mic = this.audioContext.createMediaStreamSource(this.stream);
minBufferSize = this.audioContext.sampleRate / 16000 * 1024;
bufferSize = 4;
while (bufferSize < minBufferSize) {
bufferSize *= 2;
}scriptNode = this.audioContext.createScriptProcessor(bufferSize, 1, 1);
scriptNode.onaudioprocess = this.processMicrophoneBuffer.bind(this);
gain = this.audioContext.createGain();
gain.gain.setValueAtTime(0, this.audioContext.currentTime);
mic.connect(scriptNode);
scriptNode.connect(gain);
gain.connect(this.audioContext.destination);
if (this.audioContext.state !== 'running') {
console.warn('User gesture needed to start AudioContext, please click');
}
case 14:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function processStream() {
return _ref2.apply(this, arguments);
}
return processStream;
}()
}, {
key: 'processMicrophoneBuffer',
value: function () {
var _ref3 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee3(event) {
var _this = this;
return _regenerator2.default.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return tf.nextFrame();
case 2:
/**
* The current pitch prediction results from the classification model.
* @type {Object}
* @public
*/
this.results = {};
PitchDetection.resample(event.inputBuffer, function (resampled) {
tf.tidy(function () {
/**
* A boolean value stating whether the model instance is running or not.
* @type {boolean}
* @public
*/
var centMapping = tf.add(tf.linspace(0, 7180, 360), tf.tensor(1997.3794084376191));
_this.running = true;
var frame = tf.tensor(resampled.slice(0, 1024));
var zeromean = tf.sub(frame, tf.mean(frame));
var framestd = tf.tensor(tf.norm(zeromean).dataSync() / Math.sqrt(1024));
var normalized = tf.div(zeromean, framestd);
var input = normalized.reshape([1, 1024]);
var activation = _this.model.predict([input]).reshape([360]);
var confidence = activation.max().dataSync()[0];
var center = activation.argMax().dataSync()[0];
_this.results.confidence = confidence.toFixed(3);
var start = Math.max(0, center - 4);
var end = Math.min(360, center + 5);
var weights = activation.slice([start], [end - start]);
var cents = centMapping.slice([start], [end - start]);
var products = tf.mul(weights, cents);
var productSum = products.dataSync().reduce(function (a, b) {
return a + b;
}, 0);
var weightSum = weights.dataSync().reduce(function (a, b) {
return a + b;
}, 0);
var predictedCent = productSum / weightSum;
var predictedHz = 10 * Math.pow(2, predictedCent / 1200.0);
var frequency = confidence > 0.5 ? predictedHz : null;
_this.frequency = frequency;
});
});
case 4:
case 'end':
return _context3.stop();
}
}
}, _callee3, this);
}));
function processMicrophoneBuffer(_x2) {
return _ref3.apply(this, arguments);
}
return processMicrophoneBuffer;
}()
/**
* Returns the pitch from the model attempting to predict the pitch.
* @param {function} callback - Optional. A function to be called when the model has generated content. If no callback is provided, it will return a promise that will be resolved once the model has predicted the pitch.
* @returns {number}
*/
}, {
key: 'getPitch',
value: function () {
var _ref4 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee4(callback) {
var frequency;
return _regenerator2.default.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.ready;
case 2:
_context4.next = 4;
return tf.nextFrame();
case 4:
frequency = this.frequency;
if (callback) {
callback(undefined, frequency);
}
return _context4.abrupt('return', frequency);
case 7:
case 'end':
return _context4.stop();
}
}
}, _callee4, this);
}));
function getPitch(_x3) {
return _ref4.apply(this, arguments);
}
return getPitch;
}()
}], [{
key: 'resample',
value: function resample(audioBuffer, onComplete) {
var interpolate = audioBuffer.sampleRate % 16000 !== 0;
var multiplier = audioBuffer.sampleRate / 16000;
var original = audioBuffer.getChannelData(0);
var subsamples = new Float32Array(1024);
for (var i = 0; i < 1024; i += 1) {
if (!interpolate) {
subsamples[i] = original[i * multiplier];
} else {
var left = Math.floor(i * multiplier);
var right = left + 1;
var p = i * multiplier - left;
subsamples[i] = (1 - p) * original[left] + p * original[right];
}
}
onComplete(subsamples);
}
}]);
return PitchDetection;
}();
var pitchDetection = function pitchDetection() {
var modelPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : './';
var context = arguments[1];
var stream = arguments[2];
var callback = arguments[3];
return new PitchDetection(modelPath, context, stream, callback);
};
exports.default = pitchDetection;
/***/ }),
/* 429 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/** @license See the LICENSE file. */
Object.defineProperty(exports, "__esModule", { value: true });
// This code is auto-generated, do not modify this file!
const version = '1.4.0';
exports.version = version;
//# sourceMappingURL=version.js.map
/***/ }),
/* 430 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const histogram_1 = __webpack_require__(154);
const render_utils_1 = __webpack_require__(37);
const math_1 = __webpack_require__(119);
/**
* Shows a histogram with the distribution of all values in a given tensor.
*
* ```js
* const tensor = tf.tensor1d([0, 0, 0, 0, 2, 3, 4]);
*
* const surface = {name: 'Values Distribution', tab: 'Model Inspection'};
* await tfvis.show.valuesDistribution(surface, tensor);
* ```
*
*/
/**
* @doc {heading: 'Models & Tensors', subheading: 'Model Inspection', namespace:
* 'show'}
*/
function valuesDistribution(container, tensor) {
return __awaiter(this, void 0, void 0, function* () {
const drawArea = render_utils_1.getDrawArea(container);
const stats = yield math_1.tensorStats(tensor);
const values = yield tensor.data();
histogram_1.histogram(drawArea, values, { height: 150, stats });
});
}
exports.valuesDistribution = valuesDistribution;
//# sourceMappingURL=tensor.js.map
/***/ }),
/* 431 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const render_utils_1 = __webpack_require__(37);
const table_1 = __webpack_require__(118);
/**
* Renders a per class accuracy table for classification task evaluation
*
* ```js
* const labels = tf.tensor1d([0, 0, 1, 2, 2, 2]);
* const predictions = tf.tensor1d([0, 0, 0, 2, 1, 1]);
*
* const result = await tfvis.metrics.perClassAccuracy(labels, predictions);
* console.log(result)
*
* const container = {name: 'Per Class Accuracy', tab: 'Evaluation'};
* const categories = ['cat', 'dog', 'mouse'];
* await tfvis.show.perClassAccuracy(container, result, categories);
* ```
*
* @param container A `{name: string, tab?: string}` object specifying which
* surface to render to.
* @param classAccuracy An `Array<{accuracy: number, count: number}>` array with
* the accuracy data. See metrics.perClassAccuracy for details on how to
* generate this object.
* @param classLabels An array of string labels for the classes in
* `classAccuracy`. Optional.
*
*/
function showPerClassAccuracy(container, classAccuracy, classLabels) {
return __awaiter(this, void 0, void 0, function* () {
const drawArea = render_utils_1.getDrawArea(container);
const headers = [
'Class',
'Accuracy',
'# Samples',
];
const values = [];
for (let i = 0; i < classAccuracy.length; i++) {
const label = classLabels ? classLabels[i] : i.toString();
const classAcc = classAccuracy[i];
values.push([label, classAcc.accuracy, classAcc.count]);
}
return table_1.table(drawArea, { headers, values });
});
}
exports.showPerClassAccuracy = showPerClassAccuracy;
//# sourceMappingURL=quality.js.map
/***/ }),
/* 432 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const histogram_1 = __webpack_require__(154);
const render_utils_1 = __webpack_require__(37);
const table_1 = __webpack_require__(118);
const dom_1 = __webpack_require__(59);
const math_1 = __webpack_require__(119);
/**
* Renders a summary of a tf.Model. Displays a table with layer information.
*
* ```js
* const model = tf.sequential({
* layers: [
* tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'}),
* tf.layers.dense({units: 10, activation: 'softmax'}),
* ]
* });
*
* const surface = { name: 'Model Summary', tab: 'Model Inspection'};
* tfvis.show.modelSummary(surface, model);
* ```
*
*/
/**
* @doc {
* heading: 'Models & Tensors',
* subheading: 'Model Inspection',
* namespace: 'show'
* }
*/
function modelSummary(container, model) {
return __awaiter(this, void 0, void 0, function* () {
const drawArea = render_utils_1.getDrawArea(container);
const summary = getModelSummary(model);
const headers = [
'Layer Name',
'Output Shape',
'# Of Params',
'Trainable',
];
const values = summary.layers.map(l => [l.name,
l.outputShape,
l.parameters,
l.trainable,
]);
table_1.table(drawArea, { headers, values });
});
}
exports.modelSummary = modelSummary;
/**
* Renders summary information about a layer and a histogram of parameters in
* that layer.
*
* ```js
* const model = tf.sequential({
* layers: [
* tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'}),
* tf.layers.dense({units: 10, activation: 'softmax'}),
* ]
* });
*
* const surface = { name: 'Layer Summary', tab: 'Model Inspection'};
* tfvis.show.layer(surface, model.getLayer(undefined, 1));
* ```
*
*/
/**
* @doc {
* heading: 'Models & Tensors',
* subheading: 'Model Inspection',
* namespace: 'show'
* }
*/
function layer(container, layer) {
return __awaiter(this, void 0, void 0, function* () {
const drawArea = render_utils_1.getDrawArea(container);
const details = yield getLayerDetails(layer);
const headers = [
'Weight Name',
'Shape',
'Min',
'Max',
'# Params',
'# Zeros',
'# NaNs',
'# Infinity',
];
// Show layer summary
const weightsInfoSurface = dom_1.subSurface(drawArea, 'layer-weights-info');
const detailValues = details.map(l => [l.name, l.shape, l.stats.min, l.stats.max, l.weight.size,
l.stats.numZeros, l.stats.numNans, l.stats.numInfs]);
table_1.table(weightsInfoSurface, { headers, values: detailValues });
const histogramSelectorSurface = dom_1.subSurface(drawArea, 'select-layer');
const layerValuesHistogram = dom_1.subSurface(drawArea, 'param-distribution');
const handleSelection = (layerName) => __awaiter(this, void 0, void 0, function* () {
const layer = details.filter(d => d.name === layerName)[0];
const weights = yield layer.weight.data();
histogram_1.histogram(layerValuesHistogram, weights, { height: 150, width: 460, stats: false });
});
addHistogramSelector(details.map(d => d.name), histogramSelectorSurface, handleSelection);
});
}
exports.layer = layer;
//
// Helper functions
//
function getModelSummary(model) {
return {
layers: model.layers.map(getLayerSummary),
};
}
/*
* Gets summary information/metadata about a layer.
*/
function getLayerSummary(layer) {
let outputShape;
if (Array.isArray(layer.outputShape[0])) {
const shapes = layer.outputShape.map(s => formatShape(s));
outputShape = `[${shapes.join(', ')}]`;
}
else {
outputShape = formatShape(layer.outputShape);
}
return {
name: layer.name,
trainable: layer.trainable,
parameters: layer.countParams(),
outputShape,
};
}
/*
* Gets summary stats and shape for all weights in a layer.
*/
function getLayerDetails(layer) {
return __awaiter(this, void 0, void 0, function* () {
const weights = layer.getWeights();
const layerVariables = layer.weights;
const statsPromises = weights.map(math_1.tensorStats);
const stats = yield Promise.all(statsPromises);
const shapes = weights.map(w => w.shape);
return weights.map((weight, i) => ({
name: layerVariables[i].name,
stats: stats[i],
shape: formatShape(shapes[i]),
weight,
}));
});
}
function formatShape(shape) {
const oShape = shape.slice();
if (oShape.length === 0) {
return 'Scalar';
}
if (oShape[0] === null) {
oShape[0] = 'batch';
}
return `[${oShape.join(',')}]`;
}
function addHistogramSelector(items, parent,
// tslint:disable-next-line:no-any
selectionHandler) {
const select = `
<select>
${items.map((i) => `<option value=${i}>${i}</option>`)}
</select>
`;
const button = `<button>Show Values Distribution for:</button>`;
const content = `<div>${button}${select}</div>`;
parent.innerHTML = content;
// Add listeners
const buttonEl = parent.querySelector('button');
const selectEl = parent.querySelector('select');
buttonEl.addEventListener('click', () => {
selectionHandler(selectEl.selectedOptions[0].label);
});
}
//# sourceMappingURL=model.js.map
/***/ }),
/* 433 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const linechart_1 = __webpack_require__(235);
const render_utils_1 = __webpack_require__(37);
const dom_1 = __webpack_require__(59);
/**
* Renders a tf.Model training 'History'.
*
* ```js
* const model = tf.sequential({
* layers: [
* tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'}),
* tf.layers.dense({units: 10, activation: 'softmax'}),
* ]
* });
*
* model.compile({
* optimizer: 'sgd',
* loss: 'categoricalCrossentropy',
* metrics: ['accuracy']
* });
*
* const data = tf.randomNormal([100, 784]);
* const labels = tf.randomUniform([100, 10]);
*
* function onBatchEnd(batch, logs) {
* console.log('Accuracy', logs.acc);
* }
*
* const surface = { name: 'show.history', tab: 'Training' };
* // Train for 5 epochs with batch size of 32.
* const history = await model.fit(data, labels, {
* epochs: 5,
* batchSize: 32
* });
*
* tfvis.show.history(surface, history, ['loss', 'acc']);
* ```
*
* ```js
* const model = tf.sequential({
* layers: [
* tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'}),
* tf.layers.dense({units: 10, activation: 'softmax'}),
* ]
* });
*
* model.compile({
* optimizer: 'sgd',
* loss: 'categoricalCrossentropy',
* metrics: ['accuracy']
* });
*
* const data = tf.randomNormal([100, 784]);
* const labels = tf.randomUniform([100, 10]);
*
* function onBatchEnd(batch, logs) {
* console.log('Accuracy', logs.acc);
* }
*
* const surface = { name: 'show.history live', tab: 'Training' };
* // Train for 5 epochs with batch size of 32.
* const history = [];
* await model.fit(data, labels, {
* epochs: 5,
* batchSize: 32,
* callbacks: {
* onEpochEnd: (epoch, log) => {
* history.push(log);
* tfvis.show.history(surface, history, ['loss', 'acc']);
* }
* }
* });
* ```
*
* @param history A history like object. Either a tfjs-layers `History` object
* or an array of tfjs-layers `Logs` objects.
* @param metrics An array of strings for each metric to plot from the history
* object. Using this allows you to control which metrics appear on the same
* plot.
* @param opts Optional parameters for the line charts.
*/
/**
* @doc {heading: 'Models & Tensors', subheading: 'Model Training', namespace:
* 'show'}
*/
function history(container, history, metrics, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
// Get the draw surface
const drawArea = render_utils_1.getDrawArea(container);
// We organize the data from the history object into discrete plot data
// objects so that we can group together appropriate metrics into single
// multi-series charts.
const plots = {};
for (const metric of metrics) {
if (!(/val_/.test(metric))) {
// Non validation metric
const values = getValues(history, metric, metrics.indexOf(metric));
initPlot(plots, metric);
plots[metric].series.push(metric);
plots[metric].values.push(values);
}
else {
// Validation metrics are grouped with their equivalent non validation
// metrics. Note that the corresponding non validation metric may not
// actually be included but we still want to use it as a plot name.
const nonValidationMetric = metric.replace('val_', '');
initPlot(plots, nonValidationMetric);
const values = getValues(history, metric, metrics.indexOf(metric));
plots[nonValidationMetric].series.push(metric);
plots[nonValidationMetric].values.push(values);
}
}
// Render each plot specified above to a new subsurface.
// A plot may have multiple series.
const plotNames = Object.keys(plots);
const options = Object.assign({}, { xLabel: 'Iteration', yLabel: 'Value' }, opts);
const renderPromises = [];
for (const name of plotNames) {
const subContainer = dom_1.subSurface(drawArea, name);
const series = plots[name].series;
const values = plots[name].values;
if (series.every(seriesName => Boolean(seriesName.match('acc')))) {
// Set a domain of 0-1 if all the series in this plot are related to
// accuracy. Can be overridden by setting zoomToFitAccuracy to true.
if (options.zoomToFitAccuracy) {
options.zoomToFit = true;
}
else {
options.yAxisDomain = [0, 1];
delete options.zoomToFit;
}
}
const done = linechart_1.linechart(subContainer, { values, series }, options);
renderPromises.push(done);
}
yield Promise.all(renderPromises);
});
}
exports.history = history;
function initPlot(plot, name) {
if (plot[name] == null) {
plot[name] = { series: [], values: [] };
}
}
/*
* Extracts a list of Point2D's suitable for plotting from a HistoryLike for
* a single metric.
* @param history a HistoryLike object
* @param metric the metric to extract from the logs
* @param metricIndex this is needed because the historylike can be a nested
* list of logs for multiple metrics, this index lets us extract the correct
* list.
*/
function getValues(history, metric, metricIndex) {
if (Array.isArray(history)) {
// If we were passed a nested array we want to get the correct list
// for this given metric, metrix index gives us this list.
const metricHistory = (Array.isArray(history[0]) ? history[metricIndex] : history);
const points = [];
for (let i = 0; i < metricHistory.length; i++) {
const log = metricHistory[i];
points.push({ x: i, y: log[metric] });
}
return points;
}
else {
return history.history[metric].map((y, x) => ({ x, y }));
}
}
/**
* Returns a collection of callbacks to pass to tf.Model.fit. Callbacks are
* returned for the following events, `onBatchEnd` & `onEpochEnd`.
*
* ```js
* const model = tf.sequential({
* layers: [
* tf.layers.dense({inputShape: [784], units: 32, activation: 'relu'}),
* tf.layers.dense({units: 10, activation: 'softmax'}),
* ]
* });
*
* model.compile({
* optimizer: 'sgd',
* loss: 'categoricalCrossentropy',
* metrics: ['accuracy']
* });
*
* const data = tf.randomNormal([100, 784]);
* const labels = tf.randomUniform([100, 10]);
*
* function onBatchEnd(batch, logs) {
* console.log('Accuracy', logs.acc);
* }
*
* const surface = { name: 'show.fitCallbacks', tab: 'Training' };
* // Train for 5 epochs with batch size of 32.
* await model.fit(data, labels, {
* epochs: 5,
* batchSize: 32,
* callbacks: tfvis.show.fitCallbacks(surface, ['loss', 'acc']),
* });
* ```
*
* @param metrics List of metrics to plot.
* @param opts Optional parameters
*/
/**
* @doc {heading: 'Models & Tensors', subheading: 'Model Training', namespace:
* 'show'}
*/
function fitCallbacks(container, metrics, opts = {}) {
const accumulators = {};
const callbackNames = opts.callbacks || ['onEpochEnd', 'onBatchEnd'];
const drawArea = render_utils_1.getDrawArea(container);
const historyOpts = Object.assign({}, opts);
delete historyOpts.callbacks;
function makeCallbackFor(callbackName) {
return (_, log) => __awaiter(this, void 0, void 0, function* () {
// Set a nicer x axis name where possible
if ((/batch/i).test(callbackName)) {
historyOpts.xLabel = 'Batch';
}
else if ((/epoch/i).test(callbackName)) {
historyOpts.xLabel = 'Epoch';
}
// Because of how the _ (iteration) numbers are given in the layers api
// we have to store each metric for each callback in different arrays else
// we cannot get accurate 'global' batch numbers for onBatchEnd.
// However at render time we want to be able to combine metrics for a
// given callback. So here we make a nested list of metrics, the first
// level are arrays for each callback, the second level contains arrays
// (of logs) for each metric within that callback.
const metricLogs = [];
const presentMetrics = [];
for (const metric of metrics) {
// not all logs have all kinds of metrics.
if (log[metric] != null) {
presentMetrics.push(metric);
const accumulator = getAccumulator(accumulators, callbackName, metric);
accumulator.push({ [metric]: log[metric] });
metricLogs.push(accumulator);
}
}
const subContainer = dom_1.subSurface(drawArea, callbackName, { title: callbackName });
history(subContainer, metricLogs, presentMetrics, historyOpts);
yield render_utils_1.nextFrame();
});
}
const callbacks = {};
callbackNames.forEach((name) => {
callbacks[name] = makeCallbackFor(name);
});
return callbacks;
}
exports.fitCallbacks = fitCallbacks;
function getAccumulator(accumulators, callback, metric) {
if (accumulators[callback] == null) {
accumulators[callback] = {};
}
if (accumulators[callback][metric] == null) {
accumulators[callback][metric] = [];
}
return accumulators[callback][metric];
}
//# sourceMappingURL=history.js.map
/***/ }),
/* 434 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const vega_embed_1 = __importDefault(__webpack_require__(81));
const dom_1 = __webpack_require__(59);
const utils_1 = __webpack_require__(120);
const render_utils_1 = __webpack_require__(37);
/**
* Renders a scatter plot
*
* ```js
* const series1 = Array(100).fill(0)
* .map(y => Math.random() * 100 - (Math.random() * 50))
* .map((y, x) => ({ x, y, }));
*
* const series2 = Array(100).fill(0)
* .map(y => Math.random() * 100 - (Math.random() * 150))
* .map((y, x) => ({ x, y, }));
*
* const series = ['First', 'Second'];
* const data = { values: [series1, series2], series }
*
* const surface = { name: 'Scatterplot', tab: 'Charts' };
* tfvis.render.scatterplot(surface, data);
* ```
*
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function scatterplot(container, data, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
let _values = data.values;
const _series = data.series == null ? [] : data.series;
// Nest data if necessary before further processing
_values = Array.isArray(_values[0]) ? _values :
[_values];
const values = [];
_values.forEach((seriesData, i) => {
const seriesName = _series[i] != null ? _series[i] : `Series ${i + 1}`;
const seriesVals = seriesData.map(v => Object.assign({}, v, { series: seriesName }));
values.push(...seriesVals);
});
if (opts.seriesColors != null) {
utils_1.assert(opts.seriesColors.length === _values.length, 'Must have an equal number of series colors as there are data series');
}
const drawArea = render_utils_1.getDrawArea(container);
const options = Object.assign({}, defaultOpts, opts);
const embedOpts = {
actions: false,
mode: 'vega-lite',
defaultStyle: false,
};
const xDomain = () => {
if (options.zoomToFit) {
return { 'zero': false };
}
else if (options.xAxisDomain != null) {
return { 'domain': options.xAxisDomain };
}
return undefined;
};
const yDomain = () => {
if (options.zoomToFit) {
return { 'zero': false };
}
else if (options.yAxisDomain != null) {
return { 'domain': options.yAxisDomain };
}
return undefined;
};
const spec = {
'width': options.width || dom_1.getDefaultWidth(drawArea),
'height': options.height || dom_1.getDefaultHeight(drawArea),
'padding': 0,
'autosize': {
'type': 'fit',
'contains': 'padding',
'resize': true,
},
'config': {
'axis': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'text': { 'fontSize': options.fontSize },
'legend': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
}
},
'data': {
'values': values,
},
'mark': {
'type': 'point',
'clip': true,
'tooltip': { 'content': 'data' },
},
'encoding': {
'x': {
'field': 'x',
'type': options.xType,
'title': options.xLabel,
'scale': xDomain(),
},
'y': {
'field': 'y',
'type': options.yType,
'title': options.yLabel,
'scale': yDomain(),
},
'color': {
'field': 'series',
'type': 'nominal',
'scale': {
'range': options.seriesColors,
}
},
'shape': {
'field': 'series',
'type': 'nominal',
}
},
};
yield vega_embed_1.default(drawArea, spec, embedOpts);
return Promise.resolve();
});
}
exports.scatterplot = scatterplot;
const defaultOpts = {
xLabel: 'x',
yLabel: 'y',
xType: 'quantitative',
yType: 'quantitative',
zoomToFit: false,
fontSize: 11,
};
//# sourceMappingURL=scatterplot.js.map
/***/ }),
/* 435 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const tf = __importStar(__webpack_require__(4));
const vega_embed_1 = __importDefault(__webpack_require__(81));
const dom_1 = __webpack_require__(59);
const utils_1 = __webpack_require__(120);
const render_utils_1 = __webpack_require__(37);
/**
* Renders a heatmap.
*
* ```js
* const cols = 50;
* const rows = 20;
* const values = [];
* for (let i = 0; i < cols; i++) {
* const col = []
* for (let j = 0; j < rows; j++) {
* col.push(i * j)
* }
* values.push(col);
* }
* const data = { values };
*
* // Render to visor
* const surface = { name: 'Heatmap', tab: 'Charts' };
* tfvis.render.heatmap(surface, data);
* ```
*
* ```js
* const data = {
* values: [[4, 2, 8, 20], [1, 7, 2, 10], [3, 3, 20, 13]],
* xTickLabels: ['cheese', 'pig', 'font'],
* yTickLabels: ['speed', 'smoothness', 'dexterity', 'mana'],
* }
*
* // Render to visor
* const surface = { name: 'Heatmap w Custom Labels', tab: 'Charts' };
* tfvis.render.heatmap(surface, data);
* ```
*
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function heatmap(container, data, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const options = Object.assign({}, defaultOpts, opts);
const drawArea = render_utils_1.getDrawArea(container);
let inputValues = data.values;
if (options.rowMajor) {
inputValues = yield convertToRowMajor(data.values);
}
// Data validation
const { xTickLabels, yTickLabels } = data;
if (xTickLabels != null) {
const dimension = 0;
assertLabelsMatchShape(inputValues, xTickLabels, dimension);
}
// Note that we will only do a check on the first element of the second
// dimension. We do not protect users against passing in a ragged array.
if (yTickLabels != null) {
const dimension = 1;
assertLabelsMatchShape(inputValues, yTickLabels, dimension);
}
//
// Format data for vega spec; an array of objects, one for for each cell
// in the matrix.
//
// If custom labels are passed in for xTickLabels or yTickLabels we need
// to make sure they are 'unique' before mapping them to visual properties.
// We therefore append the index of the label to the datum that will be used
// for that label in the x or y axis. We could do this in all cases but choose
// not to to avoid unnecessary string operations.
//
// We use IDX_SEPARATOR to demarcate the added index
const IDX_SEPARATOR = '@tfidx@';
const values = [];
if (inputValues instanceof tf.Tensor) {
utils_1.assert(inputValues.rank === 2, 'Input to renderHeatmap must be a 2d array or Tensor2d');
// This is a slightly specialized version of TensorBuffer.get, inlining it
// avoids the overhead of a function call per data element access and is
// specialized to only deal with the 2d case.
const inputArray = yield inputValues.data();
const [numRows, numCols] = inputValues.shape;
for (let row = 0; row < numRows; row++) {
const x = xTickLabels ? `${xTickLabels[row]}${IDX_SEPARATOR}${row}` : row;
for (let col = 0; col < numCols; col++) {
const y = yTickLabels ? `${yTickLabels[col]}${IDX_SEPARATOR}${col}` : col;
const index = (row * numCols) + col;
const value = inputArray[index];
values.push({ x, y, value });
}
}
}
else {
const inputArray = inputValues;
for (let row = 0; row < inputArray.length; row++) {
const x = xTickLabels ? `${xTickLabels[row]}${IDX_SEPARATOR}${row}` : row;
for (let col = 0; col < inputArray[row].length; col++) {
const y = yTickLabels ? `${yTickLabels[col]}${IDX_SEPARATOR}${col}` : col;
const value = inputArray[row][col];
values.push({ x, y, value });
}
}
}
const embedOpts = {
actions: false,
mode: 'vega-lite',
defaultStyle: false,
};
const spec = {
'width': options.width || dom_1.getDefaultWidth(drawArea),
'height': options.height || dom_1.getDefaultHeight(drawArea),
'padding': 0,
'autosize': {
'type': 'fit',
'contains': 'padding',
'resize': true,
},
'config': {
'axis': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'text': { 'fontSize': options.fontSize },
'legend': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'scale': { 'bandPaddingInner': 0, 'bandPaddingOuter': 0 },
},
'data': { 'values': values },
'mark': { 'type': 'rect', 'tooltip': true },
'encoding': {
'x': {
'field': 'x',
'type': options.xType,
'title': options.xLabel,
'sort': 'x',
},
'y': {
'field': 'y',
'type': options.yType,
'title': options.yLabel,
'sort': 'y',
},
'fill': {
'field': 'value',
'type': 'quantitative',
}
}
};
//
// Format custom labels to remove the appended indices
//
const suffixPattern = `${IDX_SEPARATOR}\\d+$`;
const suffixRegex = new RegExp(suffixPattern);
if (xTickLabels) {
// @ts-ignore
spec.encoding.x.axis = {
'labelExpr': `replace(datum.value, regexp(/${suffixPattern}/), '')`,
};
}
if (yTickLabels) {
// @ts-ignore
spec.encoding.y.axis = {
'labelExpr': `replace(datum.value, regexp(/${suffixPattern}/), '')`,
};
}
// Customize tooltip formatting to remove the appended indices
if (xTickLabels || yTickLabels) {
//@ts-ignore
embedOpts.tooltip = {
sanitize: (value) => {
const valueString = String(value);
return valueString.replace(suffixRegex, '');
}
};
}
let colorRange;
switch (options.colorMap) {
case 'blues':
colorRange = ['#f7fbff', '#4292c6'];
break;
case 'greyscale':
colorRange = ['#000000', '#ffffff'];
break;
case 'viridis':
default:
colorRange = 'viridis';
break;
}
if (colorRange !== 'viridis') {
const fill = spec.encoding.fill;
// @ts-ignore
fill.scale = { 'range': colorRange };
}
if (options.domain) {
const fill = spec.encoding.fill;
// @ts-ignore
if (fill.scale != null) {
// @ts-ignore
fill.scale = Object.assign({}, fill.scale, { 'domain': options.domain });
}
else {
// @ts-ignore
fill.scale = { 'domain': options.domain };
}
}
yield vega_embed_1.default(drawArea, spec, embedOpts);
});
}
exports.heatmap = heatmap;
function convertToRowMajor(inputValues) {
return __awaiter(this, void 0, void 0, function* () {
let originalShape;
let transposed;
if (inputValues instanceof tf.Tensor) {
originalShape = inputValues.shape;
transposed = inputValues.transpose();
}
else {
originalShape = [inputValues.length, inputValues[0].length];
transposed = tf.tidy(() => tf.tensor2d(inputValues).transpose());
}
utils_1.assert(transposed.rank === 2, 'Input to renderHeatmap must be a 2d array or Tensor2d');
// Download the intermediate tensor values and
// dispose the transposed tensor.
const transposedValues = yield transposed.array();
transposed.dispose();
const transposedShape = [transposedValues.length, transposedValues[0].length];
utils_1.assert(originalShape[0] === transposedShape[1] &&
originalShape[1] === transposedShape[0], `Unexpected transposed shape. Original ${originalShape} : Transposed ${transposedShape}`);
return transposedValues;
});
}
function assertLabelsMatchShape(inputValues, labels, dimension) {
const shape = inputValues instanceof tf.Tensor ?
inputValues.shape :
[inputValues.length, inputValues[0].length];
if (dimension === 0) {
utils_1.assert(shape[0] === labels.length, `Length of xTickLabels (${labels.length}) must match number of rows` +
` (${shape[0]})`);
}
else if (dimension === 1) {
utils_1.assert(shape[1] === labels.length, `Length of yTickLabels (${labels.length}) must match number of columns (${shape[1]})`);
}
}
const defaultOpts = {
xLabel: null,
yLabel: null,
xType: 'ordinal',
yType: 'ordinal',
colorMap: 'viridis',
fontSize: 12,
domain: null,
rowMajor: false,
};
//# sourceMappingURL=heatmap.js.map
/***/ }),
/* 436 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const vega_embed_1 = __importDefault(__webpack_require__(81));
const dom_1 = __webpack_require__(59);
const render_utils_1 = __webpack_require__(37);
/**
* Renders a confusion matrix.
*
* Can optionally exclude the diagonal from being shaded if one wants the visual
* focus to be on the incorrect classifications. Note that if the classification
* is perfect (i.e. only the diagonal has values) then the diagonal will always
* be shaded.
*
* ```js
* const rows = 5;
* const cols = 5;
* const values = [];
* for (let i = 0; i < rows; i++) {
* const row = []
* for (let j = 0; j < cols; j++) {
* row.push(Math.round(Math.random() * 50));
* }
* values.push(row);
* }
* const data = { values };
*
* // Render to visor
* const surface = { name: 'Confusion Matrix', tab: 'Charts' };
* tfvis.render.confusionMatrix(surface, data);
* ```
*
* ```js
* // The diagonal can be excluded from shading.
*
* const data = {
* values: [[4, 2, 8], [1, 7, 2], [3, 3, 20]],
* }
*
* // Render to visor
* const surface = {
* name: 'Confusion Matrix with Excluded Diagonal', tab: 'Charts'
* };
*
* tfvis.render.confusionMatrix(surface, data, {
* shadeDiagonal: false
* });
* ```
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function confusionMatrix(container, data, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const options = Object.assign({}, defaultOpts, opts);
const drawArea = render_utils_1.getDrawArea(container);
// Format data for vega spec; an array of objects, one for for each cell
// in the matrix.
const values = [];
const inputArray = data.values;
const tickLabels = data.tickLabels || [];
const generateLabels = tickLabels.length === 0;
let nonDiagonalIsAllZeroes = true;
for (let i = 0; i < inputArray.length; i++) {
const label = generateLabels ? `Class ${i}` : tickLabels[i];
if (generateLabels) {
tickLabels.push(label);
}
for (let j = 0; j < inputArray[i].length; j++) {
const prediction = generateLabels ? `Class ${j}` : tickLabels[j];
const count = inputArray[i][j];
if (i === j && !options.shadeDiagonal) {
values.push({
label,
prediction,
count,
noFill: true,
});
}
else {
values.push({
label,
prediction,
count,
scaleCount: count,
});
// When not shading the diagonal we want to check if there is a non
// zero value. If all values are zero we will not color them as the
// scale will be invalid.
if (count !== 0) {
nonDiagonalIsAllZeroes = false;
}
}
}
}
if (!options.shadeDiagonal && nonDiagonalIsAllZeroes) {
// User has specified requested not to shade the diagonal but all the other
// values are zero. We have two choices, don't shade the anything or only
// shade the diagonal. We choose to shade the diagonal as that is likely
// more helpful even if it is not what the user specified.
for (const val of values) {
if (val.noFill === true) {
val.noFill = false;
val.scaleCount = val.count;
}
}
}
const embedOpts = {
actions: false,
mode: 'vega-lite',
defaultStyle: false,
};
const spec = {
'width': options.width || dom_1.getDefaultWidth(drawArea),
'height': options.height || dom_1.getDefaultHeight(drawArea),
'padding': 0,
'autosize': {
'type': 'fit',
'contains': 'padding',
'resize': true,
},
'config': {
'axis': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'text': { 'fontSize': options.fontSize },
'legend': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
}
},
'data': { 'values': values },
'encoding': {
'x': {
'field': 'prediction',
'type': 'ordinal',
'title': options.xLabel || 'prediction',
// Maintain sort order of the axis if labels is passed in
'scale': { 'domain': tickLabels },
},
'y': {
'field': 'label',
'type': 'ordinal',
'title': options.yLabel || 'label',
// Maintain sort order of the axis if labels is passed in
'scale': { 'domain': tickLabels },
},
},
'layer': [
{
// The matrix
'transform': [
{ 'filter': 'datum.noFill != true' },
],
'mark': {
'type': 'rect',
},
'encoding': {
'color': {
'field': 'scaleCount',
'type': 'quantitative',
'scale': { 'range': options.colorMap },
},
'tooltip': [
{ 'field': 'label', 'type': 'nominal' },
{ 'field': 'prediction', 'type': 'nominal' },
{ 'field': 'count', 'type': 'quantitative' },
]
},
},
]
};
if (options.shadeDiagonal === false) {
spec.layer.push({
// render unfilled rects for the diagonal
'transform': [
{ 'filter': 'datum.noFill == true' },
],
'mark': {
'type': 'rect',
'fill': 'white',
},
'encoding': {
'tooltip': [
{ 'field': 'label', 'type': 'nominal' },
{ 'field': 'prediction', 'type': 'nominal' },
{ 'field': 'count', 'type': 'quantitative' },
]
},
});
}
if (options.showTextOverlay) {
spec.layer.push({
// The text labels
'mark': { 'type': 'text', 'baseline': 'middle' },
'encoding': {
'text': {
'field': 'count',
'type': 'nominal',
},
}
});
}
const colorMap = typeof options.colorMap === 'string' ?
{ scheme: options.colorMap } :
options.colorMap;
//@ts-ignore
spec.layer[0].encoding.color.scale.range = colorMap;
yield vega_embed_1.default(drawArea, spec, embedOpts);
});
}
exports.confusionMatrix = confusionMatrix;
const defaultOpts = {
xLabel: null,
yLabel: null,
xType: 'nominal',
yType: 'nominal',
shadeDiagonal: true,
fontSize: 12,
showTextOverlay: true,
height: 400,
colorMap: ['#f7fbff', '#4292c6'],
};
//# sourceMappingURL=confusion_matrix.js.map
/***/ }),
/* 437 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
const preact_1 = __webpack_require__(155);
const glamor_1 = __webpack_require__(104);
/**
* Renders a container for tab links
*/
class Tabs extends preact_1.Component {
render() {
const { tabNames, activeTab, handleClick } = this.props;
const tabs = tabNames.length > 0 ?
tabNames.map((name) => (preact_1.h(Tab, { key: name, id: name, handleClick: handleClick, isActive: name === activeTab }, name)))
: null;
const tabStyle = glamor_1.css({
overflowX: 'scroll',
overflowY: 'hidden',
whiteSpace: 'nowrap',
borderBottomStyle: 'solid',
borderBottomWidth: '1px',
borderColor: '#eee',
paddingBottom: '1rem',
marginTop: '1rem',
});
return (preact_1.h("div", { className: `${tabStyle} visor-tabs` }, tabs));
}
}
exports.Tabs = Tabs;
/**
* A link representing a tab. Note that the component does not contain the
* tab content
*/
class Tab extends preact_1.Component {
render() {
const { children, isActive, handleClick, id } = this.props;
const tabStyle = glamor_1.css({
borderBottomColor: isActive ? '#357EDD' : '#AAAAAA',
borderBottomWidth: '1px',
borderBottomStyle: 'solid',
cursor: 'pointer',
':hover': {
color: '#357EDD'
},
display: 'inline-block',
marginRight: '1rem',
padding: '.5rem',
fontSize: '1rem',
fontWeight: 'bold',
});
return (preact_1.h("a", { className: `${tabStyle} tf-tab`, "data-isactive": isActive, onClick: () => handleClick(id) }, children));
}
}
//# sourceMappingURL=tabs.js.map
/***/ }),
/* 438 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
const preact_1 = __webpack_require__(155);
const glamor_1 = __webpack_require__(104);
/**
* A surface is container for visualizations and other rendered thigns.
* It consists of a containing DOM Element, a label and an empty drawArea.
*/
class SurfaceComponent extends preact_1.Component {
componentDidMount() {
const { name, tab } = this.props;
this.props.registerSurface(name, tab, this);
}
componentDidUpdate() {
// Prevent re-rendering of this component as it
// is primarily controlled outside of this class
return false;
}
render() {
const { name, visible, styles } = this.props;
const finalStyles = Object.assign({}, SurfaceComponent.defaultStyles, styles);
const { width, height, } = finalStyles;
let { maxHeight, maxWidth, } = finalStyles;
maxHeight = height === SurfaceComponent.defaultStyles.height ?
maxHeight : height;
maxWidth = width === SurfaceComponent.defaultStyles.width ?
maxWidth : width;
const surfaceStyle = glamor_1.css({
display: visible ? 'block' : 'none',
backgroundColor: 'white',
marginTop: '10px',
marginBottom: '10px',
boxShadow: '0 0 6px -3px #777',
padding: '10px !important',
height,
width,
maxHeight,
maxWidth,
overflow: 'auto',
});
const labelStyle = glamor_1.css({
backgroundColor: 'white',
boxSizing: 'border-box',
borderBottom: '1px solid #357EDD',
lineHeight: '2em',
marginBottom: '20px',
fontWeight: '600',
textAlign: 'center',
});
const drawAreaStyle = glamor_1.css({
boxSizing: 'border-box',
});
return (preact_1.h("div", { className: `${surfaceStyle} tf-surface`, ref: (r) => this.container = r, "data-visible": visible },
preact_1.h("div", { className: `${labelStyle} tf-label`, ref: (r) => this.label = r }, name),
preact_1.h("div", { className: `${drawAreaStyle} tf-draw-area`, ref: (r) => this.drawArea = r })));
}
}
SurfaceComponent.defaultStyles = {
maxWidth: '550px',
maxHeight: '580px',
height: 'auto',
width: 'auto',
};
exports.SurfaceComponent = SurfaceComponent;
//# sourceMappingURL=surface.js.map
/***/ }),
/* 439 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
const preact_1 = __webpack_require__(155);
const glamor_1 = __webpack_require__(104);
const surface_1 = __webpack_require__(438);
const tabs_1 = __webpack_require__(437);
/**
* The Visor is a component that displays and manages 'Tabs' and 'Surfaces'.
*
* It is meant to exist as a singleton component on a given page and is thus
* accessed by a visor() function that exposes a single instance of this
* component via an imperative API (i.e. its implementation as a (p)react
* component is an internal implementation detail.
*
* Following that, and somewhat unlike a typical react component, it does allow
* for imperative calls to that instance to modify internal state. Any state
* that needs to be serialized or persisted should be lifted to props.
*/
class VisorComponent extends preact_1.Component {
/**
* Helper function to render the component to the DOM.
*
* Note that although the visor has a parent element, it rendered via absolute
* positioning and is thus taken out of regular document flow.
*
* @param parent A DOM element
* @param replaceNode The element that re-rendering this component would
* replace. Usually null initially and will be returned by
* this function after the first render.
* @param props Initial visor props
*/
static render(parent, replaceNode, props) {
return preact_1.render(preact_1.h(VisorComponent, Object.assign({}, props)), parent, replaceNode);
}
constructor(props) {
super(props);
this.surfaces = new Map();
const startOpen = props.startOpen == null ? true : props.startOpen;
this.state = {
isOpen: startOpen,
isFullscreen: false,
activeTab: null,
tabs: new Set()
};
this.keyHandler = this.keyHandler.bind(this);
}
// These public methods are exposed via an imperative interface
close() {
this.setState({ isOpen: false });
}
open() {
this.setState({ isOpen: true });
}
toggle() {
this.setState({ isOpen: !this.state.isOpen });
}
toggleFullScreen() {
this.setState({ isFullscreen: !this.state.isFullscreen });
}
isOpen() {
return this.state.isOpen;
}
isFullscreen() {
return this.state.isFullscreen;
}
getSurface(label, tab) {
const surfaceId = this.surfaceId(label, tab);
let surface;
if (this.surfaces.has(surfaceId)) {
surface = this.surfaces.get(surfaceId);
}
else {
throw Error(`Surface not found with id: ${surfaceId}`);
}
return {
container: surface.container,
label: surface.label,
drawArea: surface.drawArea,
};
}
bindKeys() {
document.addEventListener('keydown', this.keyHandler, false);
}
unbindKeys() {
document.removeEventListener('keydown', this.keyHandler);
}
surfaceId(label, tab) {
return label + tab;
}
setTabs(surfaceList) {
// Check if we have new tabs
const nextTabs = surfaceList.map(s => s.tab);
const tabs = this.state.tabs;
let newActiveTab;
for (const tab of nextTabs) {
if (!tabs.has(tab)) {
tabs.add(tab);
newActiveTab = tab;
}
}
if (newActiveTab != null) {
this.setState({
tabs,
activeTab: newActiveTab,
});
}
}
getTabs() {
return this.state.tabs;
}
// Event Handlers
registerSurface(name, tab, surface) {
const surfaceId = this.surfaceId(name, tab);
this.surfaces.set(surfaceId, surface);
}
keyHandler(event) {
const BACKTICK_KEY = 192;
if (event.keyCode === BACKTICK_KEY) {
if (event.shiftKey) {
this.toggleFullScreen();
}
else {
this.toggle();
}
}
}
setActiveTab(tab) {
this.setState({ activeTab: tab });
}
// Lifecycle Methods
componentDidMount() {
this.bindKeys();
}
componentWillMount() {
this.setTabs(this.props.surfaceList);
}
componentWillReceiveProps(nextProps) {
this.setTabs(nextProps.surfaceList);
}
render() {
const { isOpen, isFullscreen, activeTab } = this.state;
const { surfaceList } = this.props;
const tabNames = Array.from(this.getTabs().values());
const SMALL_WIDTH = '550px';
const LARGE_WIDTH = '90vw';
const width = isFullscreen ? LARGE_WIDTH : SMALL_WIDTH;
const defaultStyles = glamor_1.css({
width,
height: '100%',
backgroundColor: '#fafafa',
boxSizing: 'border-box',
padding: '10px',
position: 'fixed',
top: '0px',
// tslint:disable-next-line
transition: `right 0.5s cubic-bezier(0.645, 0.045, 0.355, 1), width 0.5s cubic-bezier(0.645, 0.045, 0.355, 1)`,
boxShadow: '0 2px 5px rgba(0, 0, 0, 0.12), 0 2px 5px rgba(0, 0, 0, 0.24)',
overflow: 'auto',
fontFamily: 'sans-serif',
fontSize: '14px',
zIndex: 1000,
});
const openStyle = glamor_1.css({ right: '0' });
const closedStyle = glamor_1.css({ right: `calc(-${width} - 10px)` });
const position = isOpen ? openStyle : closedStyle;
// TODO. Add flex wrapping for surfaces
const surfacesContainerStyle = glamor_1.css({});
return (preact_1.h("div", { className: `${defaultStyles} ${position} visor`, "data-isopen": isOpen, "data-isfullscreen": isFullscreen },
preact_1.h(VisorControls, { fullScreenHandler: this.toggleFullScreen.bind(this), closeHandler: this.close.bind(this), isFullScreen: isFullscreen }),
preact_1.h(tabs_1.Tabs, { tabNames: tabNames, activeTab: activeTab, handleClick: this.setActiveTab.bind(this) }),
preact_1.h("div", { className: `${surfacesContainerStyle} visor-surfaces` }, surfaceList.map((surfaceInfo) => (preact_1.h(surface_1.SurfaceComponent, { key: surfaceInfo.name + surfaceInfo.tab, name: surfaceInfo.name, tab: surfaceInfo.tab, styles: surfaceInfo.styles, registerSurface: this.registerSurface.bind(this), visible: activeTab === surfaceInfo.tab }))))));
}
}
exports.VisorComponent = VisorComponent;
function VisorControls(props) {
const { isFullScreen, fullScreenHandler, closeHandler } = props;
const toolBarStyle = glamor_1.css({
display: 'flex',
backgroundColor: 'white',
border: '1px solid white',
padding: '6px',
paddingTop: '10px',
marginBottom: '10px',
borderRadius: '6px',
marginTop: '-16px'
});
const controlsButtonClass = glamor_1.css({
fontSize: '.875rem',
borderRadius: '.25rem',
paddingLeft: '1rem',
paddingRight: '1rem',
paddingTop: '.5rem',
paddingBottom: '.5rem',
textDecoration: 'none',
transition: 'color .15s ease-in',
color: '#111',
});
const floatRight = glamor_1.css({
marginLeft: 'auto',
});
return (preact_1.h("div", { className: `${toolBarStyle} visor-controls` },
preact_1.h("button", { className: `${controlsButtonClass}`, onClick: fullScreenHandler }, isFullScreen ? 'Minimize' : 'Maximize'),
preact_1.h("button", { className: `${controlsButtonClass} ${floatRight}`, onClick: closeHandler }, "Hide")));
}
//# sourceMappingURL=visor.js.map
/***/ }),
/* 440 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = doHash;
// murmurhash2 via https://gist.github.com/raycmorgan/588423
function doHash(str, seed) {
var m = 0x5bd1e995;
var r = 24;
var h = seed ^ str.length;
var length = str.length;
var currentIndex = 0;
while (length >= 4) {
var k = UInt32(str, currentIndex);
k = Umul32(k, m);
k ^= k >>> r;
k = Umul32(k, m);
h = Umul32(h, m);
h ^= k;
currentIndex += 4;
length -= 4;
}
switch (length) {
case 3:
h ^= UInt16(str, currentIndex);
h ^= str.charCodeAt(currentIndex + 2) << 16;
h = Umul32(h, m);
break;
case 2:
h ^= UInt16(str, currentIndex);
h = Umul32(h, m);
break;
case 1:
h ^= str.charCodeAt(currentIndex);
h = Umul32(h, m);
break;
}
h ^= h >>> 13;
h = Umul32(h, m);
h ^= h >>> 15;
return h >>> 0;
}
function UInt32(str, pos) {
return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8) + (str.charCodeAt(pos++) << 16) + (str.charCodeAt(pos) << 24);
}
function UInt16(str, pos) {
return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8);
}
function Umul32(n, m) {
n = n | 0;
m = m | 0;
var nlo = n & 0xffff;
var nhi = n >>> 16;
var res = nlo * m + ((nhi * m & 0xffff) << 16) | 0;
return res;
}
/***/ }),
/* 441 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* eslint-disable no-var, prefer-template */
var uppercasePattern = /[A-Z]/g
var msPattern = /^ms-/
var cache = {}
function toHyphenLower(match) {
return '-' + match.toLowerCase()
}
function hyphenateStyleName(name) {
if (cache.hasOwnProperty(name)) {
return cache[name]
}
var hName = name.replace(uppercasePattern, toHyphenLower)
return (cache[name] = msPattern.test(hName) ? '-' + hName : hName)
}
/* harmony default export */ __webpack_exports__["default"] = (hyphenateStyleName);
/***/ }),
/* 442 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = hyphenateProperty;
var _hyphenateStyleName = __webpack_require__(441);
var _hyphenateStyleName2 = _interopRequireDefault(_hyphenateStyleName);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function hyphenateProperty(property) {
return (0, _hyphenateStyleName2.default)(property);
}
module.exports = exports['default'];
/***/ }),
/* 443 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transition;
var _hyphenateProperty = __webpack_require__(442);
var _hyphenateProperty2 = _interopRequireDefault(_hyphenateProperty);
var _isPrefixedValue = __webpack_require__(103);
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
var _capitalizeString = __webpack_require__(238);
var _capitalizeString2 = _interopRequireDefault(_capitalizeString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var properties = {
transition: true,
transitionProperty: true,
WebkitTransition: true,
WebkitTransitionProperty: true,
MozTransition: true,
MozTransitionProperty: true
};
var prefixMapping = {
Webkit: '-webkit-',
Moz: '-moz-',
ms: '-ms-'
};
function prefixValue(value, propertyPrefixMap) {
if ((0, _isPrefixedValue2.default)(value)) {
return value;
}
// only split multi values, not cubic beziers
var multipleValues = value.split(/,(?![^()]*(?:\([^()]*\))?\))/g);
for (var i = 0, len = multipleValues.length; i < len; ++i) {
var singleValue = multipleValues[i];
var values = [singleValue];
for (var property in propertyPrefixMap) {
var dashCaseProperty = (0, _hyphenateProperty2.default)(property);
if (singleValue.indexOf(dashCaseProperty) > -1 && dashCaseProperty !== 'order') {
var prefixes = propertyPrefixMap[property];
for (var j = 0, pLen = prefixes.length; j < pLen; ++j) {
// join all prefixes and create a new value
values.unshift(singleValue.replace(dashCaseProperty, prefixMapping[prefixes[j]] + dashCaseProperty));
}
}
}
multipleValues[i] = values.join(',');
}
return multipleValues.join(',');
}
function transition(property, value, style, propertyPrefixMap) {
// also check for already prefixed transitions
if (typeof value === 'string' && properties.hasOwnProperty(property)) {
var outputValue = prefixValue(value, propertyPrefixMap);
// if the property is already prefixed
var webkitOutput = outputValue.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function (val) {
return !/-moz-|-ms-/.test(val);
}).join(',');
if (property.indexOf('Webkit') > -1) {
return webkitOutput;
}
var mozOutput = outputValue.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function (val) {
return !/-webkit-|-ms-/.test(val);
}).join(',');
if (property.indexOf('Moz') > -1) {
return mozOutput;
}
style['Webkit' + (0, _capitalizeString2.default)(property)] = webkitOutput;
style['Moz' + (0, _capitalizeString2.default)(property)] = mozOutput;
return outputValue;
}
}
module.exports = exports['default'];
/***/ }),
/* 444 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = sizing;
var prefixes = ['-webkit-', '-moz-', ''];
var properties = {
maxHeight: true,
maxWidth: true,
width: true,
height: true,
columnWidth: true,
minWidth: true,
minHeight: true
};
var values = {
'min-content': true,
'max-content': true,
'fill-available': true,
'fit-content': true,
'contain-floats': true
};
function sizing(property, value) {
if (properties.hasOwnProperty(property) && values.hasOwnProperty(value)) {
return prefixes.map(function (prefix) {
return prefix + value;
});
}
}
module.exports = exports['default'];
/***/ }),
/* 445 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = position;
function position(property, value) {
if (property === 'position' && value === 'sticky') {
return ['-webkit-sticky', 'sticky'];
}
}
module.exports = exports['default'];
/***/ }),
/* 446 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = imageSet;
var _isPrefixedValue = __webpack_require__(103);
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// http://caniuse.com/#feat=css-image-set
var prefixes = ['-webkit-', ''];
function imageSet(property, value) {
if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && value.indexOf('image-set(') > -1) {
return prefixes.map(function (prefix) {
return value.replace(/image-set\(/g, prefix + 'image-set(');
});
}
}
module.exports = exports['default'];
/***/ }),
/* 447 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = gradient;
var _isPrefixedValue = __webpack_require__(103);
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var prefixes = ['-webkit-', '-moz-', ''];
var values = /linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/;
function gradient(property, value) {
if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && values.test(value)) {
return prefixes.map(function (prefix) {
return prefix + value;
});
}
}
module.exports = exports['default'];
/***/ }),
/* 448 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = flexboxOld;
var alternativeValues = {
'space-around': 'justify',
'space-between': 'justify',
'flex-start': 'start',
'flex-end': 'end',
'wrap-reverse': 'multiple',
wrap: 'multiple'
};
var alternativeProps = {
alignItems: 'WebkitBoxAlign',
justifyContent: 'WebkitBoxPack',
flexWrap: 'WebkitBoxLines'
};
function flexboxOld(property, value, style) {
if (property === 'flexDirection' && typeof value === 'string') {
if (value.indexOf('column') > -1) {
style.WebkitBoxOrient = 'vertical';
} else {
style.WebkitBoxOrient = 'horizontal';
}
if (value.indexOf('reverse') > -1) {
style.WebkitBoxDirection = 'reverse';
} else {
style.WebkitBoxDirection = 'normal';
}
}
if (alternativeProps.hasOwnProperty(property)) {
style[alternativeProps[property]] = alternativeValues[value] || value;
}
}
module.exports = exports['default'];
/***/ }),
/* 449 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = flex;
var values = {
flex: ['-webkit-box', '-moz-box', '-ms-flexbox', '-webkit-flex', 'flex'],
'inline-flex': ['-webkit-inline-box', '-moz-inline-box', '-ms-inline-flexbox', '-webkit-inline-flex', 'inline-flex']
};
function flex(property, value) {
if (property === 'display' && values.hasOwnProperty(value)) {
return values[value];
}
}
module.exports = exports['default'];
/***/ }),
/* 450 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = filter;
var _isPrefixedValue = __webpack_require__(103);
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// http://caniuse.com/#feat=css-filter-function
var prefixes = ['-webkit-', ''];
function filter(property, value) {
if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && value.indexOf('filter(') > -1) {
return prefixes.map(function (prefix) {
return value.replace(/filter\(/g, prefix + 'filter(');
});
}
}
module.exports = exports['default'];
/***/ }),
/* 451 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = crossFade;
var _isPrefixedValue = __webpack_require__(103);
var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// http://caniuse.com/#search=cross-fade
var prefixes = ['-webkit-', ''];
function crossFade(property, value) {
if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && value.indexOf('cross-fade(') > -1) {
return prefixes.map(function (prefix) {
return value.replace(/cross-fade\(/g, prefix + 'cross-fade(');
});
}
}
module.exports = exports['default'];
/***/ }),
/* 452 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = cursor;
var prefixes = ['-webkit-', '-moz-', ''];
var values = {
'zoom-in': true,
'zoom-out': true,
grab: true,
grabbing: true
};
function cursor(property, value) {
if (property === 'cursor' && values.hasOwnProperty(value)) {
return prefixes.map(function (prefix) {
return prefix + value;
});
}
}
module.exports = exports['default'];
/***/ }),
/* 453 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = prefixValue;
function prefixValue(plugins, property, value, style, metaData) {
for (var i = 0, len = plugins.length; i < len; ++i) {
var processedValue = plugins[i](property, value, style, metaData);
// we can stop processing if a value is returned
// as all plugin criteria are unique
if (processedValue) {
return processedValue;
}
}
}
module.exports = exports["default"];
/***/ }),
/* 454 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = prefixProperty;
var _capitalizeString = __webpack_require__(238);
var _capitalizeString2 = _interopRequireDefault(_capitalizeString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function prefixProperty(prefixProperties, property, style) {
if (prefixProperties.hasOwnProperty(property)) {
var requiredPrefixes = prefixProperties[property];
for (var i = 0, len = requiredPrefixes.length; i < len; ++i) {
style[requiredPrefixes[i] + (0, _capitalizeString2.default)(property)] = style[property];
}
}
}
module.exports = exports['default'];
/***/ }),
/* 455 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var w = ["Webkit"];
var m = ["Moz"];
var ms = ["ms"];
var wm = ["Webkit", "Moz"];
var wms = ["Webkit", "ms"];
var wmms = ["Webkit", "Moz", "ms"];
exports.default = {
plugins: [],
prefixMap: { "appearance": wm, "userSelect": wmms, "textEmphasisPosition": w, "textEmphasis": w, "textEmphasisStyle": w, "textEmphasisColor": w, "boxDecorationBreak": w, "clipPath": w, "maskImage": w, "maskMode": w, "maskRepeat": w, "maskPosition": w, "maskClip": w, "maskOrigin": w, "maskSize": w, "maskComposite": w, "mask": w, "maskBorderSource": w, "maskBorderMode": w, "maskBorderSlice": w, "maskBorderWidth": w, "maskBorderOutset": w, "maskBorderRepeat": w, "maskBorder": w, "maskType": w, "textDecorationStyle": w, "textDecorationSkip": w, "textDecorationLine": w, "textDecorationColor": w, "filter": w, "fontFeatureSettings": w, "breakAfter": wmms, "breakBefore": wmms, "breakInside": wmms, "columnCount": wm, "columnFill": wm, "columnGap": wm, "columnRule": wm, "columnRuleColor": wm, "columnRuleStyle": wm, "columnRuleWidth": wm, "columns": wm, "columnSpan": wm, "columnWidth": wm, "writingMode": wms, "flex": w, "flexBasis": w, "flexDirection": w, "flexGrow": w, "flexFlow": w, "flexShrink": w, "flexWrap": w, "alignContent": w, "alignItems": w, "alignSelf": w, "justifyContent": w, "order": w, "transform": w, "transformOrigin": w, "transformOriginX": w, "transformOriginY": w, "backfaceVisibility": w, "perspective": w, "perspectiveOrigin": w, "transformStyle": w, "transformOriginZ": w, "animation": w, "animationDelay": w, "animationDirection": w, "animationFillMode": w, "animationDuration": w, "animationIterationCount": w, "animationName": w, "animationPlayState": w, "animationTimingFunction": w, "backdropFilter": w, "fontKerning": w, "scrollSnapType": wms, "scrollSnapPointsX": wms, "scrollSnapPointsY": wms, "scrollSnapDestination": wms, "scrollSnapCoordinate": wms, "shapeImageThreshold": w, "shapeImageMargin": w, "shapeImageOutside": w, "hyphens": wmms, "flowInto": wms, "flowFrom": wms, "regionFragment": wms, "textAlignLast": m, "tabSize": m, "wrapFlow": ms, "wrapThrough": ms, "wrapMargin": ms, "gridTemplateColumns": ms, "gridTemplateRows": ms, "gridTemplateAreas": ms, "gridTemplate": ms, "gridAutoColumns": ms, "gridAutoRows": ms, "gridAutoFlow": ms, "grid": ms, "gridRowStart": ms, "gridColumnStart": ms, "gridRowEnd": ms, "gridRow": ms, "gridColumn": ms, "gridColumnEnd": ms, "gridColumnGap": ms, "gridRowGap": ms, "gridArea": ms, "gridGap": ms, "textSizeAdjust": wms, "borderImage": w, "borderImageOutset": w, "borderImageRepeat": w, "borderImageSlice": w, "borderImageSource": w, "borderImageWidth": w, "transitionDelay": w, "transitionDuration": w, "transitionProperty": w, "transitionTimingFunction": w }
};
module.exports = exports["default"];
/***/ }),
/* 456 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = prefixer;
var _staticData = __webpack_require__(455);
var _staticData2 = _interopRequireDefault(_staticData);
var _prefixProperty = __webpack_require__(454);
var _prefixProperty2 = _interopRequireDefault(_prefixProperty);
var _prefixValue = __webpack_require__(453);
var _prefixValue2 = _interopRequireDefault(_prefixValue);
var _cursor = __webpack_require__(452);
var _cursor2 = _interopRequireDefault(_cursor);
var _crossFade = __webpack_require__(451);
var _crossFade2 = _interopRequireDefault(_crossFade);
var _filter = __webpack_require__(450);
var _filter2 = _interopRequireDefault(_filter);
var _flex = __webpack_require__(449);
var _flex2 = _interopRequireDefault(_flex);
var _flexboxOld = __webpack_require__(448);
var _flexboxOld2 = _interopRequireDefault(_flexboxOld);
var _gradient = __webpack_require__(447);
var _gradient2 = _interopRequireDefault(_gradient);
var _imageSet = __webpack_require__(446);
var _imageSet2 = _interopRequireDefault(_imageSet);
var _position = __webpack_require__(445);
var _position2 = _interopRequireDefault(_position);
var _sizing = __webpack_require__(444);
var _sizing2 = _interopRequireDefault(_sizing);
var _transition = __webpack_require__(443);
var _transition2 = _interopRequireDefault(_transition);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var plugins = [_crossFade2.default, _cursor2.default, _filter2.default, _flexboxOld2.default, _gradient2.default, _imageSet2.default, _position2.default, _sizing2.default, _transition2.default, _flex2.default]; // custom facade for inline-style-prefixer
var prefixMap = _staticData2.default.prefixMap;
function prefixer(style) {
for (var property in style) {
var value = style[property];
var processedValue = (0, _prefixValue2.default)(plugins, property, value, style, prefixMap);
// only modify the value if it was touched
// by any plugin to prevent unnecessary mutations
if (processedValue) {
style[property] = processedValue;
}
(0, _prefixProperty2.default)(prefixMap, property, style);
}
return style;
}
/***/ }),
/* 457 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.PluginSet = PluginSet;
exports.fallbacks = fallbacks;
exports.contentWrap = contentWrap;
exports.prefixes = prefixes;
var _objectAssign = __webpack_require__(156);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _CSSPropertyOperations = __webpack_require__(240);
var _prefixer = __webpack_require__(456);
var _prefixer2 = _interopRequireDefault(_prefixer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isDev = function (x) {
return x === 'development' || !x;
}("production");
function PluginSet(initial) {
this.fns = initial || [];
}
(0, _objectAssign2.default)(PluginSet.prototype, {
add: function add() {
var _this = this;
for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
fns.forEach(function (fn) {
if (_this.fns.indexOf(fn) >= 0) {
if (isDev) {
console.warn('adding the same plugin again, ignoring'); //eslint-disable-line no-console
}
} else {
_this.fns = [fn].concat(_this.fns);
}
});
},
remove: function remove(fn) {
this.fns = this.fns.filter(function (x) {
return x !== fn;
});
},
clear: function clear() {
this.fns = [];
},
transform: function transform(o) {
return this.fns.reduce(function (o, fn) {
return fn(o);
}, o);
}
});
function fallbacks(node) {
var hasArray = Object.keys(node.style).map(function (x) {
return Array.isArray(node.style[x]);
}).indexOf(true) >= 0;
if (hasArray) {
var style = node.style;
var flattened = Object.keys(style).reduce(function (o, key) {
o[key] = Array.isArray(style[key]) ? style[key].join('; ' + (0, _CSSPropertyOperations.processStyleName)(key) + ': ') : style[key];
return o;
}, {});
// todo -
// flatten arrays which haven't been flattened yet
return (0, _objectAssign2.default)({}, node, { style: flattened });
}
return node;
}
var contentValues = ['normal', 'none', 'counter', 'open-quote', 'close-quote', 'no-open-quote', 'no-close-quote', 'initial', 'inherit'];
function contentWrap(node) {
if (node.style.content) {
var cont = node.style.content;
if (contentValues.indexOf(cont) >= 0) {
return node;
}
if (/^(attr|calc|counters?|url)\(/.test(cont)) {
return node;
}
if (cont.charAt(0) === cont.charAt(cont.length - 1) && (cont.charAt(0) === '"' || cont.charAt(0) === "'")) {
return node;
}
return _extends({}, node, { style: _extends({}, node.style, { content: '"' + cont + '"' }) });
}
return node;
}
function prefixes(node) {
return (0, _objectAssign2.default)({}, node, { style: (0, _prefixer2.default)(_extends({}, node.style)) });
}
/***/ }),
/* 458 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = clean;
// Returns true for null, false, undefined and {}
function isFalsy(value) {
return value === null || value === undefined || value === false || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && Object.keys(value).length === 0;
}
function cleanObject(object) {
if (isFalsy(object)) return null;
if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object') return object;
var acc = {},
keys = Object.keys(object),
hasFalsy = false;
for (var i = 0; i < keys.length; i++) {
var value = object[keys[i]];
var filteredValue = clean(value);
if (filteredValue === null || filteredValue !== value) {
hasFalsy = true;
}
if (filteredValue !== null) {
acc[keys[i]] = filteredValue;
}
}
return Object.keys(acc).length === 0 ? null : hasFalsy ? acc : object;
}
function cleanArray(rules) {
var hasFalsy = false;
var filtered = [];
rules.forEach(function (rule) {
var filteredRule = clean(rule);
if (filteredRule === null || filteredRule !== rule) {
hasFalsy = true;
}
if (filteredRule !== null) {
filtered.push(filteredRule);
}
});
return filtered.length == 0 ? null : hasFalsy ? filtered : rules;
}
// Takes style array or object provided by user and clears all the falsy data
// If there is no styles left after filtration returns null
function clean(input) {
return Array.isArray(input) ? cleanArray(input) : cleanObject(input);
}
/***/ }),
/* 459 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @typechecks static-only
*/
/**
* Memoizes the return value of a function that accepts one string argument.
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
/***/ }),
/* 460 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
/***/ }),
/* 461 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var hyphenate = __webpack_require__(460);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
/***/ }),
/* 462 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 463 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSProperty
*/
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridRowStart: true,
gridRowEnd: true,
gridColumn: true,
gridColumnStart: true,
gridColumnEnd: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
};function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
exports.default = CSSProperty;
/***/ }),
/* 464 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CSSProperty = __webpack_require__(463);
var _CSSProperty2 = _interopRequireDefault(_CSSProperty);
var _warning = __webpack_require__(239);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
*/
var isUnitlessNumber = _CSSProperty2.default.isUnitlessNumber;
var styleWarnings = {};
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
if (false) { var warnings, warned, ownerName, owner; }
value = value.trim();
}
return value + 'px';
}
exports.default = dangerousStyleValue;
/***/ }),
/* 465 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
/***/ }),
/* 466 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var camelize = __webpack_require__(465);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
/***/ }),
/* 467 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StyleSheet = StyleSheet;
var _objectAssign = __webpack_require__(156);
var _objectAssign2 = _interopRequireDefault(_objectAssign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/*
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
- 'polyfills' on server side
// usage
import StyleSheet from 'glamor/lib/sheet'
let styleSheet = new StyleSheet()
styleSheet.inject()
- 'injects' the stylesheet into the page (or into memory if on server)
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/
function last(arr) {
return arr[arr.length - 1];
}
function sheetForTag(tag) {
if (tag.sheet) {
return tag.sheet;
}
// this weirdness brought to you by firefox
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
return document.styleSheets[i];
}
}
}
var isBrowser = typeof window !== 'undefined';
var isDev = "production" === 'development' || !"production"; //(x => (x === 'development') || !x)(process.env.NODE_ENV)
var isTest = "production" === 'test';
var oldIE = function () {
if (isBrowser) {
var div = document.createElement('div');
div.innerHTML = '<!--[if lt IE 10]><i></i><![endif]-->';
return div.getElementsByTagName('i').length === 1;
}
}();
function makeStyleTag() {
var tag = document.createElement('style');
tag.type = 'text/css';
tag.setAttribute('data-glamor', '');
tag.appendChild(document.createTextNode(''));
(document.head || document.getElementsByTagName('head')[0]).appendChild(tag);
return tag;
}
function StyleSheet() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$speedy = _ref.speedy,
speedy = _ref$speedy === undefined ? !isDev && !isTest : _ref$speedy,
_ref$maxLength = _ref.maxLength,
maxLength = _ref$maxLength === undefined ? isBrowser && oldIE ? 4000 : 65000 : _ref$maxLength;
this.isSpeedy = speedy; // the big drawback here is that the css won't be editable in devtools
this.sheet = undefined;
this.tags = [];
this.maxLength = maxLength;
this.ctr = 0;
}
(0, _objectAssign2.default)(StyleSheet.prototype, {
getSheet: function getSheet() {
return sheetForTag(last(this.tags));
},
inject: function inject() {
var _this = this;
if (this.injected) {
throw new Error('already injected stylesheet!');
}
if (isBrowser) {
this.tags[0] = makeStyleTag();
} else {
// server side 'polyfill'. just enough behavior to be useful.
this.sheet = {
cssRules: [],
insertRule: function insertRule(rule) {
// enough 'spec compliance' to be able to extract the rules later
// in other words, just the cssText field
_this.sheet.cssRules.push({ cssText: rule });
}
};
}
this.injected = true;
},
speedy: function speedy(bool) {
if (this.ctr !== 0) {
throw new Error('cannot change speedy mode after inserting any rule to sheet. Either call speedy(' + bool + ') earlier in your app, or call flush() before speedy(' + bool + ')');
}
this.isSpeedy = !!bool;
},
_insert: function _insert(rule) {
// this weirdness for perf, and chrome's weird bug
// https://stackoverflow.com/questions/20007992/chrome-suddenly-stopped-accepting-insertrule
try {
var sheet = this.getSheet();
sheet.insertRule(rule, rule.indexOf('@import') !== -1 ? 0 : sheet.cssRules.length);
} catch (e) {
if (isDev) {
// might need beter dx for this
console.warn('whoops, illegal rule inserted', rule); //eslint-disable-line no-console
}
}
},
insert: function insert(rule) {
if (isBrowser) {
// this is the ultrafast version, works across browsers
if (this.isSpeedy && this.getSheet().insertRule) {
this._insert(rule);
}
// more browser weirdness. I don't even know
// else if(this.tags.length > 0 && this.tags::last().styleSheet) {
// this.tags::last().styleSheet.cssText+= rule
// }
else {
if (rule.indexOf('@import') !== -1) {
var tag = last(this.tags);
tag.insertBefore(document.createTextNode(rule), tag.firstChild);
} else {
last(this.tags).appendChild(document.createTextNode(rule));
}
}
} else {
// server side is pretty simple
this.sheet.insertRule(rule, rule.indexOf('@import') !== -1 ? 0 : this.sheet.cssRules.length);
}
this.ctr++;
if (isBrowser && this.ctr % this.maxLength === 0) {
this.tags.push(makeStyleTag());
}
return this.ctr - 1;
},
// commenting this out till we decide on v3's decision
// _replace(index, rule) {
// // this weirdness for perf, and chrome's weird bug
// // https://stackoverflow.com/questions/20007992/chrome-suddenly-stopped-accepting-insertrule
// try {
// let sheet = this.getSheet()
// sheet.deleteRule(index) // todo - correct index here
// sheet.insertRule(rule, index)
// }
// catch(e) {
// if(isDev) {
// // might need beter dx for this
// console.warn('whoops, problem replacing rule', rule) //eslint-disable-line no-console
// }
// }
// }
// replace(index, rule) {
// if(isBrowser) {
// if(this.isSpeedy && this.getSheet().insertRule) {
// this._replace(index, rule)
// }
// else {
// let _slot = Math.floor((index + this.maxLength) / this.maxLength) - 1
// let _index = (index % this.maxLength) + 1
// let tag = this.tags[_slot]
// tag.replaceChild(document.createTextNode(rule), tag.childNodes[_index])
// }
// }
// else {
// let rules = this.sheet.cssRules
// this.sheet.cssRules = [ ...rules.slice(0, index), { cssText: rule }, ...rules.slice(index + 1) ]
// }
// }
delete: function _delete(index) {
// we insert a blank rule when 'deleting' so previously returned indexes remain stable
return this.replace(index, '');
},
flush: function flush() {
if (isBrowser) {
this.tags.forEach(function (tag) {
return tag.parentNode.removeChild(tag);
});
this.tags = [];
this.sheet = null;
this.ctr = 0;
// todo - look for remnants in document.styleSheets
} else {
// simpler on server
this.sheet.cssRules = [];
}
this.injected = false;
},
rules: function rules() {
if (!isBrowser) {
return this.sheet.cssRules;
}
var arr = [];
this.tags.forEach(function (tag) {
return arr.splice.apply(arr, [arr.length, 0].concat(_toConsumableArray(Array.from(sheetForTag(tag).cssRules))));
});
return arr;
}
});
/***/ }),
/* 468 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _isoFormat_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(288);
/* harmony import */ var _defaultLocale_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(null);
function parseIsoNative(string) {
var date = new Date(string);
return isNaN(date) ? null : date;
}
var parseIso = +new Date("2000-01-01T00:00:00.000Z")
? parseIsoNative
: Object(_defaultLocale_js__WEBPACK_IMPORTED_MODULE_1__[/* utcParse */ "e"])(_isoFormat_js__WEBPACK_IMPORTED_MODULE_0__["isoSpecifier"]);
/* harmony default export */ __webpack_exports__["default"] = (parseIso);
/***/ }),
/* 469 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _exponent_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
/* harmony default export */ __webpack_exports__["default"] = (function(step, max) {
step = Math.abs(step), max = Math.abs(max) - step;
return Math.max(0, Object(_exponent_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(max) - Object(_exponent_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(step)) + 1;
});
/***/ }),
/* 470 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _exponent_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
/* harmony default export */ __webpack_exports__["default"] = (function(step, value) {
return Math.max(0, Math.max(-8, Math.min(8, Math.floor(Object(_exponent_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(value) / 3))) * 3 - Object(_exponent_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(Math.abs(step)));
});
/***/ }),
/* 471 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _exponent_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
/* harmony default export */ __webpack_exports__["default"] = (function(step) {
return Math.max(0, -Object(_exponent_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(Math.abs(step)));
});
/***/ }),
/* 472 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return sequentialQuantile; });
/* harmony import */ var d3_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
/* harmony import */ var d3_array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(null);
/* harmony import */ var d3_array__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(null);
/* harmony import */ var _continuous_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(null);
/* harmony import */ var _init_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(null);
function sequentialQuantile() {
var domain = [],
interpolator = _continuous_js__WEBPACK_IMPORTED_MODULE_3__[/* identity */ "c"];
function scale(x) {
if (!isNaN(x = +x)) return interpolator((Object(d3_array__WEBPACK_IMPORTED_MODULE_0__[/* default */ "b"])(domain, x, 1) - 1) / (domain.length - 1));
}
scale.domain = function(_) {
if (!arguments.length) return domain.slice();
domain = [];
for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);
domain.sort(d3_array__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"]);
return scale;
};
scale.interpolator = function(_) {
return arguments.length ? (interpolator = _, scale) : interpolator;
};
scale.range = function() {
return domain.map((d, i) => interpolator(i / (domain.length - 1)));
};
scale.quantiles = function(n) {
return Array.from({length: n + 1}, (_, i) => Object(d3_array__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(domain, i / n));
};
scale.copy = function() {
return sequentialQuantile(interpolator).domain(domain);
};
return _init_js__WEBPACK_IMPORTED_MODULE_4__[/* initInterpolator */ "b"].apply(scale, arguments);
}
/***/ }),
/* 473 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return radial; });
/* harmony import */ var _continuous_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(null);
/* harmony import */ var _init_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(null);
/* harmony import */ var _linear_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(null);
/* harmony import */ var _number_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(null);
function square(x) {
return Math.sign(x) * x * x;
}
function unsquare(x) {
return Math.sign(x) * Math.sqrt(Math.abs(x));
}
function radial() {
var squared = Object(_continuous_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(),
range = [0, 1],
round = false,
unknown;
function scale(x) {
var y = unsquare(squared(x));
return isNaN(y) ? unknown : round ? Math.round(y) : y;
}
scale.invert = function(y) {
return squared.invert(square(y));
};
scale.domain = function(_) {
return arguments.length ? (squared.domain(_), scale) : squared.domain();
};
scale.range = function(_) {
return arguments.length ? (squared.range((range = Array.from(_, _number_js__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])).map(square)), scale) : range.slice();
};
scale.rangeRound = function(_) {
return scale.range(_).round(true);
};
scale.round = function(_) {
return arguments.length ? (round = !!_, scale) : round;
};
scale.clamp = function(_) {
return arguments.length ? (squared.clamp(_), scale) : squared.clamp();
};
scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
};
scale.copy = function() {
return radial(squared.domain(), range)
.round(round)
.clamp(squared.clamp())
.unknown(unknown);
};
_init_js__WEBPACK_IMPORTED_MODULE_1__[/* initRange */ "a"].apply(scale, arguments);
return Object(_linear_js__WEBPACK_IMPORTED_MODULE_2__[/* linearish */ "b"])(scale);
}
/***/ }),
/* 474 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2018 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const vega_embed_1 = __importDefault(__webpack_require__(81));
const dom_1 = __webpack_require__(59);
const render_utils_1 = __webpack_require__(37);
/**
* Renders a barchart.
*
* ```js
* const data = [
* { index: 0, value: 50 },
* { index: 1, value: 100 },
* { index: 2, value: 150 },
* ];
*
* // Render to visor
* const surface = { name: 'Bar chart', tab: 'Charts' };
* tfvis.render.barchart(surface, data);
* ```
*
* @param data Data in the following format, (an array of objects)
* `[ {index: number, value: number} ... ]`
*
* @returns Promise - indicates completion of rendering
*/
/** @doc {heading: 'Charts', namespace: 'render'} */
function barchart(container, data, opts = {}) {
return __awaiter(this, void 0, void 0, function* () {
const drawArea = render_utils_1.getDrawArea(container);
const values = data;
const options = Object.assign({}, defaultOpts, opts);
// If we have rendered this chart before with the same options we can do a
// data only update, else we do a regular re-render.
if (instances.has(drawArea)) {
const instanceInfo = instances.get(drawArea);
if (render_utils_1.shallowEquals(options, instanceInfo.lastOptions)) {
yield render_utils_1.nextFrame();
const view = instanceInfo.view;
const changes = view.changeset().remove(() => true).insert(values);
yield view.change('values', changes).runAsync();
return;
}
}
const { xLabel, yLabel, xType, yType } = options;
let xAxis = null;
if (xLabel != null) {
xAxis = { title: xLabel };
}
let yAxis = null;
if (yLabel != null) {
yAxis = { title: yLabel };
}
const embedOpts = {
actions: false,
mode: 'vega-lite',
defaultStyle: false,
};
let colorEncoding;
if (options.color != null) {
if (Array.isArray(options.color)) {
colorEncoding = {
'field': 'index',
'type': 'nominal',
'scale': {
'range': options.color,
}
};
}
else {
colorEncoding = { 'value': options.color };
}
}
else {
colorEncoding = { 'value': '#4C78A0' };
}
const spec = {
'width': options.width || dom_1.getDefaultWidth(drawArea),
'height': options.height || dom_1.getDefaultHeight(drawArea),
'padding': 0,
'autosize': {
'type': 'fit',
'contains': 'padding',
'resize': true,
},
'config': {
'axis': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
},
'text': { 'fontSize': options.fontSize },
'legend': {
'labelFontSize': options.fontSize,
'titleFontSize': options.fontSize,
}
},
'data': { 'values': values, 'name': 'values' },
'mark': {
'type': 'bar',
'tooltip': true,
},
'encoding': {
'x': { 'field': 'index', 'type': xType, 'axis': xAxis },
'y': { 'field': 'value', 'type': yType, 'axis': yAxis },
'color': colorEncoding,
},
};
yield render_utils_1.nextFrame();
const embedRes = yield vega_embed_1.default(drawArea, spec, embedOpts);
instances.set(drawArea, {
view: embedRes.view,
lastOptions: options,
});
});
}
exports.barchart = barchart;
const defaultOpts = {
xLabel: '',
yLabel: '',
xType: 'ordinal',
yType: 'quantitative',
fontSize: 11,
};
// We keep a map of containers to chart instances in order to reuse the
// instance where possible.
const instances = new Map();
//# sourceMappingURL=barchart.js.map
/***/ }),
/* 475 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 476 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 477 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 478 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 479 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 480 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 481 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
};
}
function installSetTimeoutImplementation() {
registerImmediate = function(handle) {
setTimeout(runIfPresent, 0, handle);
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 68
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53), __webpack_require__(87)))
/***/ }),
/* 482 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 483 */
/***/ (function(module, exports) {
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/* 484 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
/***/ }),
/* 485 */
/***/ (function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(161);
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ }),
/* 486 */
/***/ (function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(66);
var toLength = __webpack_require__(122);
var toAbsoluteIndex = __webpack_require__(485);
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ }),
/* 487 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.2.1 Object.assign(target, source, ...)
var DESCRIPTORS = __webpack_require__(32);
var getKeys = __webpack_require__(88);
var gOPS = __webpack_require__(157);
var pIE = __webpack_require__(105);
var toObject = __webpack_require__(65);
var IObject = __webpack_require__(163);
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(68)(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
}
} return T;
} : $assign;
/***/ }),
/* 488 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(23);
$export($export.S + $export.F, 'Object', { assign: __webpack_require__(487) });
/***/ }),
/* 489 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(488);
module.exports = __webpack_require__(18).Object.assign;
/***/ }),
/* 490 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _extends2 = __webpack_require__(90);
var _extends3 = _interopRequireDefault(_extends2);
var _assign = __webpack_require__(89);
var _assign2 = _interopRequireDefault(_assign);
var _tfjs = __webpack_require__(4);
var tf = _interopRequireWildcard(_tfjs);
var _tfjsVis = __webpack_require__(243);
var tfvis = _interopRequireWildcard(_tfjsVis);
var _PitchDetection = __webpack_require__(428);
var _PitchDetection2 = _interopRequireDefault(_PitchDetection);
var _ImageClassifier = __webpack_require__(411);
var _ImageClassifier2 = _interopRequireDefault(_ImageClassifier);
var _SoundClassifier = __webpack_require__(371);
var _SoundClassifier2 = _interopRequireDefault(_SoundClassifier);
var _KNNClassifier = __webpack_require__(368);
var _KNNClassifier2 = _interopRequireDefault(_KNNClassifier);
var _FeatureExtractor = __webpack_require__(363);
var _FeatureExtractor2 = _interopRequireDefault(_FeatureExtractor);
var _Word2vec = __webpack_require__(361);
var _Word2vec2 = _interopRequireDefault(_Word2vec);
var _YOLO = __webpack_require__(206);
var _CocoSsd = __webpack_require__(205);
var _ObjectDetector = __webpack_require__(346);
var _ObjectDetector2 = _interopRequireDefault(_ObjectDetector);
var _PoseNet = __webpack_require__(345);
var _PoseNet2 = _interopRequireDefault(_PoseNet);
var _imageUtilities = __webpack_require__(46);
var imageUtils = _interopRequireWildcard(_imageUtilities);
var _StyleTransfer = __webpack_require__(343);
var _StyleTransfer2 = _interopRequireDefault(_StyleTransfer);
var _CharRNN = __webpack_require__(342);
var _CharRNN2 = _interopRequireDefault(_CharRNN);
var _Pix2pix = __webpack_require__(340);
var _Pix2pix2 = _interopRequireDefault(_Pix2pix);
var _SketchRNN = __webpack_require__(338);
var _SketchRNN2 = _interopRequireDefault(_SketchRNN);
var _UNET = __webpack_require__(318);
var _UNET2 = _interopRequireDefault(_UNET);
var _CVAE = __webpack_require__(317);
var _CVAE2 = _interopRequireDefault(_CVAE);
var _DCGAN = __webpack_require__(316);
var _DCGAN2 = _interopRequireDefault(_DCGAN);
var _p5PreloadHelper = __webpack_require__(315);
var _p5PreloadHelper2 = _interopRequireDefault(_p5PreloadHelper);
var _package = __webpack_require__(201);
var _Sentiment = __webpack_require__(314);
var _Sentiment2 = _interopRequireDefault(_Sentiment);
var _BodyPix = __webpack_require__(313);
var _BodyPix2 = _interopRequireDefault(_BodyPix);
var _NeuralNetwork = __webpack_require__(310);
var _NeuralNetwork2 = _interopRequireDefault(_NeuralNetwork);
var _FaceApi = __webpack_require__(304);
var _FaceApi2 = _interopRequireDefault(_FaceApi);
var _KMeans = __webpack_require__(300);
var _KMeans2 = _interopRequireDefault(_KMeans);
var _CartoonGAN = __webpack_require__(299);
var _CartoonGAN2 = _interopRequireDefault(_CartoonGAN);
var _UniversalSentenceEncoder = __webpack_require__(298);
var _UniversalSentenceEncoder2 = _interopRequireDefault(_UniversalSentenceEncoder);
var _Facemesh = __webpack_require__(296);
var _Facemesh2 = _interopRequireDefault(_Facemesh);
var _Handpose = __webpack_require__(294);
var _Handpose2 = _interopRequireDefault(_Handpose);
var _p5Utils = __webpack_require__(83);
var _p5Utils2 = _interopRequireDefault(_p5Utils);
var _community = __webpack_require__(292);
var _community2 = _interopRequireDefault(_community);
var _testingUtils = __webpack_require__(291);
var testingUtils = _interopRequireWildcard(_testingUtils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright (c) 2018 ml5
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
var withPreload = {
charRNN: _CharRNN2.default,
CVAE: _CVAE2.default,
cartoon: _CartoonGAN2.default,
DCGAN: _DCGAN2.default,
featureExtractor: _FeatureExtractor2.default,
imageClassifier: _ImageClassifier2.default,
kmeans: _KMeans2.default,
soundClassifier: _SoundClassifier2.default,
pitchDetection: _PitchDetection2.default,
pix2pix: _Pix2pix2.default,
poseNet: _PoseNet2.default,
sketchRNN: _SketchRNN2.default,
styleTransfer: _StyleTransfer2.default,
word2vec: _Word2vec2.default,
YOLO: _YOLO.YOLO,
CocoSsd: _CocoSsd.CocoSsd,
objectDetector: _ObjectDetector2.default,
uNet: _UNET2.default,
sentiment: _Sentiment2.default,
bodyPix: _BodyPix2.default,
faceApi: _FaceApi2.default,
universalSentenceEncoder: _UniversalSentenceEncoder2.default,
facemesh: _Facemesh2.default,
handpose: _Handpose2.default
};
// call community statement on load
(function () {
(0, _community2.default)();
})();
module.exports = (0, _assign2.default)({ p5Utils: _p5Utils2.default }, (0, _p5PreloadHelper2.default)(withPreload), (0, _extends3.default)({
KNNClassifier: _KNNClassifier2.default,
communityStatement: _community2.default
}, imageUtils, {
tf: tf,
tfvis: tfvis,
version: _package.version,
neuralNetwork: _NeuralNetwork2.default,
testingUtils: testingUtils
}));
/***/ }),
/* 491 */
/***/ (function(module, exports) {
module.exports = function (regExp, replace) {
var replacer = replace === Object(replace) ? function (part) {
return replace[part];
} : replace;
return function (it) {
return String(it).replace(regExp, replacer);
};
};
/***/ }),
/* 492 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/benjamingr/RexExp.escape
var $export = __webpack_require__(5);
var $re = __webpack_require__(491)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } });
/***/ }),
/* 493 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(492);
module.exports = __webpack_require__(44).RegExp.escape;
/***/ }),
/* 494 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
!(function(global) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
runtime.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
resolve(result);
}, reject);
}
}
if (typeof global.process === "object" && global.process.domain) {
invoke = global.process.domain.bind(invoke);
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
if (delegate.iterator.return) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
})(
// Among the various tricks for obtaining a reference to the global
// object, this seems to be the most reliable technique that does not
// use indirect eval (which violates Content Security Policy).
typeof global === "object" ? global :
typeof window === "object" ? window :
typeof self === "object" ? self : this
);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53)))
/***/ }),
/* 495 */
/***/ (function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__(172);
var getKeys = __webpack_require__(77);
var redefine = __webpack_require__(30);
var global = __webpack_require__(11);
var hide = __webpack_require__(31);
var Iterators = __webpack_require__(91);
var wks = __webpack_require__(16);
var ITERATOR = wks('iterator');
var TO_STRING_TAG = wks('toStringTag');
var ArrayValues = Iterators.Array;
var DOMIterables = {
CSSRuleList: true, // TODO: Not spec compliant, should be false.
CSSStyleDeclaration: false,
CSSValueList: false,
ClientRectList: false,
DOMRectList: false,
DOMStringList: false,
DOMTokenList: true,
DataTransferItemList: false,
FileList: false,
HTMLAllCollection: false,
HTMLCollection: false,
HTMLFormElement: false,
HTMLSelectElement: false,
MediaList: true, // TODO: Not spec compliant, should be false.
MimeTypeArray: false,
NamedNodeMap: false,
NodeList: true,
PaintRequestList: false,
Plugin: false,
PluginArray: false,
SVGLengthList: false,
SVGNumberList: false,
SVGPathSegList: false,
SVGPointList: false,
SVGStringList: false,
SVGTransformList: false,
SourceBufferList: false,
StyleSheetList: true, // TODO: Not spec compliant, should be false.
TextTrackCueList: false,
TextTrackList: false,
TouchList: false
};
for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) {
var NAME = collections[i];
var explicit = DOMIterables[NAME];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
var key;
if (proto) {
if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues);
if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true);
}
}
/***/ }),
/* 496 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var $task = __webpack_require__(169);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ }),
/* 497 */
/***/ (function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var global = __webpack_require__(11);
var $export = __webpack_require__(5);
var userAgent = __webpack_require__(128);
var slice = [].slice;
var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check
var wrap = function (set) {
return function (fn, time /* , ...args */) {
var boundArgs = arguments.length > 2;
var args = boundArgs ? slice.call(arguments, 2) : false;
return set(boundArgs ? function () {
// eslint-disable-next-line no-new-func
(typeof fn == 'function' ? fn : Function(fn)).apply(this, args);
} : fn, time);
};
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
/***/ }),
/* 498 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/zenparsing/es-observable
var $export = __webpack_require__(5);
var global = __webpack_require__(11);
var core = __webpack_require__(44);
var microtask = __webpack_require__(168)();
var OBSERVABLE = __webpack_require__(16)('observable');
var aFunction = __webpack_require__(27);
var anObject = __webpack_require__(6);
var anInstance = __webpack_require__(72);
var redefineAll = __webpack_require__(70);
var hide = __webpack_require__(31);
var forOf = __webpack_require__(71);
var RETURN = forOf.RETURN;
var getMethod = function (fn) {
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function (subscription) {
var cleanup = subscription._c;
if (cleanup) {
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function (subscription) {
return subscription._o === undefined;
};
var closeSubscription = function (subscription) {
if (!subscriptionClosed(subscription)) {
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function (observer, subscriber) {
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer);
var subscription = cleanup;
if (cleanup != null) {
if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch (e) {
observer.error(e);
return;
} if (subscriptionClosed(this)) cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe() { closeSubscription(this); }
});
var SubscriptionObserver = function (subscription) {
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value) {
var subscription = this._s;
if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if (m) return m.call(observer, value);
} catch (e) {
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value) {
var subscription = this._s;
if (subscriptionClosed(subscription)) throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if (!m) throw value;
value = m.call(observer, value);
} catch (e) {
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value) {
var subscription = this._s;
if (!subscriptionClosed(subscription)) {
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch (e) {
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber) {
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer) {
return new Subscription(observer, this._f);
},
forEach: function forEach(fn) {
var that = this;
return new (core.Promise || global.Promise)(function (resolve, reject) {
aFunction(fn);
var subscription = that.subscribe({
next: function (value) {
try {
return fn(value);
} catch (e) {
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x) {
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if (method) {
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function (observer) {
return observable.subscribe(observer);
});
}
return new C(function (observer) {
var done = false;
microtask(function () {
if (!done) {
try {
if (forOf(x, false, function (it) {
observer.next(it);
if (done) return RETURN;
}) === RETURN) return;
} catch (e) {
if (done) throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function () { done = true; };
});
},
of: function of() {
for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function (observer) {
var done = false;
microtask(function () {
if (!done) {
for (var j = 0; j < items.length; ++j) {
observer.next(items[j]);
if (done) return;
} observer.complete();
}
});
return function () { done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function () { return this; });
$export($export.G, { Observable: $Observable });
__webpack_require__(73)('Observable');
/***/ }),
/* 499 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = __webpack_require__(5);
var microtask = __webpack_require__(168)();
var process = __webpack_require__(11).process;
var isNode = __webpack_require__(42)(process) == 'process';
$export($export.G, {
asap: function asap(fn) {
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
/***/ }),
/* 500 */
/***/ (function(module, exports, __webpack_require__) {
var $metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var aFunction = __webpack_require__(27);
var toMetaKey = $metadata.key;
var ordinaryDefineOwnMetadata = $metadata.set;
$metadata.exp({ metadata: function metadata(metadataKey, metadataValue) {
return function decorator(target, targetKey) {
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
} });
/***/ }),
/* 501 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var ordinaryHasOwnMetadata = metadata.has;
var toMetaKey = metadata.key;
metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 502 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var getPrototypeOf = __webpack_require__(33);
var ordinaryHasOwnMetadata = metadata.has;
var toMetaKey = metadata.key;
var ordinaryHasMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) {
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 503 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var ordinaryOwnMetadataKeys = metadata.keys;
var toMetaKey = metadata.key;
metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) {
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
} });
/***/ }),
/* 504 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var ordinaryGetOwnMetadata = metadata.get;
var toMetaKey = metadata.key;
metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 505 */
/***/ (function(module, exports, __webpack_require__) {
var Set = __webpack_require__(257);
var from = __webpack_require__(248);
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var getPrototypeOf = __webpack_require__(33);
var ordinaryOwnMetadataKeys = metadata.keys;
var toMetaKey = metadata.key;
var ordinaryMetadataKeys = function (O, P) {
var oKeys = ordinaryOwnMetadataKeys(O, P);
var parent = getPrototypeOf(O);
if (parent === null) return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) {
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
} });
/***/ }),
/* 506 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var getPrototypeOf = __webpack_require__(33);
var ordinaryHasOwnMetadata = metadata.has;
var ordinaryGetOwnMetadata = metadata.get;
var toMetaKey = metadata.key;
var ordinaryGetMetadata = function (MetadataKey, O, P) {
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) {
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
} });
/***/ }),
/* 507 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var toMetaKey = metadata.key;
var getOrCreateMetadataMap = metadata.map;
var store = metadata.store;
metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) {
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]);
var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false;
if (metadataMap.size) return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
} });
/***/ }),
/* 508 */
/***/ (function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(57);
var anObject = __webpack_require__(6);
var toMetaKey = metadata.key;
var ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) {
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
} });
/***/ }),
/* 509 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-promise-try
var $export = __webpack_require__(5);
var newPromiseCapability = __webpack_require__(167);
var perform = __webpack_require__(261);
$export($export.S, 'Promise', { 'try': function (callbackfn) {
var promiseCapability = newPromiseCapability.f(this);
var result = perform(callbackfn);
(result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
return promiseCapability.promise;
} });
/***/ }),
/* 510 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-promise-finally
var $export = __webpack_require__(5);
var core = __webpack_require__(44);
var global = __webpack_require__(11);
var speciesConstructor = __webpack_require__(110);
var promiseResolve = __webpack_require__(260);
$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
var C = speciesConstructor(this, core.Promise || global.Promise);
var isFunction = typeof onFinally == 'function';
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
} });
/***/ }),
/* 511 */
/***/ (function(module, exports, __webpack_require__) {
// http://jfbastien.github.io/papers/Math.signbit.html
var $export = __webpack_require__(5);
$export($export.S, 'Math', { signbit: function signbit(x) {
// eslint-disable-next-line no-self-compare
return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0;
} });
/***/ }),
/* 512 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
umulh: function umulh(u, v) {
var UINT16 = 0xffff;
var $u = +u;
var $v = +v;
var u0 = $u & UINT16;
var v0 = $v & UINT16;
var u1 = $u >>> 16;
var v1 = $v >>> 16;
var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
/***/ }),
/* 513 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
$export($export.S, 'Math', { scale: __webpack_require__(247) });
/***/ }),
/* 514 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
var DEG_PER_RAD = Math.PI / 180;
$export($export.S, 'Math', {
radians: function radians(degrees) {
return degrees * DEG_PER_RAD;
}
});
/***/ }),
/* 515 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
$export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI });
/***/ }),
/* 516 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
imulh: function imulh(u, v) {
var UINT16 = 0xffff;
var $u = +u;
var $v = +v;
var u0 = $u & UINT16;
var v0 = $v & UINT16;
var u1 = $u >> 16;
var v1 = $v >> 16;
var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
/***/ }),
/* 517 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1) {
var $x0 = x0 >>> 0;
var $x1 = x1 >>> 0;
var $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
/***/ }),
/* 518 */
/***/ (function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1) {
var $x0 = x0 >>> 0;
var $x1 = x1 >>> 0;
var $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
/***/ }),
/* 519 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
var scale = __webpack_require__(247);
var fround = __webpack_require__(268);
$export($export.S, 'Math', {
fscale: function fscale(x, inLow, inHigh, outLow, outHigh) {
return fround(scale(x, inLow, inHigh, outLow, outHigh));
}
});
/***/ }),
/* 520 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
var RAD_PER_DEG = 180 / Math.PI;
$export($export.S, 'Math', {
degrees: function degrees(radians) {
return radians * RAD_PER_DEG;
}
});
/***/ }),
/* 521 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
$export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 });
/***/ }),
/* 522 */
/***/ (function(module, exports, __webpack_require__) {
// https://rwaldron.github.io/proposal-math-extensions/
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
clamp: function clamp(x, lower, upper) {
return Math.min(upper, Math.max(lower, x));
}
});
/***/ }),
/* 523 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-is-error
var $export = __webpack_require__(5);
var cof = __webpack_require__(42);
$export($export.S, 'Error', {
isError: function isError(it) {
return cof(it) === 'Error';
}
});
/***/ }),
/* 524 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-global
var $export = __webpack_require__(5);
$export($export.S, 'System', { global: __webpack_require__(11) });
/***/ }),
/* 525 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-global
var $export = __webpack_require__(5);
$export($export.G, { global: __webpack_require__(11) });
/***/ }),
/* 526 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from
__webpack_require__(123)('WeakSet');
/***/ }),
/* 527 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from
__webpack_require__(123)('WeakMap');
/***/ }),
/* 528 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from
__webpack_require__(123)('Set');
/***/ }),
/* 529 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from
__webpack_require__(123)('Map');
/***/ }),
/* 530 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of
__webpack_require__(124)('WeakSet');
/***/ }),
/* 531 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of
__webpack_require__(124)('WeakMap');
/***/ }),
/* 532 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of
__webpack_require__(124)('Set');
/***/ }),
/* 533 */
/***/ (function(module, exports, __webpack_require__) {
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of
__webpack_require__(124)('Map');
/***/ }),
/* 534 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(5);
$export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(249)('Set') });
/***/ }),
/* 535 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(5);
$export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(249)('Map') });
/***/ }),
/* 536 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toObject = __webpack_require__(22);
var toPrimitive = __webpack_require__(52);
var getPrototypeOf = __webpack_require__(33);
var getOwnPropertyDescriptor = __webpack_require__(34).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
__webpack_require__(19) && $export($export.P + __webpack_require__(125), 'Object', {
__lookupSetter__: function __lookupSetter__(P) {
var O = toObject(this);
var K = toPrimitive(P, true);
var D;
do {
if (D = getOwnPropertyDescriptor(O, K)) return D.set;
} while (O = getPrototypeOf(O));
}
});
/***/ }),
/* 537 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toObject = __webpack_require__(22);
var toPrimitive = __webpack_require__(52);
var getPrototypeOf = __webpack_require__(33);
var getOwnPropertyDescriptor = __webpack_require__(34).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
__webpack_require__(19) && $export($export.P + __webpack_require__(125), 'Object', {
__lookupGetter__: function __lookupGetter__(P) {
var O = toObject(this);
var K = toPrimitive(P, true);
var D;
do {
if (D = getOwnPropertyDescriptor(O, K)) return D.get;
} while (O = getPrototypeOf(O));
}
});
/***/ }),
/* 538 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toObject = __webpack_require__(22);
var aFunction = __webpack_require__(27);
var $defineProperty = __webpack_require__(21);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
__webpack_require__(19) && $export($export.P + __webpack_require__(125), 'Object', {
__defineSetter__: function __defineSetter__(P, setter) {
$defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true });
}
});
/***/ }),
/* 539 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toObject = __webpack_require__(22);
var aFunction = __webpack_require__(27);
var $defineProperty = __webpack_require__(21);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
__webpack_require__(19) && $export($export.P + __webpack_require__(125), 'Object', {
__defineGetter__: function __defineGetter__(P, getter) {
$defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true });
}
});
/***/ }),
/* 540 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(5);
var $entries = __webpack_require__(250)(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
/***/ }),
/* 541 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(5);
var $values = __webpack_require__(250)(false);
$export($export.S, 'Object', {
values: function values(it) {
return $values(it);
}
});
/***/ }),
/* 542 */
/***/ (function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(5);
var ownKeys = __webpack_require__(253);
var toIObject = __webpack_require__(35);
var gOPD = __webpack_require__(34);
var createProperty = __webpack_require__(176);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIObject(object);
var getDesc = gOPD.f;
var keys = ownKeys(O);
var result = {};
var i = 0;
var key, desc;
while (keys.length > i) {
desc = getDesc(O, key = keys[i++]);
if (desc !== undefined) createProperty(result, key, desc);
}
return result;
}
});
/***/ }),
/* 543 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(191)('observable');
/***/ }),
/* 544 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(191)('asyncIterator');
/***/ }),
/* 545 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/String.prototype.matchAll/
var $export = __webpack_require__(5);
var defined = __webpack_require__(51);
var toLength = __webpack_require__(17);
var isRegExp = __webpack_require__(132);
var getFlags = __webpack_require__(111);
var RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function (regexp, string) {
this._r = regexp;
this._s = string;
};
__webpack_require__(180)($RegExpStringIterator, 'RegExp String', function next() {
var match = this._r.exec(this._s);
return { value: match, done: match === null };
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp) {
defined(this);
if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!');
var S = String(this);
var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp);
var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
/***/ }),
/* 546 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(92)('trimRight', function ($trim) {
return function trimRight() {
return $trim(this, 2);
};
}, 'trimEnd');
/***/ }),
/* 547 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(92)('trimLeft', function ($trim) {
return function trimLeft() {
return $trim(this, 1);
};
}, 'trimStart');
/***/ }),
/* 548 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(5);
var $pad = __webpack_require__(251);
var userAgent = __webpack_require__(128);
// https://github.com/zloirock/core-js/issues/280
var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent);
$export($export.P + $export.F * WEBKIT_BUG, 'String', {
padEnd: function padEnd(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ }),
/* 549 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(5);
var $pad = __webpack_require__(251);
var userAgent = __webpack_require__(128);
// https://github.com/zloirock/core-js/issues/280
var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent);
$export($export.P + $export.F * WEBKIT_BUG, 'String', {
padStart: function padStart(maxLength /* , fillString = ' ' */) {
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ }),
/* 550 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/mathiasbynens/String.prototype.at
var $export = __webpack_require__(5);
var $at = __webpack_require__(133)(true);
$export($export.P, 'String', {
at: function at(pos) {
return $at(this, pos);
}
});
/***/ }),
/* 551 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten
var $export = __webpack_require__(5);
var flattenIntoArray = __webpack_require__(252);
var toObject = __webpack_require__(22);
var toLength = __webpack_require__(17);
var toInteger = __webpack_require__(41);
var arraySpeciesCreate = __webpack_require__(174);
$export($export.P, 'Array', {
flatten: function flatten(/* depthArg = 1 */) {
var depthArg = arguments[0];
var O = toObject(this);
var sourceLen = toLength(O.length);
var A = arraySpeciesCreate(O, 0);
flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
return A;
}
});
__webpack_require__(61)('flatten');
/***/ }),
/* 552 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap
var $export = __webpack_require__(5);
var flattenIntoArray = __webpack_require__(252);
var toObject = __webpack_require__(22);
var toLength = __webpack_require__(17);
var aFunction = __webpack_require__(27);
var arraySpeciesCreate = __webpack_require__(174);
$export($export.P, 'Array', {
flatMap: function flatMap(callbackfn /* , thisArg */) {
var O = toObject(this);
var sourceLen, A;
aFunction(callbackfn);
sourceLen = toLength(O.length);
A = arraySpeciesCreate(O, 0);
flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]);
return A;
}
});
__webpack_require__(61)('flatMap');
/***/ }),
/* 553 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(5);
var $includes = __webpack_require__(136)(true);
$export($export.P, 'Array', {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(61)('includes');
/***/ }),
/* 554 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(5);
var setProto = __webpack_require__(187);
if (setProto) $export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto) {
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch (e) {
return false;
}
}
});
/***/ }),
/* 555 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = __webpack_require__(21);
var gOPD = __webpack_require__(34);
var getPrototypeOf = __webpack_require__(33);
var has = __webpack_require__(36);
var $export = __webpack_require__(5);
var createDesc = __webpack_require__(79);
var anObject = __webpack_require__(6);
var isObject = __webpack_require__(13);
function set(target, propertyKey, V /* , receiver */) {
var receiver = arguments.length < 4 ? target : arguments[3];
var ownDesc = gOPD.f(anObject(target), propertyKey);
var existingDescriptor, proto;
if (!ownDesc) {
if (isObject(proto = getPrototypeOf(target))) {
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if (has(ownDesc, 'value')) {
if (ownDesc.writable === false || !isObject(receiver)) return false;
if (existingDescriptor = gOPD.f(receiver, propertyKey)) {
if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false;
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
} else dP.f(receiver, propertyKey, createDesc(0, V));
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', { set: set });
/***/ }),
/* 556 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(5);
var anObject = __webpack_require__(6);
var $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target) {
anObject(target);
try {
if ($preventExtensions) $preventExtensions(target);
return true;
} catch (e) {
return false;
}
}
});
/***/ }),
/* 557 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(5);
$export($export.S, 'Reflect', { ownKeys: __webpack_require__(253) });
/***/ }),
/* 558 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(5);
var anObject = __webpack_require__(6);
var $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target) {
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ }),
/* 559 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(5);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey) {
return propertyKey in target;
}
});
/***/ }),
/* 560 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(5);
var getProto = __webpack_require__(33);
var anObject = __webpack_require__(6);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target) {
return getProto(anObject(target));
}
});
/***/ }),
/* 561 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = __webpack_require__(34);
var $export = __webpack_require__(5);
var anObject = __webpack_require__(6);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) {
return gOPD.f(anObject(target), propertyKey);
}
});
/***/ }),
/* 562 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = __webpack_require__(34);
var getPrototypeOf = __webpack_require__(33);
var has = __webpack_require__(36);
var $export = __webpack_require__(5);
var isObject = __webpack_require__(13);
var anObject = __webpack_require__(6);
function get(target, propertyKey /* , receiver */) {
var receiver = arguments.length < 3 ? target : arguments[2];
var desc, proto;
if (anObject(target) === receiver) return target[propertyKey];
if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', { get: get });
/***/ }),
/* 563 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(5);
var anObject = __webpack_require__(6);
var Enumerate = function (iterated) {
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = []; // keys
var key;
for (key in iterated) keys.push(key);
};
__webpack_require__(180)(Enumerate, 'Object', function () {
var that = this;
var keys = that._k;
var key;
do {
if (that._i >= keys.length) return { value: undefined, done: true };
} while (!((key = keys[that._i++]) in that._t));
return { value: key, done: false };
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target) {
return new Enumerate(target);
}
});
/***/ }),
/* 564 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(5);
var gOPD = __webpack_require__(34).f;
var anObject = __webpack_require__(6);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey) {
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ }),
/* 565 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = __webpack_require__(21);
var $export = __webpack_require__(5);
var anObject = __webpack_require__(6);
var toPrimitive = __webpack_require__(52);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(12)(function () {
// eslint-disable-next-line no-undef
Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 });
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes) {
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch (e) {
return false;
}
}
});
/***/ }),
/* 566 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = __webpack_require__(5);
var create = __webpack_require__(75);
var aFunction = __webpack_require__(27);
var anObject = __webpack_require__(6);
var isObject = __webpack_require__(13);
var fails = __webpack_require__(12);
var bind = __webpack_require__(275);
var rConstruct = (__webpack_require__(11).Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function () {
function F() { /* empty */ }
return !(rConstruct(function () { /* empty */ }, [], F) instanceof F);
});
var ARGS_BUG = !fails(function () {
rConstruct(function () { /* empty */ });
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
construct: function construct(Target, args /* , newTarget */) {
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget);
if (Target == newTarget) {
// w/o altered newTarget, optimization for 0-4 arguments
switch (args.length) {
case 0: return new Target();
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args))();
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype;
var instance = create(isObject(proto) ? proto : Object.prototype);
var result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ }),
/* 567 */
/***/ (function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(5);
var aFunction = __webpack_require__(27);
var anObject = __webpack_require__(6);
var rApply = (__webpack_require__(11).Reflect || {}).apply;
var fApply = Function.apply;
// MS Edge argumentsList argument is optional
$export($export.S + $export.F * !__webpack_require__(12)(function () {
rApply(function () { /* empty */ });
}), 'Reflect', {
apply: function apply(target, thisArgument, argumentsList) {
var T = aFunction(target);
var L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
/***/ }),
/* 568 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Float64', 8, function (init) {
return function Float64Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 569 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Float32', 4, function (init) {
return function Float32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 570 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint32', 4, function (init) {
return function Uint32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 571 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Int32', 4, function (init) {
return function Int32Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 572 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint16', 2, function (init) {
return function Uint16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 573 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Int16', 2, function (init) {
return function Int16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 574 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint8', 1, function (init) {
return function Uint8ClampedArray(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
}, true);
/***/ }),
/* 575 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Uint8', 1, function (init) {
return function Uint8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 576 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(58)('Int8', 1, function (init) {
return function Int8Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
/***/ }),
/* 577 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
$export($export.G + $export.W + $export.F * !__webpack_require__(126).ABV, {
DataView: __webpack_require__(166).DataView
});
/***/ }),
/* 578 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $typed = __webpack_require__(126);
var buffer = __webpack_require__(166);
var anObject = __webpack_require__(6);
var toAbsoluteIndex = __webpack_require__(76);
var toLength = __webpack_require__(17);
var isObject = __webpack_require__(13);
var ArrayBuffer = __webpack_require__(11).ArrayBuffer;
var speciesConstructor = __webpack_require__(110);
var $ArrayBuffer = buffer.ArrayBuffer;
var $DataView = buffer.DataView;
var $isView = $typed.ABV && ArrayBuffer.isView;
var $slice = $ArrayBuffer.prototype.slice;
var VIEW = $typed.VIEW;
var ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer });
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it) {
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * __webpack_require__(12)(function () {
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end) {
if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength;
var first = toAbsoluteIndex(start, len);
var fin = toAbsoluteIndex(end === undefined ? len : end, len);
var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first));
var viewS = new $DataView(this);
var viewT = new $DataView(result);
var index = 0;
while (first < fin) {
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
__webpack_require__(73)(ARRAY_BUFFER);
/***/ }),
/* 579 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var weak = __webpack_require__(255);
var validate = __webpack_require__(69);
var WEAK_SET = 'WeakSet';
// 23.4 WeakSet Objects
__webpack_require__(127)(WEAK_SET, function (get) {
return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value) {
return weak.def(validate(this, WEAK_SET), value, true);
}
}, weak, false, true);
/***/ }),
/* 580 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LIBRARY = __webpack_require__(63);
var global = __webpack_require__(11);
var ctx = __webpack_require__(43);
var classof = __webpack_require__(93);
var $export = __webpack_require__(5);
var isObject = __webpack_require__(13);
var aFunction = __webpack_require__(27);
var anInstance = __webpack_require__(72);
var forOf = __webpack_require__(71);
var speciesConstructor = __webpack_require__(110);
var task = __webpack_require__(169).set;
var microtask = __webpack_require__(168)();
var newPromiseCapabilityModule = __webpack_require__(167);
var perform = __webpack_require__(261);
var userAgent = __webpack_require__(128);
var promiseResolve = __webpack_require__(260);
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var FakePromise = (promise.constructor = {})[__webpack_require__(16)('species')] = function (exec) {
exec(empty, empty);
};
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function')
&& promise.then(empty) instanceof FakePromise
// v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// we can't detect it synchronously, so just check versions
&& v8.indexOf('6.6') !== 0
&& userAgent.indexOf('Chrome/66') === -1;
} catch (e) { /* empty */ }
}();
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // may throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (e) {
if (domain && !exited) domain.exit();
reject(e);
}
};
while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if (isReject && !promise._h) onUnhandled(promise);
});
};
var onUnhandled = function (promise) {
task.call(global, function () {
var value = promise._v;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = perform(function () {
if (isNode) {
process.emit('unhandledRejection', value, promise);
} else if (handler = global.onunhandledrejection) {
handler({ promise: promise, reason: value });
} else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global, function () {
var handler;
if (isNode) {
process.emit('rejectionHandled', promise);
} else if (handler = global.onrejectionhandled) {
handler({ promise: promise, reason: promise._v });
}
});
};
var $reject = function (value) {
var promise = this;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function (value) {
var promise = this;
var then;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if (promise === value) throw TypeError("Promise can't be resolved itself");
if (then = isThenable(value)) {
microtask(function () {
var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch (e) {
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch (e) {
$reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch (err) {
$reject.call(this, err);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(70)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected) {
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if (this._a) this._a.push(reaction);
if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
__webpack_require__(94)($Promise, PROMISE);
__webpack_require__(73)(PROMISE);
Wrapper = __webpack_require__(44)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r) {
var capability = newPromiseCapability(this);
var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(131)(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
/***/ }),
/* 581 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isRegExp = __webpack_require__(132);
var anObject = __webpack_require__(6);
var speciesConstructor = __webpack_require__(110);
var advanceStringIndex = __webpack_require__(170);
var toLength = __webpack_require__(17);
var callRegExpExec = __webpack_require__(130);
var regexpExec = __webpack_require__(171);
var fails = __webpack_require__(12);
var $min = Math.min;
var $push = [].push;
var $SPLIT = 'split';
var LENGTH = 'length';
var LAST_INDEX = 'lastIndex';
var MAX_UINT32 = 0xffffffff;
// babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
var SUPPORTS_Y = !fails(function () { RegExp(MAX_UINT32, 'y'); });
// @@split logic
__webpack_require__(129)('split', 2, function (defined, SPLIT, $split, maybeCallNative) {
var internalSplit;
if (
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
) {
// based on es5-shim implementation, need to rework it
internalSplit = function (separator, limit) {
var string = String(this);
if (separator === undefined && limit === 0) return [];
// If `separator` is not a regex, use native split
if (!isRegExp(separator)) return $split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? MAX_UINT32 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var match, lastIndex, lastLength;
while (match = regexpExec.call(separatorCopy, string)) {
lastIndex = separatorCopy[LAST_INDEX];
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if (output[LENGTH] >= splitLimit) break;
}
if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if (lastLastIndex === string[LENGTH]) {
if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if ('0'[$SPLIT](undefined, 0)[LENGTH]) {
internalSplit = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : $split.call(this, separator, limit);
};
} else {
internalSplit = $split;
}
return [
// `String.prototype.split` method
// https://tc39.github.io/ecma262/#sec-string.prototype.split
function split(separator, limit) {
var O = defined(this);
var splitter = separator == undefined ? undefined : separator[SPLIT];
return splitter !== undefined
? splitter.call(separator, O, limit)
: internalSplit.call(String(O), separator, limit);
},
// `RegExp.prototype[@@split]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
//
// NOTE: This cannot be properly polyfilled in engines that don't support
// the 'y' flag.
function (regexp, limit) {
var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== $split);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var C = speciesConstructor(rx, RegExp);
var unicodeMatching = rx.unicode;
var flags = (rx.ignoreCase ? 'i' : '') +
(rx.multiline ? 'm' : '') +
(rx.unicode ? 'u' : '') +
(SUPPORTS_Y ? 'y' : 'g');
// ^(? + rx + ) is needed, in combination with some S slicing, to
// simulate the 'y' flag.
var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
if (lim === 0) return [];
if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : [];
var p = 0;
var q = 0;
var A = [];
while (q < S.length) {
splitter.lastIndex = SUPPORTS_Y ? q : 0;
var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q));
var e;
if (
z === null ||
(e = $min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p
) {
q = advanceStringIndex(S, q, unicodeMatching);
} else {
A.push(S.slice(p, q));
if (A.length === lim) return A;
for (var i = 1; i <= z.length - 1; i++) {
A.push(z[i]);
if (A.length === lim) return A;
}
q = p = e;
}
}
A.push(S.slice(p));
return A;
}
];
});
/***/ }),
/* 582 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__(6);
var sameValue = __webpack_require__(276);
var regExpExec = __webpack_require__(130);
// @@search logic
__webpack_require__(129)('search', 1, function (defined, SEARCH, $search, maybeCallNative) {
return [
// `String.prototype.search` method
// https://tc39.github.io/ecma262/#sec-string.prototype.search
function search(regexp) {
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
},
// `RegExp.prototype[@@search]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
function (regexp) {
var res = maybeCallNative($search, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var previousLastIndex = rx.lastIndex;
if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
var result = regExpExec(rx, S);
if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
return result === null ? -1 : result.index;
}
];
});
/***/ }),
/* 583 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__(6);
var toObject = __webpack_require__(22);
var toLength = __webpack_require__(17);
var toInteger = __webpack_require__(41);
var advanceStringIndex = __webpack_require__(170);
var regExpExec = __webpack_require__(130);
var max = Math.max;
var min = Math.min;
var floor = Math.floor;
var SUBSTITUTION_SYMBOLS = /\$([$&`']|\d\d?|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&`']|\d\d?)/g;
var maybeToString = function (it) {
return it === undefined ? it : String(it);
};
// @@replace logic
__webpack_require__(129)('replace', 2, function (defined, REPLACE, $replace, maybeCallNative) {
return [
// `String.prototype.replace` method
// https://tc39.github.io/ecma262/#sec-string.prototype.replace
function replace(searchValue, replaceValue) {
var O = defined(this);
var fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
function (regexp, replaceValue) {
var res = maybeCallNative($replace, regexp, this, replaceValue);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var functionalReplace = typeof replaceValue === 'function';
if (!functionalReplace) replaceValue = String(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regExpExec(rx, S);
if (result === null) break;
results.push(result);
if (!global) break;
var matchStr = String(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = String(result[0]);
var position = max(min(toInteger(result.index), S.length), 0);
var captures = [];
// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = [matched].concat(captures, position, S);
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
var replacement = String(replaceValue.apply(undefined, replacerArgs));
} else {
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + S.slice(nextSourcePosition);
}
];
// https://tc39.github.io/ecma262/#sec-getsubstitution
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
var tailPos = position + matched.length;
var m = captures.length;
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
if (namedCaptures !== undefined) {
namedCaptures = toObject(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return $replace.call(replacement, symbols, function (match, ch) {
var capture;
switch (ch.charAt(0)) {
case '$': return '$';
case '&': return matched;
case '`': return str.slice(0, position);
case "'": return str.slice(tailPos);
case '<':
capture = namedCaptures[ch.slice(1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
}
});
/***/ }),
/* 584 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__(6);
var toLength = __webpack_require__(17);
var advanceStringIndex = __webpack_require__(170);
var regExpExec = __webpack_require__(130);
// @@match logic
__webpack_require__(129)('match', 1, function (defined, MATCH, $match, maybeCallNative) {
return [
// `String.prototype.match` method
// https://tc39.github.io/ecma262/#sec-string.prototype.match
function match(regexp) {
var O = defined(this);
var fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
},
// `RegExp.prototype[@@match]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
function (regexp) {
var res = maybeCallNative($match, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
if (!rx.global) return regExpExec(rx, S);
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
var A = [];
var n = 0;
var result;
while ((result = regExpExec(rx, S)) !== null) {
var matchStr = String(result[0]);
A[n] = matchStr;
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
n++;
}
return n === 0 ? null : A;
}
];
});
/***/ }),
/* 585 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__(262);
var anObject = __webpack_require__(6);
var $flags = __webpack_require__(111);
var DESCRIPTORS = __webpack_require__(19);
var TO_STRING = 'toString';
var $toString = /./[TO_STRING];
var define = function (fn) {
__webpack_require__(30)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if (__webpack_require__(12)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) {
define(function toString() {
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if ($toString.name != TO_STRING) {
define(function toString() {
return $toString.call(this);
});
}
/***/ }),
/* 586 */
/***/ (function(module, exports, __webpack_require__) {
var global = __webpack_require__(11);
var inheritIfRequired = __webpack_require__(185);
var dP = __webpack_require__(21).f;
var gOPN = __webpack_require__(74).f;
var isRegExp = __webpack_require__(132);
var $flags = __webpack_require__(111);
var $RegExp = global.RegExp;
var Base = $RegExp;
var proto = $RegExp.prototype;
var re1 = /a/g;
var re2 = /a/g;
// "new" creates a new object, old webkit buggy here
var CORRECT_NEW = new $RegExp(re1) !== re1;
if (__webpack_require__(19) && (!CORRECT_NEW || __webpack_require__(12)(function () {
re2[__webpack_require__(16)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))) {
$RegExp = function RegExp(p, f) {
var tiRE = this instanceof $RegExp;
var piRE = isRegExp(p);
var fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function (key) {
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function () { return Base[key]; },
set: function (it) { Base[key] = it; }
});
};
for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(30)(global, 'RegExp', $RegExp);
}
__webpack_require__(73)('RegExp');
/***/ }),
/* 587 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(73)('Array');
/***/ }),
/* 588 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(5);
var $find = __webpack_require__(49)(6);
var KEY = 'findIndex';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(61)(KEY);
/***/ }),
/* 589 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(5);
var $find = __webpack_require__(49)(5);
var KEY = 'find';
var forced = true;
// Shouldn't skip holes
if (KEY in []) Array(1)[KEY](function () { forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(61)(KEY);
/***/ }),
/* 590 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(5);
$export($export.P, 'Array', { fill: __webpack_require__(173) });
__webpack_require__(61)('fill');
/***/ }),
/* 591 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(5);
$export($export.P, 'Array', { copyWithin: __webpack_require__(265) });
__webpack_require__(61)('copyWithin');
/***/ }),
/* 592 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toIObject = __webpack_require__(35);
var toInteger = __webpack_require__(41);
var toLength = __webpack_require__(17);
var $native = [].lastIndexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(40)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0;
var O = toIObject(this);
var length = toLength(O.length);
var index = length - 1;
if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0;
return -1;
}
});
/***/ }),
/* 593 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $indexOf = __webpack_require__(136)(false);
var $native = [].indexOf;
var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(40)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ }),
/* 594 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $reduce = __webpack_require__(266);
$export($export.P + $export.F * !__webpack_require__(40)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
/***/ }),
/* 595 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $reduce = __webpack_require__(266);
$export($export.P + $export.F * !__webpack_require__(40)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */) {
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ }),
/* 596 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $every = __webpack_require__(49)(4);
$export($export.P + $export.F * !__webpack_require__(40)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 597 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $some = __webpack_require__(49)(3);
$export($export.P + $export.F * !__webpack_require__(40)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 598 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $filter = __webpack_require__(49)(2);
$export($export.P + $export.F * !__webpack_require__(40)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 599 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $map = __webpack_require__(49)(1);
$export($export.P + $export.F * !__webpack_require__(40)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 600 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(13);
var isArray = __webpack_require__(134);
var SPECIES = __webpack_require__(16)('species');
module.exports = function (original) {
var C;
if (isArray(original)) {
C = original.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ }),
/* 601 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $forEach = __webpack_require__(49)(0);
var STRICT = __webpack_require__(40)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */) {
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ }),
/* 602 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var aFunction = __webpack_require__(27);
var toObject = __webpack_require__(22);
var fails = __webpack_require__(12);
var $sort = [].sort;
var test = [1, 2, 3];
$export($export.P + $export.F * (fails(function () {
// IE8-
test.sort(undefined);
}) || !fails(function () {
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__(40)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn) {
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ }),
/* 603 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var html = __webpack_require__(188);
var cof = __webpack_require__(42);
var toAbsoluteIndex = __webpack_require__(76);
var toLength = __webpack_require__(17);
var arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__(12)(function () {
if (html) arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end) {
var len = toLength(this.length);
var klass = cof(this);
end = end === undefined ? len : end;
if (klass == 'Array') return arraySlice.call(this, begin, end);
var start = toAbsoluteIndex(begin, len);
var upTo = toAbsoluteIndex(end, len);
var size = toLength(upTo - start);
var cloned = new Array(size);
var i = 0;
for (; i < size; i++) cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ }),
/* 604 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 22.1.3.13 Array.prototype.join(separator)
var $export = __webpack_require__(5);
var toIObject = __webpack_require__(35);
var arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (__webpack_require__(113) != Object || !__webpack_require__(40)(arrayJoin)), 'Array', {
join: function join(separator) {
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
/***/ }),
/* 605 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var createProperty = __webpack_require__(176);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(12)(function () {
function F() { /* empty */ }
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */) {
var index = 0;
var aLen = arguments.length;
var result = new (typeof this == 'function' ? this : Array)(aLen);
while (aLen > index) createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ }),
/* 606 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ctx = __webpack_require__(43);
var $export = __webpack_require__(5);
var toObject = __webpack_require__(22);
var call = __webpack_require__(267);
var isArrayIter = __webpack_require__(177);
var toLength = __webpack_require__(17);
var createProperty = __webpack_require__(176);
var getIterFn = __webpack_require__(175);
$export($export.S + $export.F * !__webpack_require__(131)(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ }),
/* 607 */
/***/ (function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(5);
$export($export.S, 'Array', { isArray: __webpack_require__(134) });
/***/ }),
/* 608 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var anObject = __webpack_require__(6);
var toPrimitive = __webpack_require__(52);
var NUMBER = 'number';
module.exports = function (hint) {
if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
/***/ }),
/* 609 */
/***/ (function(module, exports, __webpack_require__) {
var TO_PRIMITIVE = __webpack_require__(16)('toPrimitive');
var proto = Date.prototype;
if (!(TO_PRIMITIVE in proto)) __webpack_require__(31)(proto, TO_PRIMITIVE, __webpack_require__(608));
/***/ }),
/* 610 */
/***/ (function(module, exports, __webpack_require__) {
var DateProto = Date.prototype;
var INVALID_DATE = 'Invalid Date';
var TO_STRING = 'toString';
var $toString = DateProto[TO_STRING];
var getTime = DateProto.getTime;
if (new Date(NaN) + '' != INVALID_DATE) {
__webpack_require__(30)(DateProto, TO_STRING, function toString() {
var value = getTime.call(this);
// eslint-disable-next-line no-self-compare
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
/***/ }),
/* 611 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var fails = __webpack_require__(12);
var getTime = Date.prototype.getTime;
var $toISOString = Date.prototype.toISOString;
var lz = function (num) {
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
module.exports = (fails(function () {
return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z';
}) || !fails(function () {
$toISOString.call(new Date(NaN));
})) ? function toISOString() {
if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value');
var d = this;
var y = d.getUTCFullYear();
var m = d.getUTCMilliseconds();
var s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
} : $toISOString;
/***/ }),
/* 612 */
/***/ (function(module, exports, __webpack_require__) {
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__(5);
var toISOString = __webpack_require__(611);
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', {
toISOString: toISOString
});
/***/ }),
/* 613 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toObject = __webpack_require__(22);
var toPrimitive = __webpack_require__(52);
$export($export.P + $export.F * __webpack_require__(12)(function () {
return new Date(NaN).toJSON() !== null
|| Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1;
}), 'Date', {
// eslint-disable-next-line no-unused-vars
toJSON: function toJSON(key) {
var O = toObject(this);
var pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
/***/ }),
/* 614 */
/***/ (function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(5);
$export($export.S, 'Date', { now: function () { return new Date().getTime(); } });
/***/ }),
/* 615 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.14 String.prototype.sup()
__webpack_require__(29)('sup', function (createHTML) {
return function sup() {
return createHTML(this, 'sup', '', '');
};
});
/***/ }),
/* 616 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.13 String.prototype.sub()
__webpack_require__(29)('sub', function (createHTML) {
return function sub() {
return createHTML(this, 'sub', '', '');
};
});
/***/ }),
/* 617 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.12 String.prototype.strike()
__webpack_require__(29)('strike', function (createHTML) {
return function strike() {
return createHTML(this, 'strike', '', '');
};
});
/***/ }),
/* 618 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.11 String.prototype.small()
__webpack_require__(29)('small', function (createHTML) {
return function small() {
return createHTML(this, 'small', '', '');
};
});
/***/ }),
/* 619 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.10 String.prototype.link(url)
__webpack_require__(29)('link', function (createHTML) {
return function link(url) {
return createHTML(this, 'a', 'href', url);
};
});
/***/ }),
/* 620 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.9 String.prototype.italics()
__webpack_require__(29)('italics', function (createHTML) {
return function italics() {
return createHTML(this, 'i', '', '');
};
});
/***/ }),
/* 621 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(29)('fontsize', function (createHTML) {
return function fontsize(size) {
return createHTML(this, 'font', 'size', size);
};
});
/***/ }),
/* 622 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(29)('fontcolor', function (createHTML) {
return function fontcolor(color) {
return createHTML(this, 'font', 'color', color);
};
});
/***/ }),
/* 623 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.6 String.prototype.fixed()
__webpack_require__(29)('fixed', function (createHTML) {
return function fixed() {
return createHTML(this, 'tt', '', '');
};
});
/***/ }),
/* 624 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.5 String.prototype.bold()
__webpack_require__(29)('bold', function (createHTML) {
return function bold() {
return createHTML(this, 'b', '', '');
};
});
/***/ }),
/* 625 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.4 String.prototype.blink()
__webpack_require__(29)('blink', function (createHTML) {
return function blink() {
return createHTML(this, 'blink', '', '');
};
});
/***/ }),
/* 626 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.3 String.prototype.big()
__webpack_require__(29)('big', function (createHTML) {
return function big() {
return createHTML(this, 'big', '', '');
};
});
/***/ }),
/* 627 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(29)('anchor', function (createHTML) {
return function anchor(name) {
return createHTML(this, 'a', 'name', name);
};
});
/***/ }),
/* 628 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
var $export = __webpack_require__(5);
var toLength = __webpack_require__(17);
var context = __webpack_require__(179);
var STARTS_WITH = 'startsWith';
var $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(178)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = context(this, searchString, STARTS_WITH);
var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ }),
/* 629 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(184)
});
/***/ }),
/* 630 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
var $export = __webpack_require__(5);
var context = __webpack_require__(179);
var INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(178)(INCLUDES), 'String', {
includes: function includes(searchString /* , position = 0 */) {
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ }),
/* 631 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
var $export = __webpack_require__(5);
var toLength = __webpack_require__(17);
var context = __webpack_require__(179);
var ENDS_WITH = 'endsWith';
var $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(178)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /* , endPosition = @length */) {
var that = context(this, searchString, ENDS_WITH);
var endPosition = arguments.length > 1 ? arguments[1] : undefined;
var len = toLength(that.length);
var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len);
var search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ }),
/* 632 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $at = __webpack_require__(133)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos) {
return $at(this, pos);
}
});
/***/ }),
/* 633 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $at = __webpack_require__(133)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(181)(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
/***/ }),
/* 634 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 21.1.3.25 String.prototype.trim()
__webpack_require__(92)('trim', function ($trim) {
return function trim() {
return $trim(this, 3);
};
});
/***/ }),
/* 635 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var toIObject = __webpack_require__(35);
var toLength = __webpack_require__(17);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite) {
var tpl = toIObject(callSite.raw);
var len = toLength(tpl.length);
var aLen = arguments.length;
var res = [];
var i = 0;
while (len > i) {
res.push(String(tpl[i++]));
if (i < aLen) res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ }),
/* 636 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var toAbsoluteIndex = __webpack_require__(76);
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
var res = [];
var aLen = arguments.length;
var i = 0;
var code;
while (aLen > i) {
code = +arguments[i++];
if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ }),
/* 637 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
trunc: function trunc(it) {
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ }),
/* 638 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(5);
var expm1 = __webpack_require__(182);
var exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x) {
var a = expm1(x = +x);
var b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ }),
/* 639 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(5);
var expm1 = __webpack_require__(182);
var exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(12)(function () {
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x) {
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ }),
/* 640 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', { sign: __webpack_require__(183) });
/***/ }),
/* 641 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
log2: function log2(x) {
return Math.log(x) / Math.LN2;
}
});
/***/ }),
/* 642 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', { log1p: __webpack_require__(269) });
/***/ }),
/* 643 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
log10: function log10(x) {
return Math.log(x) * Math.LOG10E;
}
});
/***/ }),
/* 644 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(5);
var $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(12)(function () {
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y) {
var UINT16 = 0xffff;
var xn = +x;
var yn = +y;
var xl = UINT16 & xn;
var yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ }),
/* 645 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(5);
var abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars
var sum = 0;
var i = 0;
var aLen = arguments.length;
var larg = 0;
var arg, div;
while (i < aLen) {
arg = abs(arguments[i++]);
if (larg < arg) {
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if (arg > 0) {
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ }),
/* 646 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', { fround: __webpack_require__(268) });
/***/ }),
/* 647 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(5);
var $expm1 = __webpack_require__(182);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 });
/***/ }),
/* 648 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(5);
var exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x) {
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ }),
/* 649 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(5);
$export($export.S, 'Math', {
clz32: function clz32(x) {
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ }),
/* 650 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(5);
var sign = __webpack_require__(183);
$export($export.S, 'Math', {
cbrt: function cbrt(x) {
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ }),
/* 651 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(5);
var $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x) {
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ }),
/* 652 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(5);
var $asinh = Math.asinh;
function asinh(x) {
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh });
/***/ }),
/* 653 */
/***/ (function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(5);
var log1p = __webpack_require__(269);
var sqrt = Math.sqrt;
var $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x) {
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ }),
/* 654 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var $parseInt = __webpack_require__(273);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt });
/***/ }),
/* 655 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var $parseFloat = __webpack_require__(272);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat });
/***/ }),
/* 656 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(5);
$export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff });
/***/ }),
/* 657 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(5);
$export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff });
/***/ }),
/* 658 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(5);
var isInteger = __webpack_require__(270);
var abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number) {
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ }),
/* 659 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(5);
$export($export.S, 'Number', {
isNaN: function isNaN(number) {
// eslint-disable-next-line no-self-compare
return number != number;
}
});
/***/ }),
/* 660 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(5);
$export($export.S, 'Number', { isInteger: __webpack_require__(270) });
/***/ }),
/* 661 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(5);
var _isFinite = __webpack_require__(11).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it) {
return typeof it == 'number' && _isFinite(it);
}
});
/***/ }),
/* 662 */
/***/ (function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(5);
$export($export.S, 'Number', { EPSILON: Math.pow(2, -52) });
/***/ }),
/* 663 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var $fails = __webpack_require__(12);
var aNumberValue = __webpack_require__(271);
var $toPrecision = 1.0.toPrecision;
$export($export.P + $export.F * ($fails(function () {
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function () {
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision) {
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
/***/ }),
/* 664 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var $export = __webpack_require__(5);
var toInteger = __webpack_require__(41);
var aNumberValue = __webpack_require__(271);
var repeat = __webpack_require__(184);
var $toFixed = 1.0.toFixed;
var floor = Math.floor;
var data = [0, 0, 0, 0, 0, 0];
var ERROR = 'Number.toFixed: incorrect invocation!';
var ZERO = '0';
var multiply = function (n, c) {
var i = -1;
var c2 = c;
while (++i < 6) {
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function (n) {
var i = 6;
var c = 0;
while (--i >= 0) {
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function () {
var i = 6;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || data[i] !== 0) {
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function (x, n, acc) {
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function (x) {
var n = 0;
var x2 = x;
while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
while (x2 >= 2) {
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128.0.toFixed(0) !== '1000000000000000128'
) || !__webpack_require__(12)(function () {
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits) {
var x = aNumberValue(this, ERROR);
var f = toInteger(fractionDigits);
var s = '';
var m = ZERO;
var e, z, j, k;
if (f < 0 || f > 20) throw RangeError(ERROR);
// eslint-disable-next-line no-self-compare
if (x != x) return 'NaN';
if (x <= -1e21 || x >= 1e21) return String(x);
if (x < 0) {
s = '-';
x = -x;
}
if (x > 1e-21) {
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if (e > 0) {
multiply(0, z);
j = f;
while (j >= 7) {
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if (f > 0) {
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
/***/ }),
/* 665 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var global = __webpack_require__(11);
var has = __webpack_require__(36);
var cof = __webpack_require__(42);
var inheritIfRequired = __webpack_require__(185);
var toPrimitive = __webpack_require__(52);
var fails = __webpack_require__(12);
var gOPN = __webpack_require__(74).f;
var gOPD = __webpack_require__(34).f;
var dP = __webpack_require__(21).f;
var $trim = __webpack_require__(92).trim;
var NUMBER = 'Number';
var $Number = global[NUMBER];
var Base = $Number;
var proto = $Number.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_COF = cof(__webpack_require__(75)(proto)) == NUMBER;
var TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function (argument) {
var it = toPrimitive(argument, false);
if (typeof it == 'string' && it.length > 2) {
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0);
var third, radix, maxCode;
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default: return +it;
}
for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) {
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) {
$Number = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for (var keys = __webpack_require__(19) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++) {
if (has(Base, key = keys[j]) && !has($Number, key)) {
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__(30)(global, NUMBER, $Number);
}
/***/ }),
/* 666 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var $parseFloat = __webpack_require__(272);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat });
/***/ }),
/* 667 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
var $parseInt = __webpack_require__(273);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt });
/***/ }),
/* 668 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isObject = __webpack_require__(13);
var getPrototypeOf = __webpack_require__(33);
var HAS_INSTANCE = __webpack_require__(16)('hasInstance');
var FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(21).f(FunctionProto, HAS_INSTANCE, { value: function (O) {
if (typeof this != 'function' || !isObject(O)) return false;
if (!isObject(this.prototype)) return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
return false;
} });
/***/ }),
/* 669 */
/***/ (function(module, exports, __webpack_require__) {
var dP = __webpack_require__(21).f;
var FProto = Function.prototype;
var nameRE = /^\s*function ([^ (]*)/;
var NAME = 'name';
// 19.2.4.2 name
NAME in FProto || __webpack_require__(19) && dP(FProto, NAME, {
configurable: true,
get: function () {
try {
return ('' + this).match(nameRE)[1];
} catch (e) {
return '';
}
}
});
/***/ }),
/* 670 */
/***/ (function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(5);
$export($export.P, 'Function', { bind: __webpack_require__(275) });
/***/ }),
/* 671 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__(93);
var test = {};
test[__webpack_require__(16)('toStringTag')] = 'z';
if (test + '' != '[object z]') {
__webpack_require__(30)(Object.prototype, 'toString', function toString() {
return '[object ' + classof(this) + ']';
}, true);
}
/***/ }),
/* 672 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(5);
$export($export.S, 'Object', { setPrototypeOf: __webpack_require__(187).set });
/***/ }),
/* 673 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(5);
$export($export.S, 'Object', { is: __webpack_require__(276) });
/***/ }),
/* 674 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(5);
$export($export.S + $export.F, 'Object', { assign: __webpack_require__(277) });
/***/ }),
/* 675 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(13);
__webpack_require__(50)('isExtensible', function ($isExtensible) {
return function isExtensible(it) {
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ }),
/* 676 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(13);
__webpack_require__(50)('isSealed', function ($isSealed) {
return function isSealed(it) {
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ }),
/* 677 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(13);
__webpack_require__(50)('isFrozen', function ($isFrozen) {
return function isFrozen(it) {
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ }),
/* 678 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(13);
var meta = __webpack_require__(62).onFreeze;
__webpack_require__(50)('preventExtensions', function ($preventExtensions) {
return function preventExtensions(it) {
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ }),
/* 679 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(13);
var meta = __webpack_require__(62).onFreeze;
__webpack_require__(50)('seal', function ($seal) {
return function seal(it) {
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ }),
/* 680 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(13);
var meta = __webpack_require__(62).onFreeze;
__webpack_require__(50)('freeze', function ($freeze) {
return function freeze(it) {
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ }),
/* 681 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(50)('getOwnPropertyNames', function () {
return __webpack_require__(278).f;
});
/***/ }),
/* 682 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(22);
var $keys = __webpack_require__(77);
__webpack_require__(50)('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
/***/ }),
/* 683 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(22);
var $getPrototypeOf = __webpack_require__(33);
__webpack_require__(50)('getPrototypeOf', function () {
return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
/***/ }),
/* 684 */
/***/ (function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(35);
var $getOwnPropertyDescriptor = __webpack_require__(34).f;
__webpack_require__(50)('getOwnPropertyDescriptor', function () {
return function getOwnPropertyDescriptor(it, key) {
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ }),
/* 685 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__(19), 'Object', { defineProperties: __webpack_require__(279) });
/***/ }),
/* 686 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(19), 'Object', { defineProperty: __webpack_require__(21).f });
/***/ }),
/* 687 */
/***/ (function(module, exports, __webpack_require__) {
var $export = __webpack_require__(5);
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: __webpack_require__(75) });
/***/ }),
/* 688 */
/***/ (function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(77);
var gOPS = __webpack_require__(135);
var pIE = __webpack_require__(112);
module.exports = function (it) {
var result = getKeys(it);
var getSymbols = gOPS.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = pIE.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
/***/ }),
/* 689 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(114)('native-function-to-string', Function.toString);
/***/ }),
/* 690 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// ECMAScript 6 symbols shim
var global = __webpack_require__(11);
var has = __webpack_require__(36);
var DESCRIPTORS = __webpack_require__(19);
var $export = __webpack_require__(5);
var redefine = __webpack_require__(30);
var META = __webpack_require__(62).KEY;
var $fails = __webpack_require__(12);
var shared = __webpack_require__(114);
var setToStringTag = __webpack_require__(94);
var uid = __webpack_require__(78);
var wks = __webpack_require__(16);
var wksExt = __webpack_require__(281);
var wksDefine = __webpack_require__(191);
var enumKeys = __webpack_require__(688);
var isArray = __webpack_require__(134);
var anObject = __webpack_require__(6);
var isObject = __webpack_require__(13);
var toObject = __webpack_require__(22);
var toIObject = __webpack_require__(35);
var toPrimitive = __webpack_require__(52);
var createDesc = __webpack_require__(79);
var _create = __webpack_require__(75);
var gOPNExt = __webpack_require__(278);
var $GOPD = __webpack_require__(34);
var $GOPS = __webpack_require__(135);
var $DP = __webpack_require__(21);
var $keys = __webpack_require__(77);
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if (has(AllSymbols, key)) {
if (!D.enumerable) {
if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
anObject(it);
var keys = enumKeys(P = toIObject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = toIObject(it);
key = toPrimitive(key, true);
if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN(toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto) $set.call(OPSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(74).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(112).f = $propertyIsEnumerable;
$GOPS.f = $getOwnPropertySymbols;
if (DESCRIPTORS && !__webpack_require__(63)) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function (name) {
return wrap(wks(name));
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });
$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return $GOPS.f(toObject(it));
}
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(31)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ }),
/* 691 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(690);
__webpack_require__(687);
__webpack_require__(686);
__webpack_require__(685);
__webpack_require__(684);
__webpack_require__(683);
__webpack_require__(682);
__webpack_require__(681);
__webpack_require__(680);
__webpack_require__(679);
__webpack_require__(678);
__webpack_require__(677);
__webpack_require__(676);
__webpack_require__(675);
__webpack_require__(674);
__webpack_require__(673);
__webpack_require__(672);
__webpack_require__(671);
__webpack_require__(670);
__webpack_require__(669);
__webpack_require__(668);
__webpack_require__(667);
__webpack_require__(666);
__webpack_require__(665);
__webpack_require__(664);
__webpack_require__(663);
__webpack_require__(662);
__webpack_require__(661);
__webpack_require__(660);
__webpack_require__(659);
__webpack_require__(658);
__webpack_require__(657);
__webpack_require__(656);
__webpack_require__(655);
__webpack_require__(654);
__webpack_require__(653);
__webpack_require__(652);
__webpack_require__(651);
__webpack_require__(650);
__webpack_require__(649);
__webpack_require__(648);
__webpack_require__(647);
__webpack_require__(646);
__webpack_require__(645);
__webpack_require__(644);
__webpack_require__(643);
__webpack_require__(642);
__webpack_require__(641);
__webpack_require__(640);
__webpack_require__(639);
__webpack_require__(638);
__webpack_require__(637);
__webpack_require__(636);
__webpack_require__(635);
__webpack_require__(634);
__webpack_require__(633);
__webpack_require__(632);
__webpack_require__(631);
__webpack_require__(630);
__webpack_require__(629);
__webpack_require__(628);
__webpack_require__(627);
__webpack_require__(626);
__webpack_require__(625);
__webpack_require__(624);
__webpack_require__(623);
__webpack_require__(622);
__webpack_require__(621);
__webpack_require__(620);
__webpack_require__(619);
__webpack_require__(618);
__webpack_require__(617);
__webpack_require__(616);
__webpack_require__(615);
__webpack_require__(614);
__webpack_require__(613);
__webpack_require__(612);
__webpack_require__(610);
__webpack_require__(609);
__webpack_require__(607);
__webpack_require__(606);
__webpack_require__(605);
__webpack_require__(604);
__webpack_require__(603);
__webpack_require__(602);
__webpack_require__(601);
__webpack_require__(599);
__webpack_require__(598);
__webpack_require__(597);
__webpack_require__(596);
__webpack_require__(595);
__webpack_require__(594);
__webpack_require__(593);
__webpack_require__(592);
__webpack_require__(591);
__webpack_require__(590);
__webpack_require__(589);
__webpack_require__(588);
__webpack_require__(587);
__webpack_require__(172);
__webpack_require__(586);
__webpack_require__(263);
__webpack_require__(585);
__webpack_require__(262);
__webpack_require__(584);
__webpack_require__(583);
__webpack_require__(582);
__webpack_require__(581);
__webpack_require__(580);
__webpack_require__(259);
__webpack_require__(257);
__webpack_require__(256);
__webpack_require__(579);
__webpack_require__(578);
__webpack_require__(577);
__webpack_require__(576);
__webpack_require__(575);
__webpack_require__(574);
__webpack_require__(573);
__webpack_require__(572);
__webpack_require__(571);
__webpack_require__(570);
__webpack_require__(569);
__webpack_require__(568);
__webpack_require__(567);
__webpack_require__(566);
__webpack_require__(565);
__webpack_require__(564);
__webpack_require__(563);
__webpack_require__(562);
__webpack_require__(561);
__webpack_require__(560);
__webpack_require__(559);
__webpack_require__(558);
__webpack_require__(557);
__webpack_require__(556);
__webpack_require__(555);
__webpack_require__(554);
__webpack_require__(553);
__webpack_require__(552);
__webpack_require__(551);
__webpack_require__(550);
__webpack_require__(549);
__webpack_require__(548);
__webpack_require__(547);
__webpack_require__(546);
__webpack_require__(545);
__webpack_require__(544);
__webpack_require__(543);
__webpack_require__(542);
__webpack_require__(541);
__webpack_require__(540);
__webpack_require__(539);
__webpack_require__(538);
__webpack_require__(537);
__webpack_require__(536);
__webpack_require__(535);
__webpack_require__(534);
__webpack_require__(533);
__webpack_require__(532);
__webpack_require__(531);
__webpack_require__(530);
__webpack_require__(529);
__webpack_require__(528);
__webpack_require__(527);
__webpack_require__(526);
__webpack_require__(525);
__webpack_require__(524);
__webpack_require__(523);
__webpack_require__(522);
__webpack_require__(521);
__webpack_require__(520);
__webpack_require__(519);
__webpack_require__(518);
__webpack_require__(517);
__webpack_require__(516);
__webpack_require__(515);
__webpack_require__(514);
__webpack_require__(513);
__webpack_require__(512);
__webpack_require__(511);
__webpack_require__(510);
__webpack_require__(509);
__webpack_require__(508);
__webpack_require__(507);
__webpack_require__(506);
__webpack_require__(505);
__webpack_require__(504);
__webpack_require__(503);
__webpack_require__(502);
__webpack_require__(501);
__webpack_require__(500);
__webpack_require__(499);
__webpack_require__(498);
__webpack_require__(497);
__webpack_require__(496);
__webpack_require__(495);
module.exports = __webpack_require__(44);
/***/ }),
/* 692 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
__webpack_require__(691);
__webpack_require__(494);
__webpack_require__(493);
if (global._babelPolyfill) {
throw new Error("only one instance of babel-polyfill is allowed");
}
global._babelPolyfill = true;
var DEFINE_PROPERTY = "defineProperty";
function define(O, key, value) {
O[key] || Object[DEFINE_PROPERTY](O, key, {
writable: true,
configurable: true,
value: value
});
}
define(String.prototype, "padLeft", "".padStart);
define(String.prototype, "padRight", "".padEnd);
"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) {
[][key] && define(Array, key, Function.call.bind([][key]));
});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(53)))
/***/ }),
/* 693 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(692);
module.exports = __webpack_require__(490);
/***/ })
/******/ ]);
});
//# sourceMappingURL=ml5.js.map