/**
* nmr-metadata - Extract and normalize metadata from NMR spectra
* @version v2.3.0
* @link https://github.com/cheminfo/nmr-metadata
* @license MIT
*/
(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["nmrMetadata"] = factory();
else
root["nmrMetadata"] = factory();
})(typeof self !== 'undefined' ? self : this, 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, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // 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 = 59);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(3).Matrix;
module.exports.Decompositions = module.exports.DC = __webpack_require__(84);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
const HashTable = __webpack_require__(122);
class SparseMatrix {
constructor(rows, columns) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (rows instanceof SparseMatrix) {
// clone
const other = rows;
this._init(other.rows, other.columns, other.elements.clone(), other.threshold);
return;
}
if (Array.isArray(rows)) {
const matrix = rows;
rows = matrix.length;
options = columns || {};
columns = matrix[0].length;
this._init(rows, columns, new HashTable(options), options.threshold);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
var value = matrix[i][j];
if (this.threshold && Math.abs(value) < this.threshold) value = 0;
if (value !== 0) {
this.elements.set(i * columns + j, matrix[i][j]);
}
}
}
} else {
this._init(rows, columns, new HashTable(options), options.threshold);
}
}
_init(rows, columns, elements, threshold) {
this.rows = rows;
this.columns = columns;
this.elements = elements;
this.threshold = threshold || 0;
}
static eye() {
let rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
let columns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : rows;
const min = Math.min(rows, columns);
const matrix = new SparseMatrix(rows, columns, {
initialCapacity: min
});
for (var i = 0; i < min; i++) {
matrix.set(i, i, 1);
}
return matrix;
}
clone() {
return new SparseMatrix(this);
}
to2DArray() {
const copy = new Array(this.rows);
for (var i = 0; i < this.rows; i++) {
copy[i] = new Array(this.columns);
for (var j = 0; j < this.columns; j++) {
copy[i][j] = this.get(i, j);
}
}
return copy;
}
isSquare() {
return this.rows === this.columns;
}
isSymmetric() {
if (!this.isSquare()) return false;
var symmetric = true;
this.forEachNonZero((i, j, v) => {
if (this.get(j, i) !== v) {
symmetric = false;
return false;
}
return v;
});
return symmetric;
}
get cardinality() {
return this.elements.size;
}
get size() {
return this.rows * this.columns;
}
get(row, column) {
return this.elements.get(row * this.columns + column);
}
set(row, column, value) {
if (this.threshold && Math.abs(value) < this.threshold) value = 0;
if (value === 0) {
this.elements.remove(row * this.columns + column);
} else {
this.elements.set(row * this.columns + column, value);
}
return this;
}
mmul(other) {
if (this.columns !== other.rows) console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');
const m = this.rows;
const p = other.columns;
const result = new SparseMatrix(m, p);
this.forEachNonZero((i, j, v1) => {
other.forEachNonZero((k, l, v2) => {
if (j === k) {
result.set(i, l, result.get(i, l) + v1 * v2);
}
return v2;
});
return v1;
});
return result;
}
kroneckerProduct(other) {
const m = this.rows;
const n = this.columns;
const p = other.rows;
const q = other.columns;
const result = new SparseMatrix(m * p, n * q, {
initialCapacity: this.cardinality * other.cardinality
});
this.forEachNonZero((i, j, v1) => {
other.forEachNonZero((k, l, v2) => {
result.set(p * i + k, q * j + l, v1 * v2);
return v2;
});
return v1;
});
return result;
}
forEachNonZero(callback) {
this.elements.forEachPair((key, value) => {
const i = key / this.columns | 0;
const j = key % this.columns;
let r = callback(i, j, value);
if (r === false) return false; // stop iteration
if (this.threshold && Math.abs(r) < this.threshold) r = 0;
if (r !== value) {
if (r === 0) {
this.elements.remove(key, true);
} else {
this.elements.set(key, r);
}
}
return true;
});
this.elements.maybeShrinkCapacity();
return this;
}
getNonZeros() {
const cardinality = this.cardinality;
const rows = new Array(cardinality);
const columns = new Array(cardinality);
const values = new Array(cardinality);
var idx = 0;
this.forEachNonZero((i, j, value) => {
rows[idx] = i;
columns[idx] = j;
values[idx] = value;
idx++;
return value;
});
return {
rows,
columns,
values
};
}
setThreshold(newThreshold) {
if (newThreshold !== 0 && newThreshold !== this.threshold) {
this.threshold = newThreshold;
this.forEachNonZero((i, j, v) => v);
}
return this;
}
}
SparseMatrix.prototype.klass = 'Matrix';
SparseMatrix.identity = SparseMatrix.eye;
SparseMatrix.prototype.tensorProduct = SparseMatrix.prototype.kroneckerProduct;
module.exports = SparseMatrix;
/*
Add dynamically instance and static methods for mathematical operations
*/
var inplaceOperator = `
(function %name%(value) {
if (typeof value === 'number') return this.%name%S(value);
return this.%name%M(value);
})
`;
var inplaceOperatorScalar = `
(function %name%S(value) {
this.forEachNonZero((i, j, v) => v %op% value);
return this;
})
`;
var inplaceOperatorMatrix = `
(function %name%M(matrix) {
matrix.forEachNonZero((i, j, v) => {
this.set(i, j, this.get(i, j) %op% v);
return v;
});
return this;
})
`;
var staticOperator = `
(function %name%(matrix, value) {
var newMatrix = new SparseMatrix(matrix);
return newMatrix.%name%(value);
})
`;
var inplaceMethod = `
(function %name%() {
this.forEachNonZero((i, j, v) => %method%(v));
return this;
})
`;
var staticMethod = `
(function %name%(matrix) {
var newMatrix = new SparseMatrix(matrix);
return newMatrix.%name%();
})
`;
var operators = [// Arithmetic operators
['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], // Bitwise operators
['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']];
for (var operator of operators) {
for (var i = 1; i < operator.length; i++) {
SparseMatrix.prototype[operator[i]] = eval(fillTemplateFunction(inplaceOperator, {
name: operator[i],
op: operator[0]
}));
SparseMatrix.prototype[operator[i] + 'S'] = eval(fillTemplateFunction(inplaceOperatorScalar, {
name: operator[i] + 'S',
op: operator[0]
}));
SparseMatrix.prototype[operator[i] + 'M'] = eval(fillTemplateFunction(inplaceOperatorMatrix, {
name: operator[i] + 'M',
op: operator[0]
}));
SparseMatrix[operator[i]] = eval(fillTemplateFunction(staticOperator, {
name: operator[i]
}));
}
}
var methods = [['~', 'not']];
['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p', 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'].forEach(function (mathMethod) {
methods.push(['Math.' + mathMethod, mathMethod]);
});
for (var method of methods) {
for (var i = 1; i < method.length; i++) {
SparseMatrix.prototype[method[i]] = eval(fillTemplateFunction(inplaceMethod, {
name: method[i],
method: method[0]
}));
SparseMatrix[method[i]] = eval(fillTemplateFunction(staticMethod, {
name: method[i]
}));
}
}
function fillTemplateFunction(template, values) {
for (var i in values) {
template = template.replace(new RegExp('%' + i + '%', 'g'), values[i]);
}
return template;
}
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var support = __webpack_require__(10);
var compressions = __webpack_require__(23);
var nodeBuffer = __webpack_require__(25);
/**
* Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
* @param {string} str the string to transform.
* @return {String} the binary string.
*/
exports.string2binary = function (str) {
var result = "";
for (var i = 0; i < str.length; i++) {
result += String.fromCharCode(str.charCodeAt(i) & 0xff);
}
return result;
};
exports.arrayBuffer2Blob = function (buffer, mimeType) {
exports.checkSupport("blob");
mimeType = mimeType || 'application/zip';
try {
// Blob constructor
return new Blob([buffer], {
type: mimeType
});
} catch (e) {
try {
// deprecated, browser only, old way
var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var builder = new Builder();
builder.append(buffer);
return builder.getBlob(mimeType);
} catch (e) {
// well, fuck ?!
throw new Error("Bug : can't construct the Blob.");
}
}
};
/**
* The identity function.
* @param {Object} input the input.
* @return {Object} the same input.
*/
function identity(input) {
return input;
}
/**
* Fill in an array with a string.
* @param {String} str the string to use.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
*/
function stringToArrayLike(str, array) {
for (var i = 0; i < str.length; ++i) {
array[i] = str.charCodeAt(i) & 0xFF;
}
return array;
}
/**
* Transform an array-like object to a string.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @return {String} the result.
*/
function arrayLikeToString(array) {
// Performances notes :
// --------------------
// String.fromCharCode.apply(null, array) is the fastest, see
// see http://jsperf.com/converting-a-uint8array-to-a-string/2
// but the stack is limited (and we can get huge arrays !).
//
// result += String.fromCharCode(array[i]); generate too many strings !
//
// This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
var chunk = 65536;
var result = [],
len = array.length,
type = exports.getTypeOf(array),
k = 0,
canUseApply = true;
try {
switch (type) {
case "uint8array":
String.fromCharCode.apply(null, new Uint8Array(0));
break;
case "nodebuffer":
String.fromCharCode.apply(null, nodeBuffer(0));
break;
}
} catch (e) {
canUseApply = false;
} // no apply : slow and painful algorithm
// default browser on android 4.*
if (!canUseApply) {
var resultStr = "";
for (var i = 0; i < array.length; i++) {
resultStr += String.fromCharCode(array[i]);
}
return resultStr;
}
while (k < len && chunk > 1) {
try {
if (type === "array" || type === "nodebuffer") {
result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
} else {
result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
}
k += chunk;
} catch (e) {
chunk = Math.floor(chunk / 2);
}
}
return result.join("");
}
exports.applyFromCharCode = arrayLikeToString;
/**
* Copy the data from an array-like to an other array-like.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
*/
function arrayLikeToArrayLike(arrayFrom, arrayTo) {
for (var i = 0; i < arrayFrom.length; i++) {
arrayTo[i] = arrayFrom[i];
}
return arrayTo;
} // a matrix containing functions to transform everything into everything.
var transform = {}; // string to ?
transform["string"] = {
"string": identity,
"array": function array(input) {
return stringToArrayLike(input, new Array(input.length));
},
"arraybuffer": function arraybuffer(input) {
return transform["string"]["uint8array"](input).buffer;
},
"uint8array": function uint8array(input) {
return stringToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": function nodebuffer(input) {
return stringToArrayLike(input, nodeBuffer(input.length));
}
}; // array to ?
transform["array"] = {
"string": arrayLikeToString,
"array": identity,
"arraybuffer": function arraybuffer(input) {
return new Uint8Array(input).buffer;
},
"uint8array": function uint8array(input) {
return new Uint8Array(input);
},
"nodebuffer": function nodebuffer(input) {
return nodeBuffer(input);
}
}; // arraybuffer to ?
transform["arraybuffer"] = {
"string": function string(input) {
return arrayLikeToString(new Uint8Array(input));
},
"array": function array(input) {
return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
},
"arraybuffer": identity,
"uint8array": function uint8array(input) {
return new Uint8Array(input);
},
"nodebuffer": function nodebuffer(input) {
return nodeBuffer(new Uint8Array(input));
}
}; // uint8array to ?
transform["uint8array"] = {
"string": arrayLikeToString,
"array": function array(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function arraybuffer(input) {
return input.buffer;
},
"uint8array": identity,
"nodebuffer": function nodebuffer(input) {
return nodeBuffer(input);
}
}; // nodebuffer to ?
transform["nodebuffer"] = {
"string": arrayLikeToString,
"array": function array(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function arraybuffer(input) {
return transform["nodebuffer"]["uint8array"](input).buffer;
},
"uint8array": function uint8array(input) {
return arrayLikeToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": identity
};
/**
* Transform an input into any type.
* The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
* If no output type is specified, the unmodified input will be returned.
* @param {String} outputType the output type.
* @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
* @throws {Error} an Error if the browser doesn't support the requested output type.
*/
exports.transformTo = function (outputType, input) {
if (!input) {
// undefined, null, etc
// an empty string won't harm.
input = "";
}
if (!outputType) {
return input;
}
exports.checkSupport(outputType);
var inputType = exports.getTypeOf(input);
var result = transform[inputType][outputType](input);
return result;
};
/**
* Return the type of the input.
* The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
* @param {Object} input the input to identify.
* @return {String} the (lowercase) type of the input.
*/
exports.getTypeOf = function (input) {
if (typeof input === "string") {
return "string";
}
if (Object.prototype.toString.call(input) === "[object Array]") {
return "array";
}
if (support.nodebuffer && nodeBuffer.test(input)) {
return "nodebuffer";
}
if (support.uint8array && input instanceof Uint8Array) {
return "uint8array";
}
if (support.arraybuffer && input instanceof ArrayBuffer) {
return "arraybuffer";
}
};
/**
* Throw an exception if the type is not supported.
* @param {String} type the type to check.
* @throws {Error} an Error if the browser doesn't support the requested type.
*/
exports.checkSupport = function (type) {
var supported = support[type.toLowerCase()];
if (!supported) {
throw new Error(type + " is not supported by this browser");
}
};
exports.MAX_VALUE_16BITS = 65535;
exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
/**
* Prettify a string read as binary.
* @param {string} str the string to prettify.
* @return {string} a pretty string.
*/
exports.pretty = function (str) {
var res = '',
code,
i;
for (i = 0; i < (str || "").length; i++) {
code = str.charCodeAt(i);
res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
}
return res;
};
/**
* Find a compression registered in JSZip.
* @param {string} compressionMethod the method magic to find.
* @return {Object|null} the JSZip compression object, null if none found.
*/
exports.findCompression = function (compressionMethod) {
for (var method in compressions) {
if (!compressions.hasOwnProperty(method)) {
continue;
}
if (compressions[method].magic === compressionMethod) {
return compressions[method];
}
}
return null;
};
/**
* Cross-window, cross-Node-context regular expression detection
* @param {Object} object Anything
* @return {Boolean} true if the object is a regular expression,
* false otherwise
*/
exports.isRegExp = function (object) {
return Object.prototype.toString.call(object) === "[object RegExp]";
};
/**
* Merge the objects passed as parameters into a new one.
* @private
* @param {...Object} var_args All objects to merge.
* @return {Object} a new object with the data of the others.
*/
exports.extend = function () {
var result = {},
i,
attr;
for (i = 0; i < arguments.length; i++) {
// arguments is not enumerable in some browsers
for (attr in arguments[i]) {
if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
result[attr] = arguments[i][attr];
}
}
}
return result;
};
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__(72);
var abstractMatrix = __webpack_require__(35);
var util = __webpack_require__(13);
class Matrix extends abstractMatrix(Array) {
constructor(nRows, nColumns) {
var i;
if (arguments.length === 1 && typeof nRows === 'number') {
return new Array(nRows);
}
if (Matrix.isMatrix(nRows)) {
return nRows.clone();
} else if (Number.isInteger(nRows) && nRows > 0) {
// Create an empty matrix
super(nRows);
if (Number.isInteger(nColumns) && nColumns > 0) {
for (i = 0; i < nRows; i++) {
this[i] = new Array(nColumns);
}
} else {
throw new TypeError('nColumns must be a positive integer');
}
} else if (Array.isArray(nRows)) {
// Copy the values from the 2D array
const matrix = nRows;
nRows = matrix.length;
nColumns = matrix[0].length;
if (typeof nColumns !== 'number' || nColumns === 0) {
throw new TypeError('Data must be a 2D array with at least one element');
}
super(nRows);
for (i = 0; i < nRows; i++) {
if (matrix[i].length !== nColumns) {
throw new RangeError('Inconsistent array dimensions');
}
this[i] = [].concat(matrix[i]);
}
} else {
throw new TypeError('First argument must be a positive number or an array');
}
this.rows = nRows;
this.columns = nColumns;
return this;
}
set(rowIndex, columnIndex, value) {
this[rowIndex][columnIndex] = value;
return this;
}
get(rowIndex, columnIndex) {
return this[rowIndex][columnIndex];
}
/**
* Creates an exact and independent copy of the matrix
* @return {Matrix}
*/
clone() {
var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns);
for (var row = 0; row < this.rows; row++) {
for (var column = 0; column < this.columns; column++) {
newMatrix.set(row, column, this.get(row, column));
}
}
return newMatrix;
}
/**
* Removes a row from the given index
* @param {number} index - Row index
* @return {Matrix} this
*/
removeRow(index) {
util.checkRowIndex(this, index);
if (this.rows === 1) {
throw new RangeError('A matrix cannot have less than one row');
}
this.splice(index, 1);
this.rows -= 1;
return this;
}
/**
* Adds a row at the given index
* @param {number} [index = this.rows] - Row index
* @param {Array|Matrix} array - Array or vector
* @return {Matrix} this
*/
addRow(index, array) {
if (array === undefined) {
array = index;
index = this.rows;
}
util.checkRowIndex(this, index, true);
array = util.checkRowVector(this, array, true);
this.splice(index, 0, array);
this.rows += 1;
return this;
}
/**
* Removes a column from the given index
* @param {number} index - Column index
* @return {Matrix} this
*/
removeColumn(index) {
util.checkColumnIndex(this, index);
if (this.columns === 1) {
throw new RangeError('A matrix cannot have less than one column');
}
for (var i = 0; i < this.rows; i++) {
this[i].splice(index, 1);
}
this.columns -= 1;
return this;
}
/**
* Adds a column at the given index
* @param {number} [index = this.columns] - Column index
* @param {Array|Matrix} array - Array or vector
* @return {Matrix} this
*/
addColumn(index, array) {
if (typeof array === 'undefined') {
array = index;
index = this.columns;
}
util.checkColumnIndex(this, index, true);
array = util.checkColumnVector(this, array);
for (var i = 0; i < this.rows; i++) {
this[i].splice(index, 0, array[i]);
}
this.columns += 1;
return this;
}
}
exports.Matrix = Matrix;
Matrix.abstractMatrix = abstractMatrix;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const toString = Object.prototype.toString;
function isAnyArray(object) {
return toString.call(object).endsWith('Array]');
}
module.exports = isAnyArray;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var TYPED_OK = typeof Uint8Array !== 'undefined' && typeof Uint16Array !== 'undefined' && typeof Int32Array !== 'undefined';
function _has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
exports.assign = function (obj
/*from1, from2, from3, ...*/
) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) {
continue;
}
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (_has(source, p)) {
obj[p] = source[p];
}
}
}
return obj;
}; // reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) {
return buf;
}
if (buf.subarray) {
return buf.subarray(0, size);
}
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function arraySet(dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
return;
} // Fallback to ordinary array
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function flattenChunks(chunks) {
var i, l, len, pos, chunk, result; // calculate data length
len = 0;
for (i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
} // join chunks
result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length; i < l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function arraySet(dest, src, src_offs, len, dest_offs) {
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function flattenChunks(chunks) {
return [].concat.apply([], chunks);
}
}; // Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var abstractMatrix = __webpack_require__(35);
var Matrix = __webpack_require__(3);
class BaseView extends abstractMatrix() {
constructor(matrix, rows, columns) {
super();
this.matrix = matrix;
this.rows = rows;
this.columns = columns;
}
static get [Symbol.species]() {
return Matrix.Matrix;
}
}
module.exports = BaseView;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.array = __webpack_require__(31);
exports.matrix = __webpack_require__(61);
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(module) {/* unused harmony export nmrJ */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return joinCoupling; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return group; });
/* unused harmony export compilePattern */
const patterns = ['s', 'd', 't', 'q', 'quint', 'h', 'sept', 'o', 'n'];
function nmrJ(Js) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var jString = '';
options = Object.assign({}, {
separator: ', ',
nbDecimal: 2
}, options);
let j, i;
for (i = 0; i < Js.length; i++) {
j = Js[i];
if (j.length > 11) {
j += options.separator;
}
jString += `${j.multiplicity} ${j.coupling.toFixed(options.nbDecimal)}`;
}
return jString;
}
function joinCoupling(signal) {
let tolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.05;
var jc = signal.j;
if (jc && jc.length > 0) {
var cont = jc[0].assignment ? jc[0].assignment.length : 1;
var pattern = '';
var newNmrJs = [];
var diaIDs = [];
var atoms = [];
jc.sort(function (a, b) {
return b.coupling - a.coupling;
});
if (jc[0].diaID) {
diaIDs = [jc[0].diaID];
}
if (jc[0].assignment) {
atoms = jc[0].assignment;
}
for (var i = 0; i < jc.length - 1; i++) {
if (Math.abs(jc[i].coupling - jc[i + 1].coupling) < tolerance) {
cont += jc[i + 1].assignment ? jc[i + 1].assignment.length : 1;
diaIDs.push(jc[i].diaID);
atoms = atoms.concat(jc[i + 1].assignment);
} else {
let jTemp = {
coupling: Math.abs(jc[i].coupling),
multiplicity: patterns[cont]
};
if (diaIDs.length > 0) {
jTemp.diaID = diaIDs;
}
if (atoms.length > 0) {
jTemp.assignment = atoms;
}
newNmrJs.push(jTemp);
if (jc[0].diaID) {
diaIDs = [jc[i].diaID];
}
if (jc[0].assignment) {
atoms = jc[i].assignment;
}
pattern += patterns[cont];
cont = jc[i + 1].assignment ? jc[i + 1].assignment.length : 1;
}
}
let jTemp = {
coupling: Math.abs(jc[i].coupling),
multiplicity: patterns[cont]
};
if (diaIDs.length > 0) {
jTemp.diaID = diaIDs;
}
if (atoms.length > 0) {
jTemp.assignment = atoms;
}
newNmrJs.push(jTemp);
pattern += patterns[cont];
signal.j = newNmrJs;
} else if (signal.delta) {
pattern = 's';
} else {
pattern = 'm';
}
return pattern;
}
function group(signals) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i, k;
for (i = 0; i < signals.length; i++) {
var j = signals[i].j;
if (j && j.length > 0) {
for (k = j.length - 2; k >= 0; k--) {
for (var m = j.length - 1; m > k; m--) {
if (j[k].diaID === j[m].diaID && j[k].coupling === j[m].coupling && j[k].distance === j[m].distance) {
j[k].assignment = j[k].assignment.concat(j[m].assignment);
j.splice(m, 1);
}
}
}
}
}
signals.sort((a, b) => {
if (a.diaIDs[0] < b.diaIDs[0]) return -1;
if (a.diaIDs[0] > b.diaIDs[0]) return 1;
return 0;
});
for (i = signals.length - 2; i >= 0; i--) {
if (signals[i].diaIDs[0] === signals[i + 1].diaIDs[0]) {
signals[i].nbAtoms += signals[i + 1].nbAtoms;
signals[i].atomIDs = signals[i].atomIDs.concat(signals[i + 1].atomIDs);
signals.splice(i + 1, 1);
}
}
for (i = 0; i < signals.length; i++) {
j = signals[i].j;
if (j) {
for (k = 0; k < j.length; k++) {
j[k].multiplicity = patterns[j[k].assignment.length];
} // signals[i].multiplicity = module.exports.compilePattern(signals[i], options.tolerance);
} // console.log(signals[i]);
signals[i].multiplicity = module.exports.compilePattern(signals[i], options.tolerance);
}
return signals;
}
function compilePattern(signal) {
let tolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.05;
var jc = signal.j;
var pattern = '';
if (jc && jc.length > 0) {
var cont = jc[0].assignment ? jc[0].assignment.length : 0;
jc.sort(function (a, b) {
return b.coupling - a.coupling;
});
for (var i = 0; i < jc.length - 1; i++) {
if (Math.abs(jc[i].coupling - jc[i + 1].coupling) < tolerance) {
cont += jc[i + 1].assignment ? jc[i + 1].assignment.length : 1;
} else {
pattern += patterns[cont];
cont = jc[i + 1].assignment ? jc[i + 1].assignment.length : 1;
}
}
pattern += patterns[cont];
} else if (signal.delta) {
pattern = 's';
} else {
pattern = 'm';
}
return pattern;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(126)(module)))
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* lodash (Custom Build)
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors
* Released under MIT license
* Based on Underscore.js 1.8.3
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var Symbol = root.Symbol;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = value + '';
return result == '0' && 1 / value == -INFINITY ? '-0' : result;
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/
function createRound(methodName) {
var func = Math[methodName];
return function (number, precision) {
number = toNumber(number);
precision = nativeMin(toInteger(precision), 292);
if (precision) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' || isObjectLike(value) && objectToString.call(value) == symbolTag;
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = value < 0 ? -1 : 1;
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? remainder ? result - remainder : result : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? other + '' : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {string} Returns the string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/**
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
*/
var round = createRound('round');
module.exports = round;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(22)))
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
exports.base64 = true;
exports.array = true;
exports.string = true;
exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; // contains true if JSZip can read/generate nodejs Buffer, false otherwise.
// Browserify will provide a Buffer implementation for browsers, which is
// an augmented Uint8Array (i.e., can be used as either Buffer or U8).
exports.nodebuffer = typeof Buffer !== "undefined"; // contains true if JSZip can read/generate Uint8Array, false otherwise.
exports.uint8array = typeof Uint8Array !== "undefined";
if (typeof ArrayBuffer === "undefined") {
exports.blob = false;
} else {
var buffer = new ArrayBuffer(0);
try {
exports.blob = new Blob([buffer], {
type: "application/zip"
}).size === 0;
} catch (e) {
try {
var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var builder = new Builder();
builder.append(buffer);
exports.blob = builder.getBlob('application/zip').size === 0;
} catch (e) {
exports.blob = false;
}
}
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(39).Buffer))
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const Converter = __webpack_require__(14);
const IOBuffer = __webpack_require__(90);
const JSZip = __webpack_require__(91); // constants
var BINARY = 1;
var TEXT = 2;
function readZIP(zipFile, options) {
options = options || {};
var zip = new JSZip();
zip.load(zipFile, options);
var files = {
'ser': BINARY,
'fid': BINARY,
'acqus': TEXT,
'acqu2s': TEXT,
'procs': TEXT,
'proc2s': TEXT,
'1r': BINARY,
'1i': BINARY,
'2rr': BINARY
};
var folders = zip.filter(function (relativePath, file) {
if (relativePath.indexOf("ser") >= 0 || relativePath.indexOf("fid") >= 0 || relativePath.indexOf("1r") >= 0 || relativePath.indexOf("2rr") >= 0) {
return true;
}
return false;
});
var spectra = new Array(folders.length);
for (var i = 0; i < folders.length; ++i) {
var len = folders[i].name.length;
var name = folders[i].name;
name = name.substr(0, name.lastIndexOf("/") + 1);
var currFolder = zip.folder(name);
var currFiles = currFolder.filter(function (relativePath, file) {
return files[relativePath] ? true : false;
});
var brukerFiles = {};
if (name.indexOf("pdata") >= 0) {
brukerFiles['acqus'] = zip.file(name.replace(/pdata\/[0-9]\//, "acqus")).asText();
}
for (var j = 0; j < currFiles.length; ++j) {
var idx = currFiles[j].name.lastIndexOf('/');
var name = currFiles[j].name.substr(idx + 1);
if (files[name] === BINARY) {
brukerFiles[name] = new IOBuffer(currFiles[j].asArrayBuffer());
} else {
brukerFiles[name] = currFiles[j].asText();
}
} //console.log(folders[i].name);
spectra[i] = {
"filename": folders[i].name,
value: convert(brukerFiles, options)
};
}
return spectra;
}
function convert(brukerFiles, options) {
options = options || {};
var start = new Date();
var result;
if (brukerFiles['ser'] || brukerFiles['2rr']) {
result = convert2D(brukerFiles, options);
} else if (brukerFiles['1r'] || brukerFiles['1i'] || brukerFiles['fid']) {
result = convert1D(brukerFiles, options);
} else {
throw new RangeError('The current files are invalid');
}
if (result.twoD && !options.noContours) {
//console.log("Countours");
add2D(result);
if (result.profiling) result.profiling.push({
action: 'Finished countour plot calculation',
time: new Date() - start
});
if (!options.keepSpectra) {
delete result.spectra;
}
}
var spectra = result.spectra;
if (options.xy) {
// the spectraData should not be a oneD array but an object with x and y
if (spectra.length > 0) {
for (var i = 0; i < spectra.length; i++) {
var spectrum = spectra[i];
if (spectrum.data.length > 0) {
for (var j = 0; j < spectrum.data.length; j++) {
var data = spectrum.data[j];
var newData = {
x: new Array(data.length / 2),
y: new Array(data.length / 2)
};
for (var k = 0; k < data.length; k = k + 2) {
newData.x[k / 2] = data[k];
newData.y[k / 2] = data[k + 1];
}
spectrum.data[j] = newData;
}
}
}
}
}
return result;
}
function convert1D(files, options) {
var result = parseData(files["procs"], options);
var temp = parseData(files['acqus'], options);
var keys = Object.keys(temp.info);
for (var i = 0; i < keys.length; i++) {
var currKey = keys[i];
if (result.info[currKey] === undefined) {
result.info[currKey] = temp.info[currKey];
}
}
if (files['1r'] || files['1i']) {
if (files['1r']) {
setXYSpectrumData(files['1r'], result, '1r', true);
}
if (files['1i']) {
setXYSpectrumData(files['1i'], result, '1i', false);
}
} else if (files['fid']) {
setFIDSpectrumData(files['fid'], result);
}
return result;
}
function convert2D(files, options) {
var SF, SW_p, SW, offset;
if (files['2rr']) {
var result = parseData(files['procs'], options);
var temp = parseData(files['acqus'], options);
var keys = Object.keys(temp.info);
for (var i = 0; i < keys.length; i++) {
var currKey = keys[i];
if (result.info[currKey] === undefined) {
result.info[currKey] = temp.info[currKey];
}
}
temp = parseData(files['proc2s'], options);
result.info.nbSubSpectra = temp.info['$SI'] = parseInt(temp.info['$SI']);
SF = temp.info['$SF'] = parseFloat(temp.info['$SF']);
SW_p = temp.info['$SWP'] = parseFloat(temp.info['$SWP']);
offset = temp.info['$OFFSET'] = parseFloat(temp.info['$OFFSET']);
} else if (files['ser']) {
result = parseData(files['acqus'], options);
temp = parseData(files['acqu2s'], options);
result.info.nbSubSpectra = temp.info['$SI'] = parseInt(temp.info['$TD']);
result.info['$SI'] = parseInt(result.info['$TD']); //SW_p = temp.info['$SWH'] = parseFloat(temp.info['$SWH']);
SW_p = temp.info["$SW"];
result.info["$SWP"] = result.info["$SWH"];
result.info["$SF"] = parseFloat(temp.info['$SFO1']);
result.info['$OFFSET'] = 0;
SF = temp.info['$SFO1'] = parseFloat(temp.info['$SFO1']);
SF = 1;
offset = 0;
result.info['$AXNUC'] = result.info['$NUC1'];
temp.info['$AXNUC'] = temp.info['$NUC1'];
}
result.info.firstY = offset;
result.info.lastY = offset - SW_p / SF;
result.info['$BF2'] = SF;
result.info['$SFO1'] = SF;
var nbSubSpectra = result.info.nbSubSpectra;
var pageValue = result.info.firstY;
var deltaY = (result.info.lastY - result.info.firstY) / (nbSubSpectra - 1);
if (files['2rr']) {
setXYSpectrumData(files['2rr'], result, '2rr', true);
} else if (files['ser']) {
setFIDSpectrumData(files['ser'], result, 'ser', true);
}
for (var i = 0; i < nbSubSpectra; i++) {
pageValue += deltaY;
result.spectra[i].pageValue = pageValue;
}
var dataType = files['ser'] ? 'TYPE_2DNMR_FID' : 'TYPE_2DNMR_SPECTRUM';
result.info['2D_Y_NUCLEUS'] = temp.info['$AXNUC'];
result.info['2D_X_NUCLEUS'] = result.info['$AXNUC'];
result.info['2D_Y_FRECUENCY'] = SF;
result.info['2D_Y_OFFSET'] = offset;
result.info['2D_X_FRECUENCY'] = result.info['$SF'];
result.info['2D_X_OFFSET'] = result.info['$OFFSET'];
result.twoD = true;
return result;
}
function setXYSpectrumData(file, spectra, store, real) {
var td = spectra.info['$SI'] = parseInt(spectra.info['$SI']);
var SW_p = parseFloat(spectra.info["$SWP"]);
var SF = parseFloat(spectra.info["$SF"]);
var BF = SF; //var BF = parseFloat(spectra.info["$BF1"]);
var offset = spectra.shiftOffsetVal; //parseFloat(spectra.info["$OFFSET"]);
spectra.info["observeFrequency"] = SF;
spectra.info["$BF1"] = BF;
spectra.info["$SFO1"] = SF;
spectra.info.brukerReference = BF;
var endian = parseInt(spectra.info["$BYTORDP"]);
endian = endian ? 0 : 1; // number of spectras
var nbSubSpectra = spectra.info.nbSubSpectra ? spectra.info.nbSubSpectra : 1;
if (endian) file.setLittleEndian();else file.setBigEndian();
for (var i = 0; i < nbSubSpectra; i++) {
var toSave = {
dataType: "NMR Spectrum",
dataTable: "(X++(R..R))",
nbPoints: td,
firstX: offset,
lastX: offset - SW_p / SF,
xUnit: "PPM",
yUnit: "Arbitrary",
data: [new Array(td * 2)],
//[{x:new Array(td),y:new Array(td)}],
isXYdata: true,
observeFrequency: SF,
title: spectra.info['TITLE'],
deltaX: -(SW_p / SF) / (td - 1)
};
var x = offset;
var deltaX = toSave.deltaX;
if (real) {
for (var k = 0; k < td; ++k) {
toSave.data[0][2 * k] = x;
toSave.data[0][2 * k + 1] = file.readInt32();
if (toSave.data[0][2 * k + 1] === null || isNaN(toSave.data[0][2 * k + 1])) {
toSave.data[0][2 * k + 1] = 0;
}
x += deltaX;
}
} else {
for (k = td - 1; k >= 0; --k) {
toSave.data[0][2 * k] = x;
toSave.data[0][2 * k + 1] = file.readInt32();
if (toSave.data[0][2 * k + 1] === null || isNaN(toSave.data[0][2 * k + 1])) {
toSave.data[0][2 * k + 1] = 0;
}
x += deltaX;
}
}
spectra.spectra.push(toSave);
}
}
function parseData(file, options) {
var keepRecordsRegExp = /.*/;
if (options.keepRecordsRegExp) keepRecordsRegExp = options.keepRecordsRegExp;
return Converter.convert(file, {
keepRecordsRegExp: keepRecordsRegExp
});
}
function setFIDSpectrumData(file, spectra) {
var td = spectra.info['$TD'] = parseInt(spectra.info['$TD']);
var SW_h = spectra.info['$SWH'] = parseFloat(spectra.info['$SWH']);
var SW = spectra.info['$SW'] = parseFloat(spectra.info['$SW']);
var SF = spectra.info['$SFO1'] = parseFloat(spectra.info['$SFO1']);
var BF = parseFloat(spectra.info['$BF1']);
spectra.info['$BF1'] = BF; //var DW = 1 / (2 * SW_h);
//var AQ = td * DW;
var AQ = SW;
var DW = AQ / (td - 1); //console.log(DW+" "+SW+" "+td);
var endian = parseInt(spectra.info["$BYTORDP"]);
endian = endian ? 0 : 1;
if (endian) file.setLittleEndian();else file.setBigEndian();
var nbSubSpectra = spectra.info.nbSubSpectra ? spectra.info.nbSubSpectra : 1;
spectra.spectra = new Array(nbSubSpectra);
for (var j = 0; j < nbSubSpectra / 2; j++) {
var toSave = {
dataType: "NMR FID",
dataTable: "(X++(R..R))",
nbPoints: td,
firstX: 0,
lastX: AQ,
nucleus: spectra.info["$NUC1"] ? spectra.info["$NUC1"] : undefined,
xUnit: "Sec",
yUnit: "Arbitrary",
data: [new Array(2 * td)],
//[{x:new Array(td),y:new Array(td)}],
isXYdata: true,
observeFrequency: SF,
title: spectra.info['TITLE'],
deltaX: DW
};
spectra.spectra[j * 2] = toSave;
toSave = {
dataType: "NMR FID",
dataTable: "(X++(I..I))",
nbPoints: td,
firstX: 0,
lastX: AQ,
nucleus: spectra.info["$NUC1"] ? spectra.info["$NUC1"] : undefined,
xUnit: "Sec",
yUnit: "Arbitrary",
data: [new Array(2 * td)],
//[{x:new Array(td),y:new Array(td)}],
isXYdata: true,
observeFrequency: SF,
title: spectra.info['TITLE'],
deltaX: DW
};
spectra.spectra[j * 2 + 1] = toSave;
var x = 0;
var y;
for (var i = 0; file.available(8) && i < td; i++, x = i * DW) {
y = file.readInt32();
if (y === null || isNaN(y)) {
y = 0;
}
spectra.spectra[j * 2].data[0][2 * i + 1] = y;
spectra.spectra[j * 2].data[0][2 * i] = x;
y = file.readInt32();
if (y === null || isNaN(y)) {
y = 0;
}
spectra.spectra[j * 2 + 1].data[0][2 * i + 1] = y;
spectra.spectra[j * 2 + 1].data[0][2 * i] = x;
}
for (; i < td; i++, x = i * DW) {
spectra.spectra[j * 2].data[0][2 * i + 1] = 0;
spectra.spectra[j * 2].data[0][2 * i] = x;
spectra.spectra[j * 2 + 1].data[0][2 * i + 1] = 0;
spectra.spectra[j * 2 + 1].data[0][2 * i] = x;
}
}
}
/**
* Those functions should disappear if add2D becomes accessible in jcampconvert
* @param spectra
* @returns {{z: Array, minX: *, maxX: *, minY: *, maxY: *, minZ: *, maxZ: *, noise: number}}
*/
function convertTo3DZ(spectra) {
var noise = 0;
var minZ = spectra[0].data[0][0];
var maxZ = minZ;
var ySize = spectra.length;
var xSize = spectra[0].data[0].length / 2;
var z = new Array(ySize);
for (var i = 0; i < ySize; i++) {
z[i] = new Array(xSize);
for (var j = 0; j < xSize; j++) {
z[i][j] = spectra[i].data[0][j * 2 + 1];
if (z[i][j] < minZ) minZ = spectra[i].data[0][j * 2 + 1];
if (z[i][j] > maxZ) maxZ = spectra[i].data[0][j * 2 + 1];
if (i !== 0 && j !== 0) {
noise += Math.abs(z[i][j] - z[i][j - 1]) + Math.abs(z[i][j] - z[i - 1][j]);
}
}
}
return {
z: z,
minX: spectra[0].data[0][0],
maxX: spectra[0].data[0][spectra[0].data[0].length - 2],
minY: spectra[0].pageValue,
maxY: spectra[ySize - 1].pageValue,
minZ: minZ,
maxZ: maxZ,
noise: noise / ((ySize - 1) * (xSize - 1) * 2)
};
}
function add2D(result) {
var zData = convertTo3DZ(result.spectra);
result.contourLines = generateContourLines(zData);
delete zData.z;
result.minMax = zData;
}
function generateContourLines(zData, options) {
//console.time('generateContourLines');
var noise = zData.noise;
var z = zData.z;
var contourLevels = [];
var nbLevels = 7;
var povarHeight = new Float32Array(4);
var isOver = [];
var nbSubSpectra = z.length;
var nbPovars = z[0].length;
var pAx, pAy, pBx, pBy;
var x0 = zData.minX;
var xN = zData.maxX;
var dx = (xN - x0) / (nbPovars - 1);
var y0 = zData.minY;
var yN = zData.maxY;
var dy = (yN - y0) / (nbSubSpectra - 1);
var minZ = zData.minZ;
var maxZ = zData.maxZ; //System.out.prvarln('y0 '+y0+' yN '+yN);
// -------------------------
// Povars attribution
//
// 0----1
// | / |
// | / |
// 2----3
//
// ---------------------d------
var lineZValue;
for (var level = 0; level < nbLevels * 2; level++) {
// multiply by 2 for positif and negatif
var contourLevel = {};
contourLevels.push(contourLevel);
var side = level % 2;
if (side === 0) {
lineZValue = (maxZ - 5 * noise) * Math.exp(level / 2 - nbLevels) + 5 * noise;
} else {
lineZValue = -(maxZ - 5 * noise) * Math.exp(level / 2 - nbLevels) - 5 * noise;
}
var lines = [];
contourLevel.zValue = lineZValue;
contourLevel.lines = lines;
if (lineZValue <= minZ || lineZValue >= maxZ) continue;
for (var iSubSpectra = 0; iSubSpectra < nbSubSpectra - 1; iSubSpectra++) {
for (var povar = 0; povar < nbPovars - 1; povar++) {
povarHeight[0] = z[iSubSpectra][povar];
povarHeight[1] = z[iSubSpectra][povar + 1];
povarHeight[2] = z[iSubSpectra + 1][povar];
povarHeight[3] = z[iSubSpectra + 1][povar + 1];
for (var i = 0; i < 4; i++) {
isOver[i] = povarHeight[i] > lineZValue;
} // Example povar0 is over the plane and povar1 and
// povar2 are below, we find the varersections and add
// the segment
if (isOver[0] !== isOver[1] && isOver[0] !== isOver[2]) {
pAx = povar + (lineZValue - povarHeight[0]) / (povarHeight[1] - povarHeight[0]);
pAy = iSubSpectra;
pBx = povar;
pBy = iSubSpectra + (lineZValue - povarHeight[0]) / (povarHeight[2] - povarHeight[0]);
lines.push(pAx * dx + x0, pAy * dy + y0, pBx * dx + x0, pBy * dy + y0);
}
if (isOver[3] !== isOver[1] && isOver[3] !== isOver[2]) {
pAx = povar + 1;
pAy = iSubSpectra + 1 - (lineZValue - povarHeight[3]) / (povarHeight[1] - povarHeight[3]);
pBx = povar + 1 - (lineZValue - povarHeight[3]) / (povarHeight[2] - povarHeight[3]);
pBy = iSubSpectra + 1;
lines.push(pAx * dx + x0, pAy * dy + y0, pBx * dx + x0, pBy * dy + y0);
} // test around the diagonal
if (isOver[1] !== isOver[2]) {
pAx = povar + 1 - (lineZValue - povarHeight[1]) / (povarHeight[2] - povarHeight[1]);
pAy = iSubSpectra + (lineZValue - povarHeight[1]) / (povarHeight[2] - povarHeight[1]);
if (isOver[1] !== isOver[0]) {
pBx = povar + 1 - (lineZValue - povarHeight[1]) / (povarHeight[0] - povarHeight[1]);
pBy = iSubSpectra;
lines.push(pAx * dx + x0, pAy * dy + y0, pBx * dx + x0, pBy * dy + y0);
}
if (isOver[2] !== isOver[0]) {
pBx = povar;
pBy = iSubSpectra + 1 - (lineZValue - povarHeight[2]) / (povarHeight[0] - povarHeight[2]);
lines.push(pAx * dx + x0, pAy * dy + y0, pBx * dx + x0, pBy * dy + y0);
}
if (isOver[1] !== isOver[3]) {
pBx = povar + 1;
pBy = iSubSpectra + (lineZValue - povarHeight[1]) / (povarHeight[3] - povarHeight[1]);
lines.push(pAx * dx + x0, pAy * dy + y0, pBx * dx + x0, pBy * dy + y0);
}
if (isOver[2] !== isOver[3]) {
pBx = povar + (lineZValue - povarHeight[2]) / (povarHeight[3] - povarHeight[2]);
pBy = iSubSpectra + 1;
lines.push(pAx * dx + x0, pAy * dy + y0, pBx * dx + x0, pBy * dy + y0);
}
}
}
}
} // console.timeEnd('generateContourLines');
return {
minX: zData.minX,
maxX: zData.maxX,
minY: zData.minY,
maxY: zData.maxY,
segments: contourLevels
}; //return contourLevels;
}
module.exports = {
convertZip: readZIP,
converFolder: convert
};
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.FFTUtils = __webpack_require__(125);
exports.FFT = __webpack_require__(55);
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Matrix = __webpack_require__(3);
/**
* @private
* Check that a row index is not out of bounds
* @param {Matrix} matrix
* @param {number} index
* @param {boolean} [outer]
*/
exports.checkRowIndex = function checkRowIndex(matrix, index, outer) {
var max = outer ? matrix.rows : matrix.rows - 1;
if (index < 0 || index > max) {
throw new RangeError('Row index out of range');
}
};
/**
* @private
* Check that a column index is not out of bounds
* @param {Matrix} matrix
* @param {number} index
* @param {boolean} [outer]
*/
exports.checkColumnIndex = function checkColumnIndex(matrix, index, outer) {
var max = outer ? matrix.columns : matrix.columns - 1;
if (index < 0 || index > max) {
throw new RangeError('Column index out of range');
}
};
/**
* @private
* Check that the provided vector is an array with the right length
* @param {Matrix} matrix
* @param {Array|Matrix} vector
* @return {Array}
* @throws {RangeError}
*/
exports.checkRowVector = function checkRowVector(matrix, vector) {
if (vector.to1DArray) {
vector = vector.to1DArray();
}
if (vector.length !== matrix.columns) {
throw new RangeError('vector size must be the same as the number of columns');
}
return vector;
};
/**
* @private
* Check that the provided vector is an array with the right length
* @param {Matrix} matrix
* @param {Array|Matrix} vector
* @return {Array}
* @throws {RangeError}
*/
exports.checkColumnVector = function checkColumnVector(matrix, vector) {
if (vector.to1DArray) {
vector = vector.to1DArray();
}
if (vector.length !== matrix.rows) {
throw new RangeError('vector size must be the same as the number of rows');
}
return vector;
};
exports.checkIndices = function checkIndices(matrix, rowIndices, columnIndices) {
var rowOut = rowIndices.some(r => {
return r < 0 || r >= matrix.rows;
});
var columnOut = columnIndices.some(c => {
return c < 0 || c >= matrix.columns;
});
if (rowOut || columnOut) {
throw new RangeError('Indices are out of range');
}
if (typeof rowIndices !== 'object' || typeof columnIndices !== 'object') {
throw new TypeError('Unexpected type for row/column indices');
}
if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);
if (!Array.isArray(columnIndices)) rowIndices = Array.from(columnIndices);
return {
row: rowIndices,
column: columnIndices
};
};
exports.checkRange = function checkRange(matrix, startRow, endRow, startColumn, endColumn) {
if (arguments.length !== 5) throw new TypeError('Invalid argument type');
var notAllNumbers = Array.from(arguments).slice(1).some(function (arg) {
return typeof arg !== 'number';
});
if (notAllNumbers) throw new TypeError('Invalid argument type');
if (startRow > endRow || startColumn > endColumn || startRow < 0 || startRow >= matrix.rows || endRow < 0 || endRow >= matrix.rows || startColumn < 0 || startColumn >= matrix.columns || endColumn < 0 || endColumn >= matrix.columns) {
throw new RangeError('Submatrix indices are out of range');
}
};
exports.getRange = function getRange(from, to) {
var arr = new Array(to - from + 1);
for (var i = 0; i < arr.length; i++) {
arr[i] = from + i;
}
return arr;
};
exports.sumByRow = function sumByRow(matrix) {
var sum = Matrix.Matrix.zeros(matrix.rows, 1);
for (var i = 0; i < matrix.rows; ++i) {
for (var j = 0; j < matrix.columns; ++j) {
sum.set(i, 0, sum.get(i, 0) + matrix.get(i, j));
}
}
return sum;
};
exports.sumByColumn = function sumByColumn(matrix) {
var sum = Matrix.Matrix.zeros(1, matrix.columns);
for (var i = 0; i < matrix.rows; ++i) {
for (var j = 0; j < matrix.columns; ++j) {
sum.set(0, j, sum.get(0, j) + matrix.get(i, j));
}
}
return sum;
};
exports.sumAll = function sumAll(matrix) {
var v = 0;
for (var i = 0; i < matrix.rows; i++) {
for (var j = 0; j < matrix.columns; j++) {
v += matrix.get(i, j);
}
}
return v;
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function getConverter() {
// the following RegExp can only be used for XYdata, some peakTables have values with a "E-5" ...
const ntuplesSeparator = /[, \t]+/;
const GC_MS_FIELDS = ['TIC', '.RIC', 'SCANNUMBER'];
function convertToFloatArray(stringArray) {
var l = stringArray.length;
var floatArray = new Array(l);
for (var i = 0; i < l; i++) {
floatArray[i] = parseFloat(stringArray[i]);
}
return floatArray;
}
class Spectrum {}
const defaultOptions = {
keepRecordsRegExp: /^$/,
xy: false,
withoutXY: false,
chromatogram: false,
keepSpectra: false,
noContour: false,
nbContourLevels: 7,
noiseMultiplier: 5
};
function convert(jcamp, options) {
options = Object.assign({}, defaultOptions, options);
var wantXY = !options.withoutXY;
var start = Date.now();
var ntuples = {};
var ldr, dataLabel, dataValue, ldrs;
var i, ii, j, position, endLine, infos;
var result = {};
result.profiling = [];
result.logs = [];
var spectra = [];
result.spectra = spectra;
result.info = {};
var spectrum = new Spectrum();
if (!(typeof jcamp === 'string')) {
throw new TypeError('the JCAMP should be a string');
}
if (result.profiling) {
result.profiling.push({
action: 'Before split to LDRS',
time: Date.now() - start
});
}
ldrs = jcamp.split(/[\r\n]+##/);
if (result.profiling) {
result.profiling.push({
action: 'Split to LDRS',
time: Date.now() - start
});
}
if (ldrs[0]) ldrs[0] = ldrs[0].replace(/^[\r\n ]*##/, '');
for (i = 0, ii = ldrs.length; i < ii; i++) {
ldr = ldrs[i]; // This is a new LDR
position = ldr.indexOf('=');
if (position > 0) {
dataLabel = ldr.substring(0, position);
dataValue = ldr.substring(position + 1).trim();
} else {
dataLabel = ldr;
dataValue = '';
}
dataLabel = dataLabel.replace(/[_ -]/g, '').toUpperCase();
if (dataLabel === 'DATATABLE') {
endLine = dataValue.indexOf('\n');
if (endLine === -1) endLine = dataValue.indexOf('\r');
if (endLine > 0) {
var xIndex = -1;
var yIndex = -1; // ##DATA TABLE= (X++(I..I)), XYDATA
// We need to find the variables
infos = dataValue.substring(0, endLine).split(/[ ,;\t]+/);
if (infos[0].indexOf('++') > 0) {
var firstVariable = infos[0].replace(/.*\(([a-zA-Z0-9]+)\+\+.*/, '$1');
var secondVariable = infos[0].replace(/.*\.\.([a-zA-Z0-9]+).*/, '$1');
xIndex = ntuples.symbol.indexOf(firstVariable);
yIndex = ntuples.symbol.indexOf(secondVariable);
}
if (xIndex === -1) xIndex = 0;
if (yIndex === -1) yIndex = 0;
if (ntuples.first) {
if (ntuples.first.length > xIndex) {
spectrum.firstX = ntuples.first[xIndex];
}
if (ntuples.first.length > yIndex) {
spectrum.firstY = ntuples.first[yIndex];
}
}
if (ntuples.last) {
if (ntuples.last.length > xIndex) {
spectrum.lastX = ntuples.last[xIndex];
}
if (ntuples.last.length > yIndex) {
spectrum.lastY = ntuples.last[yIndex];
}
}
if (ntuples.vardim && ntuples.vardim.length > xIndex) {
spectrum.nbPoints = ntuples.vardim[xIndex];
}
if (ntuples.factor) {
if (ntuples.factor.length > xIndex) {
spectrum.xFactor = ntuples.factor[xIndex];
}
if (ntuples.factor.length > yIndex) {
spectrum.yFactor = ntuples.factor[yIndex];
}
}
if (ntuples.units) {
if (ntuples.units.length > xIndex) {
spectrum.xUnit = ntuples.units[xIndex];
}
if (ntuples.units.length > yIndex) {
spectrum.yUnit = ntuples.units[yIndex];
}
}
spectrum.datatable = infos[0];
if (infos[1] && infos[1].indexOf('PEAKS') > -1) {
dataLabel = 'PEAKTABLE';
} else if (infos[1] && (infos[1].indexOf('XYDATA') || infos[0].indexOf('++') > 0)) {
dataLabel = 'XYDATA';
spectrum.deltaX = (spectrum.lastX - spectrum.firstX) / (spectrum.nbPoints - 1);
}
}
}
if (dataLabel === 'XYDATA') {
if (wantXY) {
prepareSpectrum(result, spectrum); // well apparently we should still consider it is a PEAK TABLE if there are no '++' after
if (dataValue.match(/.*\+\+.*/)) {
if (!spectrum.deltaX) {
spectrum.deltaX = (spectrum.lastX - spectrum.firstX) / (spectrum.nbPoints - 1);
}
fastParseXYData(spectrum, dataValue, result);
} else {
parsePeakTable(spectrum, dataValue, result);
}
spectra.push(spectrum);
spectrum = new Spectrum();
}
continue;
} else if (dataLabel === 'PEAKTABLE') {
if (wantXY) {
prepareSpectrum(result, spectrum);
parsePeakTable(spectrum, dataValue, result);
spectra.push(spectrum);
spectrum = new Spectrum();
}
continue;
}
if (dataLabel === 'TITLE') {
spectrum.title = dataValue;
} else if (dataLabel === 'DATATYPE') {
spectrum.dataType = dataValue;
if (dataValue.indexOf('nD') > -1) {
result.twoD = true;
}
} else if (dataLabel === 'NTUPLES') {
if (dataValue.indexOf('nD') > -1) {
result.twoD = true;
}
} else if (dataLabel === 'XUNITS') {
spectrum.xUnit = dataValue;
} else if (dataLabel === 'YUNITS') {
spectrum.yUnit = dataValue;
} else if (dataLabel === 'FIRSTX') {
spectrum.firstX = parseFloat(dataValue);
} else if (dataLabel === 'LASTX') {
spectrum.lastX = parseFloat(dataValue);
} else if (dataLabel === 'FIRSTY') {
spectrum.firstY = parseFloat(dataValue);
} else if (dataLabel === 'LASTY') {
spectrum.lastY = parseFloat(dataValue);
} else if (dataLabel === 'NPOINTS') {
spectrum.nbPoints = parseFloat(dataValue);
} else if (dataLabel === 'XFACTOR') {
spectrum.xFactor = parseFloat(dataValue);
} else if (dataLabel === 'YFACTOR') {
spectrum.yFactor = parseFloat(dataValue);
} else if (dataLabel === 'DELTAX') {
spectrum.deltaX = parseFloat(dataValue);
} else if (dataLabel === '.OBSERVEFREQUENCY' || dataLabel === '$SFO1') {
if (!spectrum.observeFrequency) {
spectrum.observeFrequency = parseFloat(dataValue);
}
} else if (dataLabel === '.OBSERVENUCLEUS') {
if (!spectrum.xType) {
result.xType = dataValue.replace(/[^a-zA-Z0-9]/g, '');
}
} else if (dataLabel === '$SFO2') {
if (!result.indirectFrequency) {
result.indirectFrequency = parseFloat(dataValue);
}
} else if (dataLabel === '$OFFSET') {
// OFFSET for Bruker spectra
result.shiftOffsetNum = 0;
if (!result.shiftOffsetVal) {
result.shiftOffsetVal = parseFloat(dataValue);
}
} else if (dataLabel === '$REFERENCEPOINT') {// OFFSET for Varian spectra
// if we activate this part it does not work for ACD specmanager
// } else if (dataLabel=='.SHIFTREFERENCE') { // OFFSET FOR Bruker Spectra
// var parts = dataValue.split(/ *, */);
// result.shiftOffsetNum = parseInt(parts[2].trim());
// result.shiftOffsetVal = parseFloat(parts[3].trim());
} else if (dataLabel === 'VARNAME') {
ntuples.varname = dataValue.split(ntuplesSeparator);
} else if (dataLabel === 'SYMBOL') {
ntuples.symbol = dataValue.split(ntuplesSeparator);
} else if (dataLabel === 'VARTYPE') {
ntuples.vartype = dataValue.split(ntuplesSeparator);
} else if (dataLabel === 'VARFORM') {
ntuples.varform = dataValue.split(ntuplesSeparator);
} else if (dataLabel === 'VARDIM') {
ntuples.vardim = convertToFloatArray(dataValue.split(ntuplesSeparator));
} else if (dataLabel === 'UNITS') {
ntuples.units = dataValue.split(ntuplesSeparator);
} else if (dataLabel === 'FACTOR') {
ntuples.factor = convertToFloatArray(dataValue.split(ntuplesSeparator));
} else if (dataLabel === 'FIRST') {
ntuples.first = convertToFloatArray(dataValue.split(ntuplesSeparator));
} else if (dataLabel === 'LAST') {
ntuples.last = convertToFloatArray(dataValue.split(ntuplesSeparator));
} else if (dataLabel === 'MIN') {
ntuples.min = convertToFloatArray(dataValue.split(ntuplesSeparator));
} else if (dataLabel === 'MAX') {
ntuples.max = convertToFloatArray(dataValue.split(ntuplesSeparator));
} else if (dataLabel === '.NUCLEUS') {
if (result.twoD) {
result.yType = dataValue.split(ntuplesSeparator)[0];
}
} else if (dataLabel === 'PAGE') {
spectrum.page = dataValue.trim();
spectrum.pageValue = parseFloat(dataValue.replace(/^.*=/, ''));
spectrum.pageSymbol = spectrum.page.replace(/[=].*/, '');
var pageSymbolIndex = ntuples.symbol.indexOf(spectrum.pageSymbol);
var unit = '';
if (ntuples.units && ntuples.units[pageSymbolIndex]) {
unit = ntuples.units[pageSymbolIndex];
}
if (result.indirectFrequency && unit !== 'PPM') {
spectrum.pageValue /= result.indirectFrequency;
}
} else if (dataLabel === 'RETENTIONTIME') {
spectrum.pageValue = parseFloat(dataValue);
} else if (isMSField(dataLabel)) {
spectrum[convertMSFieldToLabel(dataLabel)] = dataValue;
}
if (dataLabel.match(options.keepRecordsRegExp)) {
result.info[dataLabel] = dataValue.trim();
}
}
if (result.profiling) {
result.profiling.push({
action: 'Finished parsing',
time: Date.now() - start
});
}
if (Object.keys(ntuples).length > 0) {
var newNtuples = [];
var keys = Object.keys(ntuples);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
var values = ntuples[key];
for (j = 0; j < values.length; j++) {
if (!newNtuples[j]) newNtuples[j] = {};
newNtuples[j][key] = values[j];
}
}
result.ntuples = newNtuples;
}
if (result.twoD && wantXY) {
add2D(result, options);
if (result.profiling) {
result.profiling.push({
action: 'Finished countour plot calculation',
time: Date.now() - start
});
}
if (!options.keepSpectra) {
delete result.spectra;
}
}
if (options.chromatogram) {
options.xy = true;
}
if (options.xy && wantXY) {
// the spectraData should not be a oneD array but an object with x and y
if (spectra.length > 0) {
for (i = 0; i < spectra.length; i++) {
spectrum = spectra[i];
if (spectrum.data.length > 0) {
for (j = 0; j < spectrum.data.length; j++) {
var data = spectrum.data[j];
var newData = {
x: new Array(data.length / 2),
y: new Array(data.length / 2)
};
for (var k = 0; k < data.length; k = k + 2) {
newData.x[k / 2] = data[k];
newData.y[k / 2] = data[k + 1];
}
spectrum.data[j] = newData;
}
}
}
}
} // maybe it is a GC (HPLC) / MS. In this case we add a new format
if (options.chromatogram) {
if (result.spectra.length > 1) {
complexChromatogram(result);
} else {
simpleChromatogram(result);
}
if (result.profiling) {
result.profiling.push({
action: 'Finished chromatogram calculation',
time: Date.now() - start
});
}
}
if (result.profiling) {
result.profiling.push({
action: 'Total time',
time: Date.now() - start
});
}
return result;
}
function convertMSFieldToLabel(value) {
return value.toLowerCase().replace(/[^a-z0-9]/g, '');
}
function isMSField(dataLabel) {
return GC_MS_FIELDS.indexOf(dataLabel) !== -1;
}
function complexChromatogram(result) {
var spectra = result.spectra;
var length = spectra.length;
var chromatogram = {
times: new Array(length),
series: {
ms: {
dimension: 2,
data: new Array(length)
}
}
};
var i;
var existingGCMSFields = [];
for (i = 0; i < GC_MS_FIELDS.length; i++) {
var label = convertMSFieldToLabel(GC_MS_FIELDS[i]);
if (spectra[0][label]) {
existingGCMSFields.push(label);
chromatogram.series[label] = {
dimension: 1,
data: new Array(length)
};
}
}
for (i = 0; i < length; i++) {
var spectrum = spectra[i];
chromatogram.times[i] = spectrum.pageValue;
for (var j = 0; j < existingGCMSFields.length; j++) {
chromatogram.series[existingGCMSFields[j]].data[i] = parseFloat(spectrum[existingGCMSFields[j]]);
}
if (spectrum.data) {
chromatogram.series.ms.data[i] = [spectrum.data[0].x, spectrum.data[0].y];
}
}
result.chromatogram = chromatogram;
}
function simpleChromatogram(result) {
var data = result.spectra[0].data[0];
result.chromatogram = {
times: data.x.slice(),
series: {
intensity: {
dimension: 1,
data: data.y.slice()
}
}
};
}
function prepareSpectrum(result, spectrum) {
if (!spectrum.xFactor) spectrum.xFactor = 1;
if (!spectrum.yFactor) spectrum.yFactor = 1;
if (spectrum.observeFrequency) {
if (spectrum.xUnit && spectrum.xUnit.toUpperCase() === 'HZ') {
spectrum.xUnit = 'PPM';
spectrum.xFactor = spectrum.xFactor / spectrum.observeFrequency;
spectrum.firstX = spectrum.firstX / spectrum.observeFrequency;
spectrum.lastX = spectrum.lastX / spectrum.observeFrequency;
spectrum.deltaX = spectrum.deltaX / spectrum.observeFrequency;
}
}
if (result.shiftOffsetVal) {
var shift = spectrum.firstX - result.shiftOffsetVal;
spectrum.firstX = spectrum.firstX - shift;
spectrum.lastX = spectrum.lastX - shift;
}
}
function getMedian(data) {
data = data.sort(compareNumbers);
var l = data.length;
return data[Math.floor(l / 2)];
}
function compareNumbers(a, b) {
return a - b;
}
function convertTo3DZ(spectra) {
var minZ = spectra[0].data[0][0];
var maxZ = minZ;
var ySize = spectra.length;
var xSize = spectra[0].data[0].length / 2;
var z = new Array(ySize);
for (var i = 0; i < ySize; i++) {
z[i] = new Array(xSize);
var xVector = spectra[i].data[0];
for (var j = 0; j < xSize; j++) {
var value = xVector[j * 2 + 1];
z[i][j] = value;
if (value < minZ) minZ = value;
if (value > maxZ) maxZ = value;
}
}
return {
z: z,
minX: spectra[0].data[0][0],
maxX: spectra[0].data[0][spectra[0].data[0].length - 2],
// has to be -2 because it is a 1D array [x,y,x,y,...]
minY: spectra[0].pageValue,
maxY: spectra[ySize - 1].pageValue,
minZ: minZ,
maxZ: maxZ,
noise: getMedian(z[0].map(Math.abs))
};
}
function add2D(result, options) {
var zData = convertTo3DZ(result.spectra);
if (!options.noContour) {
result.contourLines = generateContourLines(zData, options);
delete zData.z;
}
result.minMax = zData;
}
function generateContourLines(zData, options) {
var noise = zData.noise;
var z = zData.z;
var povarHeight0, povarHeight1, povarHeight2, povarHeight3;
var isOver0, isOver1, isOver2, isOver3;
var nbSubSpectra = z.length;
var nbPovars = z[0].length;
var pAx, pAy, pBx, pBy;
var x0 = zData.minX;
var xN = zData.maxX;
var dx = (xN - x0) / (nbPovars - 1);
var y0 = zData.minY;
var yN = zData.maxY;
var dy = (yN - y0) / (nbSubSpectra - 1);
var minZ = zData.minZ;
var maxZ = zData.maxZ; // System.out.prvarln('y0 '+y0+' yN '+yN);
// -------------------------
// Povars attribution
//
// 0----1
// | / |
// | / |
// 2----3
//
// ---------------------d------
var iter = options.nbContourLevels * 2;
var contourLevels = new Array(iter);
var lineZValue;
for (var level = 0; level < iter; level++) {
// multiply by 2 for positif and negatif
var contourLevel = {};
contourLevels[level] = contourLevel;
var side = level % 2;
var factor = (maxZ - options.noiseMultiplier * noise) * Math.exp((level >> 1) - options.nbContourLevels);
if (side === 0) {
lineZValue = factor + options.noiseMultiplier * noise;
} else {
lineZValue = 0 - factor - options.noiseMultiplier * noise;
}
var lines = [];
contourLevel.zValue = lineZValue;
contourLevel.lines = lines;
if (lineZValue <= minZ || lineZValue >= maxZ) continue;
for (var iSubSpectra = 0; iSubSpectra < nbSubSpectra - 1; iSubSpectra++) {
var subSpectra = z[iSubSpectra];
var subSpectraAfter = z[iSubSpectra + 1];
for (var povar = 0; povar < nbPovars - 1; povar++) {
povarHeight0 = subSpectra[povar];
povarHeight1 = subSpectra[povar + 1];
povarHeight2 = subSpectraAfter[povar];
povarHeight3 = subSpectraAfter[povar + 1];
isOver0 = povarHeight0 > lineZValue;
isOver1 = povarHeight1 > lineZValue;
isOver2 = povarHeight2 > lineZValue;
isOver3 = povarHeight3 > lineZValue; // Example povar0 is over the plane and povar1 and
// povar2 are below, we find the varersections and add
// the segment
if (isOver0 !== isOver1 && isOver0 !== isOver2) {
pAx = povar + (lineZValue - povarHeight0) / (povarHeight1 - povarHeight0);
pAy = iSubSpectra;
pBx = povar;
pBy = iSubSpectra + (lineZValue - povarHeight0) / (povarHeight2 - povarHeight0);
lines.push(pAx * dx + x0);
lines.push(pAy * dy + y0);
lines.push(pBx * dx + x0);
lines.push(pBy * dy + y0);
} // remove push does not help !!!!
if (isOver3 !== isOver1 && isOver3 !== isOver2) {
pAx = povar + 1;
pAy = iSubSpectra + 1 - (lineZValue - povarHeight3) / (povarHeight1 - povarHeight3);
pBx = povar + 1 - (lineZValue - povarHeight3) / (povarHeight2 - povarHeight3);
pBy = iSubSpectra + 1;
lines.push(pAx * dx + x0);
lines.push(pAy * dy + y0);
lines.push(pBx * dx + x0);
lines.push(pBy * dy + y0);
} // test around the diagonal
if (isOver1 !== isOver2) {
pAx = (povar + 1 - (lineZValue - povarHeight1) / (povarHeight2 - povarHeight1)) * dx + x0;
pAy = (iSubSpectra + (lineZValue - povarHeight1) / (povarHeight2 - povarHeight1)) * dy + y0;
if (isOver1 !== isOver0) {
pBx = povar + 1 - (lineZValue - povarHeight1) / (povarHeight0 - povarHeight1);
pBy = iSubSpectra;
lines.push(pAx);
lines.push(pAy);
lines.push(pBx * dx + x0);
lines.push(pBy * dy + y0);
}
if (isOver2 !== isOver0) {
pBx = povar;
pBy = iSubSpectra + 1 - (lineZValue - povarHeight2) / (povarHeight0 - povarHeight2);
lines.push(pAx);
lines.push(pAy);
lines.push(pBx * dx + x0);
lines.push(pBy * dy + y0);
}
if (isOver1 !== isOver3) {
pBx = povar + 1;
pBy = iSubSpectra + (lineZValue - povarHeight1) / (povarHeight3 - povarHeight1);
lines.push(pAx);
lines.push(pAy);
lines.push(pBx * dx + x0);
lines.push(pBy * dy + y0);
}
if (isOver2 !== isOver3) {
pBx = povar + (lineZValue - povarHeight2) / (povarHeight3 - povarHeight2);
pBy = iSubSpectra + 1;
lines.push(pAx);
lines.push(pAy);
lines.push(pBx * dx + x0);
lines.push(pBy * dy + y0);
}
}
}
}
}
return {
minX: zData.minX,
maxX: zData.maxX,
minY: zData.minY,
maxY: zData.maxY,
segments: contourLevels
};
}
function fastParseXYData(spectrum, value) {
// TODO need to deal with result
// console.log(value);
// we check if deltaX is defined otherwise we calculate it
var yFactor = spectrum.yFactor;
var deltaX = spectrum.deltaX;
spectrum.isXYdata = true; // TODO to be improved using 2 array {x:[], y:[]}
var currentData = [];
spectrum.data = [currentData];
var currentX = spectrum.firstX;
var currentY = spectrum.firstY; // we skip the first line
//
var endLine = false;
var ascii;
for (var i = 0; i < value.length; i++) {
ascii = value.charCodeAt(i);
if (ascii === 13 || ascii === 10) {
endLine = true;
} else {
if (endLine) break;
}
} // we proceed taking the i after the first line
var newLine = true;
var isDifference = false;
var isLastDifference = false;
var lastDifference = 0;
var isDuplicate = false;
var inComment = false;
var currentValue = 0;
var isNegative = false;
var inValue = false;
var skipFirstValue = false;
var decimalPosition = 0;
for (; i <= value.length; i++) {
if (i === value.length) ascii = 13;else ascii = value.charCodeAt(i);
if (inComment) {
// we should ignore the text if we are after $$
if (ascii === 13 || ascii === 10) {
newLine = true;
inComment = false;
}
} else {
// when is it a new value ?
// when it is not a digit, . or comma
// it is a number that is either new or we continue
if (ascii <= 57 && ascii >= 48) {
// a number
inValue = true;
if (decimalPosition > 0) {
currentValue += (ascii - 48) / Math.pow(10, decimalPosition++);
} else {
currentValue *= 10;
currentValue += ascii - 48;
}
} else if (ascii === 44 || ascii === 46) {
// a "," or "."
inValue = true;
decimalPosition++;
} else {
if (inValue) {
// need to process the previous value
if (newLine) {
newLine = false; // we don't check the X value
// console.log("NEW LINE",isDifference, lastDifference);
// if new line and lastDifference, the first value is just a check !
// that we don't check ...
if (isLastDifference) skipFirstValue = true;
} else {
// need to deal with duplicate and differences
if (skipFirstValue) {
skipFirstValue = false;
} else {
if (isDifference) {
lastDifference = isNegative ? 0 - currentValue : currentValue;
isLastDifference = true;
isDifference = false;
}
var duplicate = isDuplicate ? currentValue - 1 : 1;
for (var j = 0; j < duplicate; j++) {
if (isLastDifference) {
currentY += lastDifference;
} else {
currentY = isNegative ? 0 - currentValue : currentValue;
}
currentData.push(currentX);
currentData.push(currentY * yFactor);
currentX += deltaX;
}
}
}
isNegative = false;
currentValue = 0;
decimalPosition = 0;
inValue = false;
isDuplicate = false;
} // positive SQZ digits @ A B C D E F G H I (ascii 64-73)
if (ascii < 74 && ascii > 63) {
inValue = true;
isLastDifference = false;
currentValue = ascii - 64;
} else if (ascii > 96 && ascii < 106) {
// negative SQZ digits a b c d e f g h i (ascii 97-105)
inValue = true;
isLastDifference = false;
currentValue = ascii - 96;
isNegative = true;
} else if (ascii === 115) {
// DUP digits S T U V W X Y Z s (ascii 83-90, 115)
inValue = true;
isDuplicate = true;
currentValue = 9;
} else if (ascii > 82 && ascii < 91) {
inValue = true;
isDuplicate = true;
currentValue = ascii - 82;
} else if (ascii > 73 && ascii < 83) {
// positive DIF digits % J K L M N O P Q R (ascii 37, 74-82)
inValue = true;
isDifference = true;
currentValue = ascii - 73;
} else if (ascii > 105 && ascii < 115) {
// negative DIF digits j k l m n o p q r (ascii 106-114)
inValue = true;
isDifference = true;
currentValue = ascii - 105;
isNegative = true;
} else if (ascii === 36 && value.charCodeAt(i + 1) === 36) {
// $ sign, we need to check the next one
inValue = true;
inComment = true;
} else if (ascii === 37) {
// positive DIF digits % J K L M N O P Q R (ascii 37, 74-82)
inValue = true;
isDifference = true;
currentValue = 0;
isNegative = false;
} else if (ascii === 45) {
// a "-"
// check if after there is a number, decimal or comma
var ascii2 = value.charCodeAt(i + 1);
if (ascii2 >= 48 && ascii2 <= 57 || ascii2 === 44 || ascii2 === 46) {
inValue = true;
if (!newLine) isLastDifference = false;
isNegative = true;
}
} else if (ascii === 13 || ascii === 10) {
newLine = true;
inComment = false;
} // and now analyse the details ... space or tabulation
// if "+" we just don't care
}
}
}
}
function parsePeakTable(spectrum, value, result) {
var removeCommentRegExp = /\$\$.*/;
var peakTableSplitRegExp = /[,\t ]+/;
spectrum.isPeaktable = true;
var i, ii, j, jj, values;
var currentData = [];
spectrum.data = [currentData]; // counts for around 20% of the time
var lines = value.split(/,? *,?[;\r\n]+ */);
for (i = 1, ii = lines.length; i < ii; i++) {
values = lines[i].trim().replace(removeCommentRegExp, '').split(peakTableSplitRegExp);
if (values.length % 2 === 0) {
for (j = 0, jj = values.length; j < jj; j = j + 2) {
// takes around 40% of the time to add and parse the 2 values nearly exclusively because of parseFloat
currentData.push(parseFloat(values[j]) * spectrum.xFactor);
currentData.push(parseFloat(values[j + 1]) * spectrum.yFactor);
}
} else {
result.logs.push(`Format error: ${values}`);
}
}
}
return convert;
}
var convert = getConverter();
function JcampConverter(input, options, useWorker) {
if (typeof options === 'boolean') {
useWorker = options;
options = {};
}
if (useWorker) {
return postToWorker(input, options);
} else {
return convert(input, options);
}
}
var stamps = {};
var worker;
function postToWorker(input, options) {
if (!worker) {
createWorker();
}
return new Promise(function (resolve) {
var stamp = `${Date.now()}${Math.random()}`;
stamps[stamp] = resolve;
worker.postMessage(JSON.stringify({
stamp: stamp,
input: input,
options: options
}));
});
}
function createWorker() {
var workerURL = URL.createObjectURL(new Blob([`var getConverter =${getConverter.toString()};var convert = getConverter(); onmessage = function (event) { var data = JSON.parse(event.data); postMessage(JSON.stringify({stamp: data.stamp, output: convert(data.input, data.options)})); };`], {
type: 'application/javascript'
}));
worker = new Worker(workerURL);
URL.revokeObjectURL(workerURL);
worker.addEventListener('message', function (event) {
var data = JSON.parse(event.data);
var stamp = data.stamp;
if (stamps[stamp]) {
stamps[stamp](data.output);
}
});
}
function createTree(jcamp) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const _options$flatten = options.flatten,
flatten = _options$flatten === void 0 ? false : _options$flatten;
if (typeof jcamp !== 'string') {
throw new TypeError('the JCAMP should be a string');
}
let lines = jcamp.split(/[\r\n]+/);
let flat = [];
let stack = [];
let result = [];
let current;
let ntupleLevel = 0;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.substring(0, 9) === '##NTUPLES') {
ntupleLevel++;
}
if (line.substring(0, 7) === '##TITLE') {
let title = [line.substring(8).trim()];
for (let j = i + 1; j < lines.length; j++) {
if (lines[j].startsWith('##')) {
break;
} else {
title.push(lines[j].trim());
}
}
stack.push({
title: title.join('\n'),
jcamp: `${line}\n`,
children: []
});
current = stack[stack.length - 1];
flat.push(current);
} else if (line.substring(0, 5) === '##END' && ntupleLevel === 0) {
current.jcamp += `${line}\n`;
var finished = stack.pop();
if (stack.length !== 0) {
current = stack[stack.length - 1];
current.children.push(finished);
} else {
current = undefined;
result.push(finished);
}
} else if (current && current.jcamp) {
current.jcamp += `${line}\n`;
var match = line.match(/^##(.*?)=(.+)/);
if (match) {
var dataLabel = match[1].replace(/[ _-]/g, '').toUpperCase();
if (dataLabel === 'DATATYPE') {
current.dataType = match[2].trim();
}
}
}
if (line.substring(0, 5) === '##END' && ntupleLevel > 0) {
ntupleLevel--;
}
}
if (flatten) {
flat.forEach(entry => {
entry.children = undefined;
});
return flat;
} else {
return result;
}
}
module.exports = {
convert: JcampConverter,
createTree: createTree
};
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Created by acastillo on 8/8/16.
*/
const defOptions = {
threshold: 0,
out: "assignment"
}; //TODO Consider a matrix of distances too
module.exports = function fullClusterGenerator(conMat, opt) {
const options = Object.assign({}, defOptions, opt);
var clList, i, j, k;
if (typeof conMat[0] === "number") {
clList = fullClusterGeneratorVector(conMat);
} else {
if (typeof conMat[0] === "object") {
var nRows = conMat.length;
var conn = new Array(nRows * (nRows + 1) / 2);
var index = 0;
for (var i = 0; i < nRows; i++) {
for (var j = i; j < nRows; j++) {
if (conMat[i][j] > options.threshold) conn[index++] = 1;else conn[index++] = 0;
}
}
clList = fullClusterGeneratorVector(conn);
}
}
if (options.out === "indexes" || options.out === "values") {
var result = new Array(clList.length);
for (i = 0; i < clList.length; i++) {
result[i] = [];
for (j = 0; j < clList[i].length; j++) {
if (clList[i][j] != 0) {
result[i].push(j);
}
}
}
if (options.out === "values") {
var resultAsMatrix = new Array(result.length);
for (i = 0; i < result.length; i++) {
resultAsMatrix[i] = new Array(result[i].length);
for (j = 0; j < result[i].length; j++) {
resultAsMatrix[i][j] = new Array(result[i].length);
for (k = 0; k < result[i].length; k++) {
resultAsMatrix[i][j][k] = conMat[result[i][j]][result[i][k]];
}
}
}
return resultAsMatrix;
} else {
return result;
}
}
return clList;
};
function fullClusterGeneratorVector(conn) {
var nRows = Math.sqrt(conn.length * 2 + 0.25) - 0.5;
var clusterList = [];
var available = new Array(nRows);
var remaining = nRows,
i = 0;
var cluster = []; //Mark all the elements as available
for (i = nRows - 1; i >= 0; i--) {
available[i] = 1;
}
var nextAv = -1;
var toInclude = [];
while (remaining > 0) {
if (toInclude.length === 0) {
//If there is no more elements to include. Start a new cluster
cluster = new Array(nRows);
for (i = 0; i < nRows; i++) cluster[i] = 0;
clusterList.push(cluster);
for (nextAv = 0; available[nextAv] == 0; nextAv++) {}
;
} else {
nextAv = toInclude.splice(0, 1);
}
cluster[nextAv] = 1;
available[nextAv] = 0;
remaining--; //Copy the next available row
var row = new Array(nRows);
for (i = 0; i < nRows; i++) {
var c = Math.max(nextAv, i);
var r = Math.min(nextAv, i); //The element in the conn matrix
//console.log("index: "+r*(2*nRows-r-1)/2+c)
row[i] = conn[r * (2 * nRows - r - 1) / 2 + c]; //There is new elements to include in this row?
//Then, include it to the current cluster
if (row[i] == 1 && available[i] == 1 && cluster[i] == 0) {
toInclude.push(i);
cluster[i] = 1;
}
}
}
return clusterList;
}
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var numberIsNan = __webpack_require__(124);
function assertNum(x) {
if (typeof x !== 'number' || numberIsNan(x)) {
throw new TypeError('Expected a number');
}
}
exports.asc = function (a, b) {
assertNum(a);
assertNum(b);
return a - b;
};
exports.desc = function (a, b) {
assertNum(a);
assertNum(b);
return b - a;
};
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports.gsd = __webpack_require__(65);
module.exports.post = {
optimizePeaks: __webpack_require__(69),
joinBroadPeaks: __webpack_require__(88),
broadenPeaks: __webpack_require__(89)
};
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Created by acastillo on 7/7/16.
*/
var StatArray = __webpack_require__(7).array;
var convolution = __webpack_require__(127);
var labeling = __webpack_require__(130);
const smallFilter = [[0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 1, 4, 7, 7, 7, 4, 1, 0], [1, 4, 5, 3, 0, 3, 5, 4, 1], [2, 7, 3, -12, -23, -12, 3, 7, 2], [2, 7, 0, -23, -40, -23, 0, 7, 2], [2, 7, 3, -12, -23, -12, 3, 7, 2], [1, 4, 5, 3, 0, 3, 5, 4, 1], [0, 1, 3, 7, 7, 7, 3, 1, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0]];
const DEBUG = false;
/**
Detects all the 2D-peaks in the given spectrum based on center of mass logic.
*/
function findPeaks2DRegion(input, opt) {
var options = Object.assign({}, {
nStdev: 3,
kernel: smallFilter
}, opt);
var tmp = convolution.matrix2Array(input);
var inputData = tmp.data;
var i;
if (tmp.rows && tmp.cols) {
options.rows = tmp.rows;
options.cols = tmp.cols;
}
var nRows = options.rows;
var nCols = options.cols;
if (!nRows || !nCols) {
throw new Error("Invalid number of rows or columns " + nRows + " " + nCols);
}
var customFilter = options.kernel;
var cs = options.filteredData;
if (!cs) cs = convolution.fft(inputData, customFilter, options);
var nStdDev = options.nStdev;
var threshold = 0;
for (i = nCols * nRows - 2; i >= 0; i--) threshold += Math.pow(cs[i] - cs[i + 1], 2);
threshold = -Math.sqrt(threshold);
threshold *= nStdDev / nRows;
var bitmask = new Array(nCols * nRows);
for (i = nCols * nRows - 1; i >= 0; i--) {
bitmask[i] = 0;
}
var nbDetectedPoints = 0;
for (i = cs.length - 1; i >= 0; i--) {
if (cs[i] < threshold) {
bitmask[i] = 1;
nbDetectedPoints++;
}
}
var pixels = labeling(bitmask, nCols, nRows, {
neighbours: 8
});
var peakList = extractPeaks(pixels, inputData, nRows, nCols);
if (peakList.length > 0 && DEBUG) {
console.log("No peak found");
}
return peakList;
}
/**
Detects all the 2D-peaks in the given spectrum based on the Max logic.
amc
*/
function findPeaks2DMax(input, opt) {
var options = Object.assign({}, {
nStdev: 3,
kernel: smallFilter
}, opt);
var tmp = convolution.matrix2Array(input);
var inputData = tmp.data;
if (tmp.rows && tmp.cols) {
options.rows = tmp.rows;
options.cols = tmp.cols;
}
var nRows = options.rows;
var nCols = options.cols;
if (!nRows || !nCols) {
throw new Error("Invalid number of rows or columns " + nRows + " " + nCols);
}
var customFilter = options.kernel;
var cs = options.filteredData;
if (!cs) cs = convolution.fft(inputData, customFilter, options);
var nStdDev = options.nStdev;
var threshold = 0;
for (var i = nCols * nRows - 2; i >= 0; i--) threshold += Math.pow(cs[i] - cs[i + 1], 2);
threshold = -Math.sqrt(threshold);
threshold *= nStdDev / nRows;
var rowI, colI;
var peakListMax = [];
var tmpIndex = 0;
for (var i = 0; i < cs.length; i++) {
if (cs[i] < threshold) {
//It is a peak?
rowI = Math.floor(i / nCols);
colI = i % nCols; //Verifies if this point is a peak;
if (rowI > 0 && rowI + 1 < nRows && colI + 1 < nCols && colI > 0) {
//It is the minimum in the same row
if (cs[i] < cs[i + 1] && cs[i] < cs[i - 1]) {
//It is the minimum in the previous row
tmpIndex = (rowI - 1) * nCols + colI;
if (cs[i] < cs[tmpIndex - 1] && cs[i] < cs[tmpIndex] && cs[i] < cs[tmpIndex + 1]) {
//It is the minimum in the next row
tmpIndex = (rowI + 1) * nCols + colI;
if (cs[i] < cs[tmpIndex - 1] && cs[i] < cs[tmpIndex] && cs[i] < cs[tmpIndex + 1]) {
peakListMax.push({
x: colI,
y: rowI,
z: inputData[i]
});
}
}
}
}
}
}
return peakListMax;
}
function extractPeaks(pixels, data, nRow, nCols) {
//console.log(JSON.stringify(pixels));
//How many different groups we have?
var labels = {};
var row, col, tmp, i;
for (i = 0; i < pixels.length; i++) {
if (pixels[i] != 0) {
col = i % nCols;
row = (i - col) / nCols;
if (labels[pixels[i]]) {
tmp = labels[pixels[i]];
tmp.x += col * data[i];
tmp.y += row * data[i];
tmp.z += data[i];
if (col < tmp.minX) tmp.minX = col;
if (col > tmp.maxX) tmp.maxX = col;
if (row < tmp.minY) tmp.minY = row;
if (row > tmp.maxY) tmp.maxY = row;
} else {
labels[pixels[i]] = {
x: col * data[i],
y: row * data[i],
z: data[i],
minX: col,
maxX: col,
minY: row,
maxY: row
};
}
}
}
var keys = Object.keys(labels);
var peakList = new Array(keys.length);
for (i = 0; i < keys.length; i++) {
peakList[i] = labels[keys[i]];
peakList[i].x /= peakList[i].z;
peakList[i].y /= peakList[i].z;
}
return peakList;
}
module.exports = {
findPeaks2DRegion: findPeaks2DRegion,
findPeaks2DMax: findPeaks2DMax
};
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.hypotenuse = function hypotenuse(a, b) {
var r;
if (Math.abs(a) > Math.abs(b)) {
r = b / a;
return Math.abs(a) * Math.sqrt(1 + r * r);
}
if (b !== 0) {
r = a / b;
return Math.abs(b) * Math.sqrt(1 + r * r);
}
return 0;
}; // For use in the decomposition algorithms. With big matrices, access time is
// too long on elements from array subclass
// todo check when it is fixed in v8
// http://jsperf.com/access-and-write-array-subclass
exports.getEmpty2DArray = function (rows, columns) {
var array = new Array(rows);
for (var i = 0; i < rows; i++) {
array[i] = new Array(columns);
}
return array;
};
exports.getFilled2DArray = function (rows, columns, value) {
var array = new Array(rows);
for (var i = 0; i < rows; i++) {
array[i] = new Array(columns);
for (var j = 0; j < columns; j++) {
array[i][j] = value;
}
}
return array;
};
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // public method for encoding
exports.encode = function (input, utf8) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = (chr1 & 3) << 4 | chr2 >> 4;
enc3 = (chr2 & 15) << 2 | chr3 >> 6;
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
}; // public method for decoding
exports.decode = function (input, utf8) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
return output;
};
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var support = __webpack_require__(10);
var utils = __webpack_require__(2);
var _crc = __webpack_require__(105);
var signature = __webpack_require__(45);
var defaults = __webpack_require__(46);
var base64 = __webpack_require__(20);
var compressions = __webpack_require__(23);
var CompressedObject = __webpack_require__(47);
var nodeBuffer = __webpack_require__(25);
var utf8 = __webpack_require__(48);
var StringWriter = __webpack_require__(106);
var Uint8ArrayWriter = __webpack_require__(107);
/**
* Returns the raw data of a ZipObject, decompress the content if necessary.
* @param {ZipObject} file the file to use.
* @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
*/
var getRawData = function getRawData(file) {
if (file._data instanceof CompressedObject) {
file._data = file._data.getContent();
file.options.binary = true;
file.options.base64 = false;
if (utils.getTypeOf(file._data) === "uint8array") {
var copy = file._data; // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
// if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
file._data = new Uint8Array(copy.length); // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
if (copy.length !== 0) {
file._data.set(copy, 0);
}
}
}
return file._data;
};
/**
* Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
* @param {ZipObject} file the file to use.
* @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
*/
var getBinaryData = function getBinaryData(file) {
var result = getRawData(file),
type = utils.getTypeOf(result);
if (type === "string") {
if (!file.options.binary) {
// unicode text !
// unicode string => binary string is a painful process, check if we can avoid it.
if (support.nodebuffer) {
return nodeBuffer(result, "utf-8");
}
}
return file.asBinary();
}
return result;
};
/**
* Transform this._data into a string.
* @param {function} filter a function String -> String, applied if not null on the result.
* @return {String} the string representing this._data.
*/
var dataToString = function dataToString(asUTF8) {
var result = getRawData(this);
if (result === null || typeof result === "undefined") {
return "";
} // if the data is a base64 string, we decode it before checking the encoding !
if (this.options.base64) {
result = base64.decode(result);
}
if (asUTF8 && this.options.binary) {
// JSZip.prototype.utf8decode supports arrays as input
// skip to array => string step, utf8decode will do it.
result = out.utf8decode(result);
} else {
// no utf8 transformation, do the array => string step.
result = utils.transformTo("string", result);
}
if (!asUTF8 && !this.options.binary) {
result = utils.transformTo("string", out.utf8encode(result));
}
return result;
};
/**
* A simple object representing a file in the zip file.
* @constructor
* @param {string} name the name of the file
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
* @param {Object} options the options of the file
*/
var ZipObject = function ZipObject(name, data, options) {
this.name = name;
this.dir = options.dir;
this.date = options.date;
this.comment = options.comment;
this.unixPermissions = options.unixPermissions;
this.dosPermissions = options.dosPermissions;
this._data = data;
this.options = options;
/*
* This object contains initial values for dir and date.
* With them, we can check if the user changed the deprecated metadata in
* `ZipObject#options` or not.
*/
this._initialMetadata = {
dir: options.dir,
date: options.date
};
};
ZipObject.prototype = {
/**
* Return the content as UTF8 string.
* @return {string} the UTF8 string.
*/
asText: function asText() {
return dataToString.call(this, true);
},
/**
* Returns the binary content.
* @return {string} the content as binary.
*/
asBinary: function asBinary() {
return dataToString.call(this, false);
},
/**
* Returns the content as a nodejs Buffer.
* @return {Buffer} the content as a Buffer.
*/
asNodeBuffer: function asNodeBuffer() {
var result = getBinaryData(this);
return utils.transformTo("nodebuffer", result);
},
/**
* Returns the content as an Uint8Array.
* @return {Uint8Array} the content as an Uint8Array.
*/
asUint8Array: function asUint8Array() {
var result = getBinaryData(this);
return utils.transformTo("uint8array", result);
},
/**
* Returns the content as an ArrayBuffer.
* @return {ArrayBuffer} the content as an ArrayBufer.
*/
asArrayBuffer: function asArrayBuffer() {
return this.asUint8Array().buffer;
}
};
/**
* Transform an integer into a string in hexadecimal.
* @private
* @param {number} dec the number to convert.
* @param {number} bytes the number of bytes to generate.
* @returns {string} the result.
*/
var decToHex = function decToHex(dec, bytes) {
var hex = "",
i;
for (i = 0; i < bytes; i++) {
hex += String.fromCharCode(dec & 0xff);
dec = dec >>> 8;
}
return hex;
};
/**
* Transforms the (incomplete) options from the user into the complete
* set of options to create a file.
* @private
* @param {Object} o the options from the user.
* @return {Object} the complete set of options.
*/
var prepareFileAttrs = function prepareFileAttrs(o) {
o = o || {};
if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
o.binary = true;
}
o = utils.extend(o, defaults);
o.date = o.date || new Date();
if (o.compression !== null) o.compression = o.compression.toUpperCase();
return o;
};
/**
* Add a file in the current folder.
* @private
* @param {string} name the name of the file
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
* @param {Object} o the options of the file
* @return {Object} the new file.
*/
var fileAdd = function fileAdd(name, data, o) {
// be sure sub folders exist
var dataType = utils.getTypeOf(data),
parent;
o = prepareFileAttrs(o);
if (typeof o.unixPermissions === "string") {
o.unixPermissions = parseInt(o.unixPermissions, 8);
} // UNX_IFDIR 0040000 see zipinfo.c
if (o.unixPermissions && o.unixPermissions & 0x4000) {
o.dir = true;
} // Bit 4 Directory
if (o.dosPermissions && o.dosPermissions & 0x0010) {
o.dir = true;
}
if (o.dir) {
name = forceTrailingSlash(name);
}
if (o.createFolders && (parent = parentFolder(name))) {
folderAdd.call(this, parent, true);
}
if (o.dir || data === null || typeof data === "undefined") {
o.base64 = false;
o.binary = false;
data = null;
dataType = null;
} else if (dataType === "string") {
if (o.binary && !o.base64) {
// optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
if (o.optimizedBinaryString !== true) {
// this is a string, not in a base64 format.
// Be sure that this is a correct "binary string"
data = utils.string2binary(data);
}
}
} else {
// arraybuffer, uint8array, ...
o.base64 = false;
o.binary = true;
if (!dataType && !(data instanceof CompressedObject)) {
throw new Error("The data of '" + name + "' is in an unsupported format !");
} // special case : it's way easier to work with Uint8Array than with ArrayBuffer
if (dataType === "arraybuffer") {
data = utils.transformTo("uint8array", data);
}
}
var object = new ZipObject(name, data, o);
this.files[name] = object;
return object;
};
/**
* Find the parent folder of the path.
* @private
* @param {string} path the path to use
* @return {string} the parent folder, or ""
*/
var parentFolder = function parentFolder(path) {
if (path.slice(-1) == '/') {
path = path.substring(0, path.length - 1);
}
var lastSlash = path.lastIndexOf('/');
return lastSlash > 0 ? path.substring(0, lastSlash) : "";
};
/**
* Returns the path with a slash at the end.
* @private
* @param {String} path the path to check.
* @return {String} the path with a trailing slash.
*/
var forceTrailingSlash = function forceTrailingSlash(path) {
// Check the name ends with a /
if (path.slice(-1) != "/") {
path += "/"; // IE doesn't like substr(-1)
}
return path;
};
/**
* Add a (sub) folder in the current folder.
* @private
* @param {string} name the folder's name
* @param {boolean=} [createFolders] If true, automatically create sub
* folders. Defaults to false.
* @return {Object} the new folder.
*/
var folderAdd = function folderAdd(name, createFolders) {
createFolders = typeof createFolders !== 'undefined' ? createFolders : false;
name = forceTrailingSlash(name); // Does this folder already exist?
if (!this.files[name]) {
fileAdd.call(this, name, null, {
dir: true,
createFolders: createFolders
});
}
return this.files[name];
};
/**
* Generate a JSZip.CompressedObject for a given zipOject.
* @param {ZipObject} file the object to read.
* @param {JSZip.compression} compression the compression to use.
* @param {Object} compressionOptions the options to use when compressing.
* @return {JSZip.CompressedObject} the compressed result.
*/
var generateCompressedObjectFrom = function generateCompressedObjectFrom(file, compression, compressionOptions) {
var result = new CompressedObject(),
content; // the data has not been decompressed, we might reuse things !
if (file._data instanceof CompressedObject) {
result.uncompressedSize = file._data.uncompressedSize;
result.crc32 = file._data.crc32;
if (result.uncompressedSize === 0 || file.dir) {
compression = compressions['STORE'];
result.compressedContent = "";
result.crc32 = 0;
} else if (file._data.compressionMethod === compression.magic) {
result.compressedContent = file._data.getCompressedContent();
} else {
content = file._data.getContent(); // need to decompress / recompress
result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
}
} else {
// have uncompressed data
content = getBinaryData(file);
if (!content || content.length === 0 || file.dir) {
compression = compressions['STORE'];
content = "";
}
result.uncompressedSize = content.length;
result.crc32 = _crc(content);
result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
}
result.compressedSize = result.compressedContent.length;
result.compressionMethod = compression.magic;
return result;
};
/**
* Generate the UNIX part of the external file attributes.
* @param {Object} unixPermissions the unix permissions or null.
* @param {Boolean} isDir true if the entry is a directory, false otherwise.
* @return {Number} a 32 bit integer.
*
* adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
*
* TTTTsstrwxrwxrwx0000000000ADVSHR
* ^^^^____________________________ file type, see zipinfo.c (UNX_*)
* ^^^_________________________ setuid, setgid, sticky
* ^^^^^^^^^________________ permissions
* ^^^^^^^^^^______ not used ?
* ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
*/
var generateUnixExternalFileAttr = function generateUnixExternalFileAttr(unixPermissions, isDir) {
var result = unixPermissions;
if (!unixPermissions) {
// I can't use octal values in strict mode, hence the hexa.
// 040775 => 0x41fd
// 0100664 => 0x81b4
result = isDir ? 0x41fd : 0x81b4;
}
return (result & 0xFFFF) << 16;
};
/**
* Generate the DOS part of the external file attributes.
* @param {Object} dosPermissions the dos permissions or null.
* @param {Boolean} isDir true if the entry is a directory, false otherwise.
* @return {Number} a 32 bit integer.
*
* Bit 0 Read-Only
* Bit 1 Hidden
* Bit 2 System
* Bit 3 Volume Label
* Bit 4 Directory
* Bit 5 Archive
*/
var generateDosExternalFileAttr = function generateDosExternalFileAttr(dosPermissions, isDir) {
// the dir flag is already set for compatibility
return (dosPermissions || 0) & 0x3F;
};
/**
* Generate the various parts used in the construction of the final zip file.
* @param {string} name the file name.
* @param {ZipObject} file the file content.
* @param {JSZip.CompressedObject} compressedObject the compressed object.
* @param {number} offset the current offset from the start of the zip file.
* @param {String} platform let's pretend we are this platform (change platform dependents fields)
* @param {Function} encodeFileName the function to encode the file name / comment.
* @return {object} the zip parts.
*/
var generateZipParts = function generateZipParts(name, file, compressedObject, offset, platform, encodeFileName) {
var data = compressedObject.compressedContent,
useCustomEncoding = encodeFileName !== utf8.utf8encode,
encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
comment = file.comment || "",
encodedComment = utils.transformTo("string", encodeFileName(comment)),
utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
useUTF8ForComment = utfEncodedComment.length !== comment.length,
o = file.options,
dosTime,
dosDate,
extraFields = "",
unicodePathExtraField = "",
unicodeCommentExtraField = "",
dir,
date; // handle the deprecated options.dir
if (file._initialMetadata.dir !== file.dir) {
dir = file.dir;
} else {
dir = o.dir;
} // handle the deprecated options.date
if (file._initialMetadata.date !== file.date) {
date = file.date;
} else {
date = o.date;
}
var extFileAttr = 0;
var versionMadeBy = 0;
if (dir) {
// dos or unix, we set the dos dir flag
extFileAttr |= 0x00010;
}
if (platform === "UNIX") {
versionMadeBy = 0x031E; // UNIX, version 3.0
extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
} else {
// DOS or other, fallback to DOS
versionMadeBy = 0x0014; // DOS, version 2.0
extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
} // date
// @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
dosTime = date.getHours();
dosTime = dosTime << 6;
dosTime = dosTime | date.getMinutes();
dosTime = dosTime << 5;
dosTime = dosTime | date.getSeconds() / 2;
dosDate = date.getFullYear() - 1980;
dosDate = dosDate << 4;
dosDate = dosDate | date.getMonth() + 1;
dosDate = dosDate << 5;
dosDate = dosDate | date.getDate();
if (useUTF8ForFileName) {
// set the unicode path extra field. unzip needs at least one extra
// field to correctly handle unicode path, so using the path is as good
// as any other information. This could improve the situation with
// other archive managers too.
// This field is usually used without the utf8 flag, with a non
// unicode path in the header (winrar, winzip). This helps (a bit)
// with the messy Windows' default compressed folders feature but
// breaks on p7zip which doesn't seek the unicode path extra field.
// So for now, UTF-8 everywhere !
unicodePathExtraField = // Version
decToHex(1, 1) + // NameCRC32
decToHex(_crc(encodedFileName), 4) + // UnicodeName
utfEncodedFileName;
extraFields += // Info-ZIP Unicode Path Extra Field
"\x75\x70" + // size
decToHex(unicodePathExtraField.length, 2) + // content
unicodePathExtraField;
}
if (useUTF8ForComment) {
unicodeCommentExtraField = // Version
decToHex(1, 1) + // CommentCRC32
decToHex(this.crc32(encodedComment), 4) + // UnicodeName
utfEncodedComment;
extraFields += // Info-ZIP Unicode Path Extra Field
"\x75\x63" + // size
decToHex(unicodeCommentExtraField.length, 2) + // content
unicodeCommentExtraField;
}
var header = ""; // version needed to extract
header += "\x0A\x00"; // general purpose bit flag
// set bit 11 if utf8
header += !useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00"; // compression method
header += compressedObject.compressionMethod; // last mod file time
header += decToHex(dosTime, 2); // last mod file date
header += decToHex(dosDate, 2); // crc-32
header += decToHex(compressedObject.crc32, 4); // compressed size
header += decToHex(compressedObject.compressedSize, 4); // uncompressed size
header += decToHex(compressedObject.uncompressedSize, 4); // file name length
header += decToHex(encodedFileName.length, 2); // extra field length
header += decToHex(extraFields.length, 2);
var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
var dirRecord = signature.CENTRAL_FILE_HEADER + // version made by (00: DOS)
decToHex(versionMadeBy, 2) + // file header (common to file and central directory)
header + // file comment length
decToHex(encodedComment.length, 2) + // disk number start
"\x00\x00" + // internal file attributes TODO
"\x00\x00" + // external file attributes
decToHex(extFileAttr, 4) + // relative offset of local header
decToHex(offset, 4) + // file name
encodedFileName + // extra field
extraFields + // file comment
encodedComment;
return {
fileRecord: fileRecord,
dirRecord: dirRecord,
compressedObject: compressedObject
};
}; // return the actual prototype of JSZip
var out = {
/**
* Read an existing zip and merge the data in the current JSZip object.
* The implementation is in jszip-load.js, don't forget to include it.
* @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
* @param {Object} options Options for loading the stream.
* options.base64 : is the stream in base64 ? default : false
* @return {JSZip} the current JSZip object
*/
load: function load(stream, options) {
throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
},
/**
* Filter nested files/folders with the specified function.
* @param {Function} search the predicate to use :
* function (relativePath, file) {...}
* It takes 2 arguments : the relative path and the file.
* @return {Array} An array of matching elements.
*/
filter: function filter(search) {
var result = [],
filename,
relativePath,
file,
fileClone;
for (filename in this.files) {
if (!this.files.hasOwnProperty(filename)) {
continue;
}
file = this.files[filename]; // return a new object, don't let the user mess with our internal objects :)
fileClone = new ZipObject(file.name, file._data, utils.extend(file.options));
relativePath = filename.slice(this.root.length, filename.length);
if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
search(relativePath, fileClone)) {
// and the file matches the function
result.push(fileClone);
}
}
return result;
},
/**
* Add a file to the zip file, or search a file.
* @param {string|RegExp} name The name of the file to add (if data is defined),
* the name of the file to find (if no data) or a regex to match files.
* @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
* @param {Object} o File options
* @return {JSZip|Object|Array} this JSZip object (when adding a file),
* a file (when searching by string) or an array of files (when searching by regex).
*/
file: function file(name, data, o) {
if (arguments.length === 1) {
if (utils.isRegExp(name)) {
var regexp = name;
return this.filter(function (relativePath, file) {
return !file.dir && regexp.test(relativePath);
});
} else {
// text
return this.filter(function (relativePath, file) {
return !file.dir && relativePath === name;
})[0] || null;
}
} else {
// more than one argument : we have data !
name = this.root + name;
fileAdd.call(this, name, data, o);
}
return this;
},
/**
* Add a directory to the zip file, or search.
* @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
* @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
*/
folder: function folder(arg) {
if (!arg) {
return this;
}
if (utils.isRegExp(arg)) {
return this.filter(function (relativePath, file) {
return file.dir && arg.test(relativePath);
});
} // else, name is a new folder
var name = this.root + arg;
var newFolder = folderAdd.call(this, name); // Allow chaining by returning a new object with this folder as the root
var ret = this.clone();
ret.root = newFolder.name;
return ret;
},
/**
* Delete a file, or a directory and all sub-files, from the zip
* @param {string} name the name of the file to delete
* @return {JSZip} this JSZip object
*/
remove: function remove(name) {
name = this.root + name;
var file = this.files[name];
if (!file) {
// Look for any folders
if (name.slice(-1) != "/") {
name += "/";
}
file = this.files[name];
}
if (file && !file.dir) {
// file
delete this.files[name];
} else {
// maybe a folder, delete recursively
var kids = this.filter(function (relativePath, file) {
return file.name.slice(0, name.length) === name;
});
for (var i = 0; i < kids.length; i++) {
delete this.files[kids[i].name];
}
}
return this;
},
/**
* Generate the complete zip file
* @param {Object} options the options to generate the zip file :
* - base64, (deprecated, use type instead) true to generate base64.
* - compression, "STORE" by default.
* - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
* @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
*/
generate: function generate(options) {
options = utils.extend(options || {}, {
base64: true,
compression: "STORE",
compressionOptions: null,
type: "base64",
platform: "DOS",
comment: null,
mimeType: 'application/zip',
encodeFileName: utf8.utf8encode
});
utils.checkSupport(options.type); // accept nodejs `process.platform`
if (options.platform === 'darwin' || options.platform === 'freebsd' || options.platform === 'linux' || options.platform === 'sunos') {
options.platform = "UNIX";
}
if (options.platform === 'win32') {
options.platform = "DOS";
}
var zipData = [],
localDirLength = 0,
centralDirLength = 0,
writer,
i,
encodedComment = utils.transformTo("string", options.encodeFileName(options.comment || this.comment || "")); // first, generate all the zip parts.
for (var name in this.files) {
if (!this.files.hasOwnProperty(name)) {
continue;
}
var file = this.files[name];
var compressionName = file.options.compression || options.compression.toUpperCase();
var compression = compressions[compressionName];
if (!compression) {
throw new Error(compressionName + " is not a valid compression method !");
}
var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform, options.encodeFileName);
localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
centralDirLength += zipPart.dirRecord.length;
zipData.push(zipPart);
}
var dirEnd = ""; // end of central dir signature
dirEnd = signature.CENTRAL_DIRECTORY_END + // number of this disk
"\x00\x00" + // number of the disk with the start of the central directory
"\x00\x00" + // total number of entries in the central directory on this disk
decToHex(zipData.length, 2) + // total number of entries in the central directory
decToHex(zipData.length, 2) + // size of the central directory 4 bytes
decToHex(centralDirLength, 4) + // offset of start of central directory with respect to the starting disk number
decToHex(localDirLength, 4) + // .ZIP file comment length
decToHex(encodedComment.length, 2) + // .ZIP file comment
encodedComment; // we have all the parts (and the total length)
// time to create a writer !
var typeName = options.type.toLowerCase();
if (typeName === "uint8array" || typeName === "arraybuffer" || typeName === "blob" || typeName === "nodebuffer") {
writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
} else {
writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
}
for (i = 0; i < zipData.length; i++) {
writer.append(zipData[i].fileRecord);
writer.append(zipData[i].compressedObject.compressedContent);
}
for (i = 0; i < zipData.length; i++) {
writer.append(zipData[i].dirRecord);
}
writer.append(dirEnd);
var zip = writer.finalize();
switch (options.type.toLowerCase()) {
// case "zip is an Uint8Array"
case "uint8array":
case "arraybuffer":
case "nodebuffer":
return utils.transformTo(options.type.toLowerCase(), zip);
case "blob":
return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
// case "zip is a string"
case "base64":
return options.base64 ? base64.encode(zip) : zip;
default:
// case "string" :
return zip;
}
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
crc32: function crc32(input, crc) {
return _crc(input, crc);
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
utf8encode: function utf8encode(string) {
return utils.transformTo("string", utf8.utf8encode(string));
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
utf8decode: function utf8decode(input) {
return utf8.utf8decode(input);
}
};
module.exports = out;
/***/ }),
/* 22 */
/***/ (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 || new Function("return 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;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.STORE = {
magic: "\x00\x00",
compress: function compress(content, compressionOptions) {
return content; // no compression
},
uncompress: function uncompress(content) {
return content; // no compression
},
compressInputType: null,
uncompressInputType: null
};
exports.DEFLATE = __webpack_require__(95);
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
module.exports = {
2: 'need dictionary',
/* Z_NEED_DICT 2 */
1: 'stream end',
/* Z_STREAM_END 1 */
0: '',
/* Z_OK 0 */
'-1': 'file error',
/* Z_ERRNO (-1) */
'-2': 'stream error',
/* Z_STREAM_ERROR (-2) */
'-3': 'data error',
/* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory',
/* Z_MEM_ERROR (-4) */
'-5': 'buffer error',
/* Z_BUF_ERROR (-5) */
'-6': 'incompatible version'
/* Z_VERSION_ERROR (-6) */
};
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
module.exports = function (data, encoding) {
return new Buffer(data, encoding);
};
module.exports.test = function (b) {
return Buffer.isBuffer(b);
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(39).Buffer))
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const Heap = __webpack_require__(114);
function Cluster() {
this.children = [];
this.distance = -1;
this.index = [];
}
/**
* Creates an array of values where maximum distance smaller than the threshold
* @param {number} threshold
* @return {Array }
*/
Cluster.prototype.cut = function (threshold) {
if (threshold < 0) throw new RangeError('Threshold too small');
var root = new Cluster();
root.children = this.children;
root.distance = this.distance;
root.index = this.index;
var list = [root];
var ans = [];
while (list.length > 0) {
var aux = list.shift();
if (threshold >= aux.distance) {
ans.push(aux);
} else {
list = list.concat(aux.children);
}
}
return ans;
};
/**
* Merge the leaves in the minimum way to have 'minGroups' number of clusters
* @param {number} minGroups - Them minimum number of children the first level of the tree should have
* @return {Cluster}
*/
Cluster.prototype.group = function (minGroups) {
if (!Number.isInteger(minGroups) || minGroups < 1) throw new RangeError('Number of groups must be a positive integer');
const heap = new Heap(function (a, b) {
return b.distance - a.distance;
});
heap.push(this);
while (heap.size() < minGroups) {
var first = heap.pop();
if (first.children.length === 0) {
break;
}
first.children.forEach(child => heap.push(child));
}
var root = new Cluster();
root.children = heap.toArray();
root.distance = this.distance;
return root;
};
/**
* Traverses the tree depth-first and provide callback to be called on each individual node
* @param {function} cb - The callback to be called on each node encounter
* @type {Cluster}
*/
Cluster.prototype.traverse = function (cb) {
function visit(root, callback) {
callback(root);
if (root.children) {
for (var i = root.children.length - 1; i >= 0; i--) {
visit(root.children[i], callback);
}
}
}
visit(this, cb);
};
module.exports = Cluster;
/***/ }),
/* 27 */
/***/ (function(module, exports) {
module.exports = newArray;
function newArray(n, value) {
n = n || 0;
var array = new Array(n);
for (var i = 0; i < n; i++) {
array[i] = value;
}
return array;
}
/***/ }),
/* 28 */
/***/ (function(module, exports) {
module.exports = function (haystack, needle, comparator, low, high) {
var mid, cmp;
if (low === undefined) low = 0;else {
low = low | 0;
if (low < 0 || low >= haystack.length) throw new RangeError("invalid lower bound");
}
if (high === undefined) high = haystack.length - 1;else {
high = high | 0;
if (high < low || high >= haystack.length) throw new RangeError("invalid upper bound");
}
while (low <= high) {
/* Note that "(low + high) >>> 1" may overflow, and results in a typecast
* to double (which gives the wrong results). */
mid = low + (high - low >> 1);
cmp = +comparator(haystack[mid], needle, mid, haystack);
/* Too low. */
if (cmp < 0.0) low = mid + 1;
/* Too high. */
else if (cmp > 0.0) high = mid - 1;
/* Key found. */
else return mid;
}
/* Key not found. */
return ~low;
};
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = exports = __webpack_require__(60);
exports.getEquallySpacedData = __webpack_require__(62).getEquallySpacedData;
exports.SNV = __webpack_require__(63).SNV;
/***/ }),
/* 30 */
/***/ (function(module, exports) {
/**
* class encodes a integer vector as a String in order to store it in a text file.
* The algorithms used to encode the data are describe in:
* http://www.iupac.org/publications/pac/pdf/2001/pdf/7311x1765.pdf
* Created by acastillo on 3/2/16.
*/
const newLine = '\r\n';
const pseudoDigits = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], ['@', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], ['%', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R'], ['%', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'], [' ', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 's']];
const SQZ_P = 1;
const SQZ_N = 2;
const DIF_P = 3;
const DIF_N = 4;
const DUP = 5;
const MaxLinelength = 100;
/**
* This function encodes the given vector. The encoding format is specified by the
* encoding option
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @param {string} encoding: ('FIX','SQZ','DIF','DIFDUP','CVS','PAC') Default 'DIFDUP'
* @return {string}
*/
function encode(data, firstX, intervalX, encoding) {
switch (encoding) {
case 'FIX':
return fixEncoding(data, firstX, intervalX);
case 'SQZ':
return squeezedEncoding(data, firstX, intervalX);
case 'DIF':
return differenceEncoding(data, firstX, intervalX);
case 'DIFDUP':
return differenceDuplicateEncoding(data, firstX, intervalX);
case 'CSV':
return commaSeparatedValuesEncoding(data, firstX, intervalX);
case 'PAC':
return packedEncoding(data, firstX, intervalX);
default:
return differenceEncoding(data, firstX, intervalX);
}
}
/**
* @private
* No data compression used. The data is separated by a comma(',').
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @return {string}
*/
function commaSeparatedValuesEncoding(data, firstX, intervalX) {
return fixEncoding(data, firstX, intervalX, ',');
}
/**
* @private
* No data compression used. The data is separated by the specified separator.
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @param {string} separator, The separator character
* @return {string}
*/
function fixEncoding(data, firstX, intervalX, separator) {
if (!separator) {
separator = ' ';
}
var outputData = '';
var j = 0;
var TD = data.length;
var i;
while (j < TD - 7) {
outputData += Math.ceil(firstX + j * intervalX);
for (i = 0; i < 8; i++) {
outputData += separator + data[j++];
}
outputData += newLine;
}
if (j < TD) {
// We add last numbers
outputData += Math.ceil(firstX + j * intervalX);
for (i = j; i < TD; i++) {
outputData += separator + data[i];
}
}
return outputData;
}
/**
* @private
* No data compression used. The data is separated by the sign of the number.
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @return {string}
*/
function packedEncoding(data, firstX, intervalX) {
var outputData = '';
var j = 0;
var TD = data.length;
var i;
while (j < TD - 7) {
outputData += Math.ceil(firstX + j * intervalX);
for (i = 0; i < 8; i++) {
if (data[j] < 0) {
outputData += `-${data[j++]}`;
} else {
outputData += `+${data[j++]}`;
}
}
outputData += newLine;
}
if (j < TD) {
// We add last numbers
outputData += Math.ceil(firstX + j * intervalX);
for (i = j; i < TD; i++) {
if (data[i] < 0) {
outputData += `-${data[i]}`;
} else {
outputData += `+${data[i]}`;
}
}
}
return outputData;
}
/**
* @private
* Data compression is possible using the squeezed form (SQZ) in which the delimiter, the leading digit,
* and sign are replaced by a pseudo-digit from Table 1. For example, the Y-values 30, 32 would be
* represented as C0C2.
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @return {string}
*/
function squeezedEncoding(data, firstX, intervalX) {
var outputData = ''; // String outputData = new String();
var j = 0;
var TD = data.length;
var i;
while (j < TD - 10) {
outputData += Math.ceil(firstX + j * intervalX);
for (i = 0; i < 10; i++) {
outputData += squeezedDigit(data[j++].toString());
}
outputData += newLine;
}
if (j < TD) {
// We add last numbers
outputData += Math.ceil(firstX + j * intervalX);
for (i = j; i < TD; i++) {
outputData += squeezedDigit(data[i].toString());
}
}
return outputData;
}
/**
* @private
* Duplicate suppression encoding
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @return {string}
*/
function differenceDuplicateEncoding(data, firstX, intervalX) {
var mult = 0;
var index = 0;
var charCount = 0;
var i; // We built a string where we store the encoded data.
var encodData = '';
var encodNumber = '';
var temp = ''; // We calculate the differences vector
var diffData = new Array(data.length - 1);
for (i = 0; i < diffData.length; i++) {
diffData[i] = data[i + 1] - data[i];
} // We simulate a line carry
var numDiff = diffData.length;
while (index < numDiff) {
if (charCount === 0) {
// Start line
encodNumber = Math.ceil(firstX + index * intervalX) + squeezedDigit(data[index].toString()) + differenceDigit(diffData[index].toString());
encodData += encodNumber;
charCount += encodNumber.length;
} else {
// Try to insert next difference
if (diffData[index - 1] === diffData[index]) {
mult++;
} else {
if (mult > 0) {
// Now we know that it can be in line
mult++;
encodNumber = duplicateDigit(mult.toString());
encodData += encodNumber;
charCount += encodNumber.length;
mult = 0;
index--;
} else {
// Mirar si cabe, en caso contrario iniciar una nueva linea
encodNumber = differenceDigit(diffData[index].toString());
if (encodNumber.length + charCount < MaxLinelength) {
encodData += encodNumber;
charCount += encodNumber.length;
} else {
// Iniciar nueva linea
encodData += newLine;
temp = Math.ceil(firstX + index * intervalX) + squeezedDigit(data[index].toString()) + encodNumber;
encodData += temp; // Each line start with first index number.
charCount = temp.length;
}
}
}
}
index++;
}
if (mult > 0) {
encodData += duplicateDigit((mult + 1).toString());
} // We insert the last data from fid. It is done to control of data
// The last line start with the number of datas in the fid.
encodData += newLine + Math.ceil(firstX + index * intervalX) + squeezedDigit(data[index].toString());
return encodData;
}
/**
* @private
* Differential encoding
* @param {Array} data
* @param {number} firstX
* @param {number} intervalX
* @return {string}
*/
function differenceEncoding(data, firstX, intervalX) {
var index = 0;
var charCount = 0;
var i;
var encodData = '';
var encodNumber = '';
var temp = ''; // We calculate the differences vector
var diffData = new Array(data.length - 1);
for (i = 0; i < diffData.length; i++) {
diffData[i] = data[i + 1] - data[i];
}
var numDiff = diffData.length;
while (index < numDiff) {
if (charCount === 0) {
// We convert the first number.
encodNumber = Math.ceil(firstX + index * intervalX) + squeezedDigit(data[index].toString()) + differenceDigit(diffData[index].toString());
encodData += encodNumber;
charCount += encodNumber.length;
} else {
encodNumber = differenceDigit(diffData[index].toString());
if (encodNumber.length + charCount < MaxLinelength) {
encodData += encodNumber;
charCount += encodNumber.length;
} else {
encodData += newLine;
temp = Math.ceil(firstX + index * intervalX) + squeezedDigit(data[index].toString()) + encodNumber;
encodData += temp; // Each line start with first index number.
charCount = temp.length;
}
}
index++;
} // We insert the last number from data. It is done to control of data
encodData += newLine + Math.ceil(firstX + index * intervalX) + squeezedDigit(data[index].toString());
return encodData;
}
/**
* @private
* Convert number to the ZQZ format, using pseudo digits.
* @param {number} num
* @return {string}
*/
function squeezedDigit(num) {
var SQZdigit = '';
if (num.charAt(0) === '-') {
SQZdigit += pseudoDigits[SQZ_N][num.charAt(1)];
if (num.length > 2) {
SQZdigit += num.substring(2);
}
} else {
SQZdigit += pseudoDigits[SQZ_P][num.charAt(0)];
if (num.length > 1) {
SQZdigit += num.substring(1);
}
}
return SQZdigit;
}
/**
* @private
* Convert number to the DIF format, using pseudo digits.
* @param {number} num
* @return {string}
*/
function differenceDigit(num) {
var DIFFdigit = '';
if (num.charAt(0) === '-') {
DIFFdigit += pseudoDigits[DIF_N][num.charAt(1)];
if (num.length > 2) {
DIFFdigit += num.substring(2);
}
} else {
DIFFdigit += pseudoDigits[DIF_P][num.charAt(0)];
if (num.length > 1) {
DIFFdigit += num.substring(1);
}
}
return DIFFdigit;
}
/**
* @private
* Convert number to the DUP format, using pseudo digits.
* @param {number} num
* @return {string}
*/
function duplicateDigit(num) {
var DUPdigit = '';
DUPdigit += pseudoDigits[DUP][num.charAt(0)];
if (num.length > 1) {
DUPdigit += num.substring(1);
}
return DUPdigit;
}
module.exports = {
encode,
fixEncoding,
commaSeparatedValuesEncoding,
packedEncoding,
squeezedEncoding,
differenceDuplicateEncoding,
differenceEncoding
};
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function compareNumbers(a, b) {
return a - b;
}
/**
* Computes the sum of the given values
* @param {Array} values
* @returns {number}
*/
exports.sum = function sum(values) {
var sum = 0;
for (var i = 0; i < values.length; i++) {
sum += values[i];
}
return sum;
};
/**
* Computes the maximum of the given values
* @param {Array} values
* @returns {number}
*/
exports.max = function max(values) {
var max = values[0];
var l = values.length;
for (var i = 1; i < l; i++) {
if (values[i] > max) max = values[i];
}
return max;
};
/**
* Computes the minimum of the given values
* @param {Array} values
* @returns {number}
*/
exports.min = function min(values) {
var min = values[0];
var l = values.length;
for (var i = 1; i < l; i++) {
if (values[i] < min) min = values[i];
}
return min;
};
/**
* Computes the min and max of the given values
* @param {Array} values
* @returns {{min: number, max: number}}
*/
exports.minMax = function minMax(values) {
var min = values[0];
var max = values[0];
var l = values.length;
for (var i = 1; i < l; i++) {
if (values[i] < min) min = values[i];
if (values[i] > max) max = values[i];
}
return {
min: min,
max: max
};
};
/**
* Computes the arithmetic mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.arithmeticMean = function arithmeticMean(values) {
var sum = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
sum += values[i];
}
return sum / l;
};
/**
* {@link arithmeticMean}
*/
exports.mean = exports.arithmeticMean;
/**
* Computes the geometric mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.geometricMean = function geometricMean(values) {
var mul = 1;
var l = values.length;
for (var i = 0; i < l; i++) {
mul *= values[i];
}
return Math.pow(mul, 1 / l);
};
/**
* Computes the mean of the log of the given values
* If the return value is exponentiated, it gives the same result as the
* geometric mean.
* @param {Array} values
* @returns {number}
*/
exports.logMean = function logMean(values) {
var lnsum = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
lnsum += Math.log(values[i]);
}
return lnsum / l;
};
/**
* Computes the weighted grand mean for a list of means and sample sizes
* @param {Array} means - Mean values for each set of samples
* @param {Array} samples - Number of original values for each set of samples
* @returns {number}
*/
exports.grandMean = function grandMean(means, samples) {
var sum = 0;
var n = 0;
var l = means.length;
for (var i = 0; i < l; i++) {
sum += samples[i] * means[i];
n += samples[i];
}
return sum / n;
};
/**
* Computes the truncated mean of the given values using a given percentage
* @param {Array} values
* @param {number} percent - The percentage of values to keep (range: [0,1])
* @param {boolean} [alreadySorted=false]
* @returns {number}
*/
exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {
if (alreadySorted === undefined) alreadySorted = false;
if (!alreadySorted) {
values = [].concat(values).sort(compareNumbers);
}
var l = values.length;
var k = Math.floor(l * percent);
var sum = 0;
for (var i = k; i < l - k; i++) {
sum += values[i];
}
return sum / (l - 2 * k);
};
/**
* Computes the harmonic mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.harmonicMean = function harmonicMean(values) {
var sum = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
if (values[i] === 0) {
throw new RangeError('value at index ' + i + 'is zero');
}
sum += 1 / values[i];
}
return l / sum;
};
/**
* Computes the contraharmonic mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.contraHarmonicMean = function contraHarmonicMean(values) {
var r1 = 0;
var r2 = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
r1 += values[i] * values[i];
r2 += values[i];
}
if (r2 < 0) {
throw new RangeError('sum of values is negative');
}
return r1 / r2;
};
/**
* Computes the median of the given values
* @param {Array} values
* @param {boolean} [alreadySorted=false]
* @returns {number}
*/
exports.median = function median(values, alreadySorted) {
if (alreadySorted === undefined) alreadySorted = false;
if (!alreadySorted) {
values = [].concat(values).sort(compareNumbers);
}
var l = values.length;
var half = Math.floor(l / 2);
if (l % 2 === 0) {
return (values[half - 1] + values[half]) * 0.5;
} else {
return values[half];
}
};
/**
* Computes the variance of the given values
* @param {Array} values
* @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
* @returns {number}
*/
exports.variance = function variance(values, unbiased) {
if (unbiased === undefined) unbiased = true;
var theMean = exports.mean(values);
var theVariance = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
var x = values[i] - theMean;
theVariance += x * x;
}
if (unbiased) {
return theVariance / (l - 1);
} else {
return theVariance / l;
}
};
/**
* Computes the standard deviation of the given values
* @param {Array} values
* @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
* @returns {number}
*/
exports.standardDeviation = function standardDeviation(values, unbiased) {
return Math.sqrt(exports.variance(values, unbiased));
};
exports.standardError = function standardError(values) {
return exports.standardDeviation(values) / Math.sqrt(values.length);
};
/**
* IEEE Transactions on biomedical engineering, vol. 52, no. 1, january 2005, p. 76-
* Calculate the standard deviation via the Median of the absolute deviation
* The formula for the standard deviation only holds for Gaussian random variables.
* @returns {{mean: number, stdev: number}}
*/
exports.robustMeanAndStdev = function robustMeanAndStdev(y) {
var mean = 0,
stdev = 0;
var length = y.length,
i = 0;
for (i = 0; i < length; i++) {
mean += y[i];
}
mean /= length;
var averageDeviations = new Array(length);
for (i = 0; i < length; i++) averageDeviations[i] = Math.abs(y[i] - mean);
averageDeviations.sort(compareNumbers);
if (length % 2 === 1) {
stdev = averageDeviations[(length - 1) / 2] / 0.6745;
} else {
stdev = 0.5 * (averageDeviations[length / 2] + averageDeviations[length / 2 - 1]) / 0.6745;
}
return {
mean: mean,
stdev: stdev
};
};
exports.quartiles = function quartiles(values, alreadySorted) {
if (typeof alreadySorted === 'undefined') alreadySorted = false;
if (!alreadySorted) {
values = [].concat(values).sort(compareNumbers);
}
var quart = values.length / 4;
var q1 = values[Math.ceil(quart) - 1];
var q2 = exports.median(values, true);
var q3 = values[Math.ceil(quart * 3) - 1];
return {
q1: q1,
q2: q2,
q3: q3
};
};
exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {
return Math.sqrt(exports.pooledVariance(samples, unbiased));
};
exports.pooledVariance = function pooledVariance(samples, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var sum = 0;
var length = 0,
l = samples.length;
for (var i = 0; i < l; i++) {
var values = samples[i];
var vari = exports.variance(values);
sum += (values.length - 1) * vari;
if (unbiased) length += values.length - 1;else length += values.length;
}
return sum / length;
};
exports.mode = function mode(values) {
var l = values.length,
itemCount = new Array(l),
i;
for (i = 0; i < l; i++) {
itemCount[i] = 0;
}
var itemArray = new Array(l);
var count = 0;
for (i = 0; i < l; i++) {
var index = itemArray.indexOf(values[i]);
if (index >= 0) itemCount[index]++;else {
itemArray[count] = values[i];
itemCount[count] = 1;
count++;
}
}
var maxValue = 0,
maxIndex = 0;
for (i = 0; i < count; i++) {
if (itemCount[i] > maxValue) {
maxValue = itemCount[i];
maxIndex = i;
}
}
return itemArray[maxIndex];
};
exports.covariance = function covariance(vector1, vector2, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var mean1 = exports.mean(vector1);
var mean2 = exports.mean(vector2);
if (vector1.length !== vector2.length) throw 'Vectors do not have the same dimensions';
var cov = 0,
l = vector1.length;
for (var i = 0; i < l; i++) {
var x = vector1[i] - mean1;
var y = vector2[i] - mean2;
cov += x * y;
}
if (unbiased) return cov / (l - 1);else return cov / l;
};
exports.skewness = function skewness(values, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var theMean = exports.mean(values);
var s2 = 0,
s3 = 0,
l = values.length;
for (var i = 0; i < l; i++) {
var dev = values[i] - theMean;
s2 += dev * dev;
s3 += dev * dev * dev;
}
var m2 = s2 / l;
var m3 = s3 / l;
var g = m3 / Math.pow(m2, 3 / 2.0);
if (unbiased) {
var a = Math.sqrt(l * (l - 1));
var b = l - 2;
return a / b * g;
} else {
return g;
}
};
exports.kurtosis = function kurtosis(values, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var theMean = exports.mean(values);
var n = values.length,
s2 = 0,
s4 = 0;
for (var i = 0; i < n; i++) {
var dev = values[i] - theMean;
s2 += dev * dev;
s4 += dev * dev * dev * dev;
}
var m2 = s2 / n;
var m4 = s4 / n;
if (unbiased) {
var v = s2 / (n - 1);
var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3));
var b = s4 / (v * v);
var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3));
return a * b - 3 * c;
} else {
return m4 / (m2 * m2) - 3;
}
};
exports.entropy = function entropy(values, eps) {
if (typeof eps === 'undefined') eps = 0;
var sum = 0,
l = values.length;
for (var i = 0; i < l; i++) sum += values[i] * Math.log(values[i] + eps);
return -sum;
};
exports.weightedMean = function weightedMean(values, weights) {
var sum = 0,
l = values.length;
for (var i = 0; i < l; i++) sum += values[i] * weights[i];
return sum;
};
exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {
return Math.sqrt(exports.weightedVariance(values, weights));
};
exports.weightedVariance = function weightedVariance(values, weights) {
var theMean = exports.weightedMean(values, weights);
var vari = 0,
l = values.length;
var a = 0,
b = 0;
for (var i = 0; i < l; i++) {
var z = values[i] - theMean;
var w = weights[i];
vari += w * (z * z);
b += w;
a += w * w;
}
return vari * (b / (b * b - a));
};
exports.center = function center(values, inPlace) {
if (typeof inPlace === 'undefined') inPlace = false;
var result = values;
if (!inPlace) result = [].concat(values);
var theMean = exports.mean(result),
l = result.length;
for (var i = 0; i < l; i++) result[i] -= theMean;
};
exports.standardize = function standardize(values, standardDev, inPlace) {
if (typeof standardDev === 'undefined') standardDev = exports.standardDeviation(values);
if (typeof inPlace === 'undefined') inPlace = false;
var l = values.length;
var result = inPlace ? values : new Array(l);
for (var i = 0; i < l; i++) result[i] = values[i] / standardDev;
return result;
};
exports.cumulativeSum = function cumulativeSum(array) {
var l = array.length;
var result = new Array(l);
result[0] = array[0];
for (var i = 1; i < l; i++) result[i] = result[i - 1] + array[i];
return result;
};
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
} // Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {
/**/
}
return typeof key === 'undefined' || hasOwn.call(obj, key);
};
module.exports = function extend() {
var options,
name,
src,
copy,
copyIsArray,
clone,
target = arguments[0],
i = 1,
length = arguments.length,
deep = false; // Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {}; // skip the boolean and the target
i = 2;
} else if (typeof target !== 'object' && typeof target !== 'function' || target == null) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i]; // Only deal with non-null/undefined values
if (options != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name]; // Prevent never-ending loop
if (target !== copy) {
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
} // Never move original objects, clone them
target[name] = extend(deep, clone, copy); // Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
target[name] = copy;
}
}
}
}
} // Return the modified object
return target;
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function compareNumbers(a, b) {
return a - b;
}
/**
* Computes the sum of the given values
* @param {Array} values
* @returns {number}
*/
exports.sum = function sum(values) {
var sum = 0;
for (var i = 0; i < values.length; i++) {
sum += values[i];
}
return sum;
};
/**
* Computes the maximum of the given values
* @param {Array} values
* @returns {number}
*/
exports.max = function max(values) {
var max = -Infinity;
var l = values.length;
for (var i = 0; i < l; i++) {
if (values[i] > max) max = values[i];
}
return max;
};
/**
* Computes the minimum of the given values
* @param {Array} values
* @returns {number}
*/
exports.min = function min(values) {
var min = Infinity;
var l = values.length;
for (var i = 0; i < l; i++) {
if (values[i] < min) min = values[i];
}
return min;
};
/**
* Computes the min and max of the given values
* @param {Array} values
* @returns {{min: number, max: number}}
*/
exports.minMax = function minMax(values) {
var min = Infinity;
var max = -Infinity;
var l = values.length;
for (var i = 0; i < l; i++) {
if (values[i] < min) min = values[i];
if (values[i] > max) max = values[i];
}
return {
min: min,
max: max
};
};
/**
* Computes the arithmetic mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.arithmeticMean = function arithmeticMean(values) {
var sum = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
sum += values[i];
}
return sum / l;
};
/**
* {@link arithmeticMean}
*/
exports.mean = exports.arithmeticMean;
/**
* Computes the geometric mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.geometricMean = function geometricMean(values) {
var mul = 1;
var l = values.length;
for (var i = 0; i < l; i++) {
mul *= values[i];
}
return Math.pow(mul, 1 / l);
};
/**
* Computes the mean of the log of the given values
* If the return value is exponentiated, it gives the same result as the
* geometric mean.
* @param {Array} values
* @returns {number}
*/
exports.logMean = function logMean(values) {
var lnsum = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
lnsum += Math.log(values[i]);
}
return lnsum / l;
};
/**
* Computes the weighted grand mean for a list of means and sample sizes
* @param {Array} means - Mean values for each set of samples
* @param {Array} samples - Number of original values for each set of samples
* @returns {number}
*/
exports.grandMean = function grandMean(means, samples) {
var sum = 0;
var n = 0;
var l = means.length;
for (var i = 0; i < l; i++) {
sum += samples[i] * means[i];
n += samples[i];
}
return sum / n;
};
/**
* Computes the truncated mean of the given values using a given percentage
* @param {Array} values
* @param {number} percent - The percentage of values to keep (range: [0,1])
* @param {boolean} [alreadySorted=false]
* @returns {number}
*/
exports.truncatedMean = function truncatedMean(values, percent, alreadySorted) {
if (alreadySorted === undefined) alreadySorted = false;
if (!alreadySorted) {
values = values.slice().sort(compareNumbers);
}
var l = values.length;
var k = Math.floor(l * percent);
var sum = 0;
for (var i = k; i < l - k; i++) {
sum += values[i];
}
return sum / (l - 2 * k);
};
/**
* Computes the harmonic mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.harmonicMean = function harmonicMean(values) {
var sum = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
if (values[i] === 0) {
throw new RangeError('value at index ' + i + 'is zero');
}
sum += 1 / values[i];
}
return l / sum;
};
/**
* Computes the contraharmonic mean of the given values
* @param {Array} values
* @returns {number}
*/
exports.contraHarmonicMean = function contraHarmonicMean(values) {
var r1 = 0;
var r2 = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
r1 += values[i] * values[i];
r2 += values[i];
}
if (r2 < 0) {
throw new RangeError('sum of values is negative');
}
return r1 / r2;
};
/**
* Computes the median of the given values
* @param {Array} values
* @param {boolean} [alreadySorted=false]
* @returns {number}
*/
exports.median = function median(values, alreadySorted) {
if (alreadySorted === undefined) alreadySorted = false;
if (!alreadySorted) {
values = values.slice().sort(compareNumbers);
}
var l = values.length;
var half = Math.floor(l / 2);
if (l % 2 === 0) {
return (values[half - 1] + values[half]) * 0.5;
} else {
return values[half];
}
};
/**
* Computes the variance of the given values
* @param {Array} values
* @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
* @returns {number}
*/
exports.variance = function variance(values, unbiased) {
if (unbiased === undefined) unbiased = true;
var theMean = exports.mean(values);
var theVariance = 0;
var l = values.length;
for (var i = 0; i < l; i++) {
var x = values[i] - theMean;
theVariance += x * x;
}
if (unbiased) {
return theVariance / (l - 1);
} else {
return theVariance / l;
}
};
/**
* Computes the standard deviation of the given values
* @param {Array} values
* @param {boolean} [unbiased=true] - if true, divide by (n-1); if false, divide by n.
* @returns {number}
*/
exports.standardDeviation = function standardDeviation(values, unbiased) {
return Math.sqrt(exports.variance(values, unbiased));
};
exports.standardError = function standardError(values) {
return exports.standardDeviation(values) / Math.sqrt(values.length);
};
exports.quartiles = function quartiles(values, alreadySorted) {
if (typeof alreadySorted === 'undefined') alreadySorted = false;
if (!alreadySorted) {
values = values.slice();
values.sort(compareNumbers);
}
var quart = values.length / 4;
var q1 = values[Math.ceil(quart) - 1];
var q2 = exports.median(values, true);
var q3 = values[Math.ceil(quart * 3) - 1];
return {
q1: q1,
q2: q2,
q3: q3
};
};
exports.pooledStandardDeviation = function pooledStandardDeviation(samples, unbiased) {
return Math.sqrt(exports.pooledVariance(samples, unbiased));
};
exports.pooledVariance = function pooledVariance(samples, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var sum = 0;
var length = 0,
l = samples.length;
for (var i = 0; i < l; i++) {
var values = samples[i];
var vari = exports.variance(values);
sum += (values.length - 1) * vari;
if (unbiased) length += values.length - 1;else length += values.length;
}
return sum / length;
};
exports.mode = function mode(values) {
var l = values.length,
itemCount = new Array(l),
i;
for (i = 0; i < l; i++) {
itemCount[i] = 0;
}
var itemArray = new Array(l);
var count = 0;
for (i = 0; i < l; i++) {
var index = itemArray.indexOf(values[i]);
if (index >= 0) itemCount[index]++;else {
itemArray[count] = values[i];
itemCount[count] = 1;
count++;
}
}
var maxValue = 0,
maxIndex = 0;
for (i = 0; i < count; i++) {
if (itemCount[i] > maxValue) {
maxValue = itemCount[i];
maxIndex = i;
}
}
return itemArray[maxIndex];
};
exports.covariance = function covariance(vector1, vector2, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var mean1 = exports.mean(vector1);
var mean2 = exports.mean(vector2);
if (vector1.length !== vector2.length) throw "Vectors do not have the same dimensions";
var cov = 0,
l = vector1.length;
for (var i = 0; i < l; i++) {
var x = vector1[i] - mean1;
var y = vector2[i] - mean2;
cov += x * y;
}
if (unbiased) return cov / (l - 1);else return cov / l;
};
exports.skewness = function skewness(values, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var theMean = exports.mean(values);
var s2 = 0,
s3 = 0,
l = values.length;
for (var i = 0; i < l; i++) {
var dev = values[i] - theMean;
s2 += dev * dev;
s3 += dev * dev * dev;
}
var m2 = s2 / l;
var m3 = s3 / l;
var g = m3 / Math.pow(m2, 3 / 2.0);
if (unbiased) {
var a = Math.sqrt(l * (l - 1));
var b = l - 2;
return a / b * g;
} else {
return g;
}
};
exports.kurtosis = function kurtosis(values, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var theMean = exports.mean(values);
var n = values.length,
s2 = 0,
s4 = 0;
for (var i = 0; i < n; i++) {
var dev = values[i] - theMean;
s2 += dev * dev;
s4 += dev * dev * dev * dev;
}
var m2 = s2 / n;
var m4 = s4 / n;
if (unbiased) {
var v = s2 / (n - 1);
var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3));
var b = s4 / (v * v);
var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3));
return a * b - 3 * c;
} else {
return m4 / (m2 * m2) - 3;
}
};
exports.entropy = function entropy(values, eps) {
if (typeof eps === 'undefined') eps = 0;
var sum = 0,
l = values.length;
for (var i = 0; i < l; i++) sum += values[i] * Math.log(values[i] + eps);
return -sum;
};
exports.weightedMean = function weightedMean(values, weights) {
var sum = 0,
l = values.length;
for (var i = 0; i < l; i++) sum += values[i] * weights[i];
return sum;
};
exports.weightedStandardDeviation = function weightedStandardDeviation(values, weights) {
return Math.sqrt(exports.weightedVariance(values, weights));
};
exports.weightedVariance = function weightedVariance(values, weights) {
var theMean = exports.weightedMean(values, weights);
var vari = 0,
l = values.length;
var a = 0,
b = 0;
for (var i = 0; i < l; i++) {
var z = values[i] - theMean;
var w = weights[i];
vari += w * (z * z);
b += w;
a += w * w;
}
return vari * (b / (b * b - a));
};
exports.center = function center(values, inPlace) {
if (typeof inPlace === 'undefined') inPlace = false;
var result = values;
if (!inPlace) result = values.slice();
var theMean = exports.mean(result),
l = result.length;
for (var i = 0; i < l; i++) result[i] -= theMean;
};
exports.standardize = function standardize(values, standardDev, inPlace) {
if (typeof standardDev === 'undefined') standardDev = exports.standardDeviation(values);
if (typeof inPlace === 'undefined') inPlace = false;
var l = values.length;
var result = inPlace ? values : new Array(l);
for (var i = 0; i < l; i++) result[i] = values[i] / standardDev;
return result;
};
exports.cumulativeSum = function cumulativeSum(array) {
var l = array.length;
var result = new Array(l);
result[0] = array[0];
for (var i = 1; i < l; i++) result[i] = result[i - 1] + array[i];
return result;
};
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var LM = __webpack_require__(70);
var math = LM.Matrix.algebra;
var Matrix = __webpack_require__(0);
/**
* This function calculates the spectrum as a sum of lorentzian functions. The Lorentzian
* parameters are divided in 3 batches. 1st: centers; 2nd: heights; 3th: widths;
* @param t Ordinate values
* @param p Lorentzian parameters
* @param c Constant parameters(Not used)
* @returns {*}
*/
function sumOfLorentzians(t, p, c) {
var nL = p.length / 3,
factor,
i,
j,
p2,
cols = t.rows;
var result = Matrix.zeros(t.length, 1);
for (i = 0; i < nL; i++) {
p2 = Math.pow(p[i + nL * 2][0] / 2, 2);
factor = p[i + nL][0] * p2;
for (j = 0; j < cols; j++) {
result[j][0] += factor / (Math.pow(t[j][0] - p[i][0], 2) + p2);
}
}
return result;
}
/**
* This function calculates the spectrum as a sum of gaussian functions. The Gaussian
* parameters are divided in 3 batches. 1st: centers; 2nd: height; 3th: std's;
* @param t Ordinate values
* @param p Gaussian parameters
* @param c Constant parameters(Not used)
* @returns {*}
*/
function sumOfGaussians(t, p, c) {
var nL = p.length / 3,
factor,
i,
j,
cols = t.rows;
var result = Matrix.zeros(t.length, 1);
for (i = 0; i < nL; i++) {
factor = p[i + nL * 2][0] * p[i + nL * 2][0] / 2;
for (j = 0; j < cols; j++) {
result[j][0] += p[i + nL][0] * Math.exp(-(t[i][0] - p[i][0]) * (t[i][0] - p[i][0]) / factor);
}
}
return result;
}
/**
* Single 4 parameter lorentzian function
* @param t Ordinate values
* @param p Lorentzian parameters
* @param c Constant parameters(Not used)
* @returns {*}
*/
function singleLorentzian(t, p, c) {
var factor = p[1][0] * Math.pow(p[2][0] / 2, 2);
var rows = t.rows;
var result = new Matrix(t.rows, t.columns);
for (var i = 0; i < rows; i++) {
result[i][0] = factor / (Math.pow(t[i][0] - p[0][0], 2) + Math.pow(p[2][0] / 2, 2));
}
return result;
}
/**
* Single 3 parameter gaussian function
* @param t Ordinate values
* @param p Gaussian parameters [mean, height, std]
* @param c Constant parameters(Not used)
* @returns {*}
*/
function singleGaussian(t, p, c) {
var factor2 = p[2][0] * p[2][0] / 2;
var rows = t.rows;
var result = new Matrix(t.rows, t.columns);
for (var i = 0; i < rows; i++) {
result[i][0] = p[1][0] * Math.exp(-(t[i][0] - p[0][0]) * (t[i][0] - p[0][0]) / factor2);
}
return result;
}
/**
* * Fits a set of points to a Lorentzian function. Returns the center of the peak, the width at half height, and the height of the signal.
* @param data,[y]
* @returns {*[]}
*/
function optimizeSingleLorentzian(xy, peak, opts) {
opts = opts || {};
var xy2 = parseData(xy, opts.percentage || 0);
if (xy2 === null || xy2[0].rows < 3) {
return null; //Cannot run an optimization with less than 3 points
}
var t = xy2[0];
var y_data = xy2[1];
var maxY = xy2[2];
var nbPoints = t.rows,
i;
var weight = [nbPoints / Math.sqrt(y_data.dot(y_data))];
var opts = Object.create(opts.LMOptions || [3, 100, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1]); //var opts = [ 3, 100, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1 ];
var consts = [];
var dt = Math.abs(t[0][0] - t[1][0]); // optional vector of constants
var dx = new Matrix([[-dt / 10000], [-1e-3], [-dt / 10000]]); //-Math.abs(t[0][0]-t[1][0])/100;
var p_init = new Matrix([[peak.x], [1], [peak.width]]);
var p_min = new Matrix([[peak.x - dt], [0.75], [peak.width / 4]]);
var p_max = new Matrix([[peak.x + dt], [1.25], [peak.width * 4]]);
var p_fit = LM.optimize(singleLorentzian, p_init, t, y_data, weight, dx, p_min, p_max, consts, opts);
p_fit = p_fit.p;
return [p_fit[0], [p_fit[1][0] * maxY], p_fit[2]];
}
/**
* Fits a set of points to a gaussian bell. Returns the mean of the peak, the std and the height of the signal.
* @param data,[y]
* @returns {*[]}
*/
function optimizeSingleGaussian(xy, peak, opts) {
opts = opts || {};
var xy2 = parseData(xy, opts.percentage || 0);
if (xy2 === null || xy2[0].rows < 3) {
return null; //Cannot run an optimization with less than 3 points
}
var t = xy2[0];
var y_data = xy2[1];
var maxY = xy2[2];
var nbPoints = t.rows,
i;
var weight = [nbPoints / Math.sqrt(y_data.dot(y_data))];
var opts = Object.create(opts.LMOptions || [3, 100, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1]); //var opts = [ 3, 100, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1 ];
var consts = []; // optional vector of constants
var dt = Math.abs(t[0][0] - t[1][0]);
var dx = new Matrix([[-dt / 10000], [-1e-3], [-dt / 10000]]); //-Math.abs(t[0][0]-t[1][0])/100;
var dx = new Matrix([[-Math.abs(t[0][0] - t[1][0]) / 1000], [-1e-3], [-peak.width / 1000]]);
var p_init = new Matrix([[peak.x], [1], [peak.width]]);
var p_min = new Matrix([[peak.x - dt], [0.75], [peak.width / 4]]);
var p_max = new Matrix([[peak.x + dt], [1.25], [peak.width * 4]]); //var p_min = new Matrix([[peak.x-peak.width/4],[0.75],[peak.width/3]]);
//var p_max = new Matrix([[peak.x+peak.width/4],[1.25],[peak.width*3]]);
var p_fit = LM.optimize(singleGaussian, p_init, t, y_data, weight, dx, p_min, p_max, consts, opts);
p_fit = p_fit.p;
return [p_fit[0], [p_fit[1][0] * maxY], p_fit[2]];
}
/*
peaks on group should sorted
*/
function optimizeLorentzianTrain(xy, group, opts) {
var xy2 = parseData(xy); //console.log(xy2[0].rows);
if (xy2 === null || xy2[0].rows < 3) {
return null; //Cannot run an optimization with less than 3 points
}
var t = xy2[0];
var y_data = xy2[1];
var maxY = xy2[2];
var currentIndex = 0;
var nbPoints = t.length;
var nextX;
var tI, yI, maxY;
var result = [],
current;
for (var i = 0; i < group.length; i++) {
nextX = group[i].x - group[i].width * 1.5; //console.log(group[i]);
while (t[currentIndex++] < nextX && currentIndex < nbPoints);
nextX = group[i].x + group[i].width * 1.5;
tI = [];
yI = [];
while (t[currentIndex] <= nextX && currentIndex < nbPoints) {
tI.push(t[currentIndex][0]);
yI.push(y_data[currentIndex][0] * maxY);
currentIndex++;
}
current = optimizeSingleLorentzian([tI, yI], group[i], opts);
if (current) {
result.push({
"x": current[0][0],
"y": current[1][0],
"width": current[2][0],
"opt": true
});
} else {
result.push({
"x": group[i].x,
"y": group[i].y,
"width": group[i].width,
"opt": false
});
}
}
return result;
}
function optimizeGaussianTrain(xy, group, opts) {
var xy2 = parseData(xy); //console.log(xy2[0].rows);
if (xy2 === null || xy2[0].rows < 3) {
return null; //Cannot run an optimization with less than 3 points
}
var t = xy2[0];
var y_data = xy2[1];
var maxY = xy2[2];
var currentIndex = 0;
var nbPoints = t.length;
var nextX;
var tI, yI, maxY;
var result = [],
current;
for (var i = 0; i < group.length; i++) {
nextX = group[i].x - group[i].width * 1.5; //console.log(group[i]);
while (t[currentIndex++] < nextX && currentIndex < nbPoints);
nextX = group[i].x + group[i].width * 1.5;
tI = [];
yI = [];
while (t[currentIndex] <= nextX && currentIndex < nbPoints) {
tI.push(t[currentIndex][0]);
yI.push(y_data[currentIndex][0] * maxY);
currentIndex++;
}
current = optimizeSingleGaussian([tI, yI], group[i], opts);
if (current) {
result.push({
"x": current[0][0],
"y": current[1][0],
"width": current[2][0],
"opt": true
});
} else {
result.push({
"x": group[i].x,
"y": group[i].y,
"width": group[i].width,
"opt": false
});
}
}
return result;
}
/**
*
* @param xy A two column matrix containing the x and y data to be fitted
* @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height]
* @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2]
*/
function optimizeLorentzianSum(xy, group, opts) {
var xy2 = parseData(xy);
if (xy2 === null || xy2[0].rows < 3) {
return null; //Cannot run an optimization with less than 3 points
}
var t = xy2[0];
var y_data = xy2[1];
var maxY = xy2[2];
var nbPoints = t.rows,
i;
var weight = [nbPoints / math.sqrt(y_data.dot(y_data))];
var opts = Object.create(opts || [3, 100, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 1]);
var consts = []; // optional vector of constants
var nL = group.length;
var p_init = new Matrix(nL * 3, 1);
var p_min = new Matrix(nL * 3, 1);
var p_max = new Matrix(nL * 3, 1);
var dx = new Matrix(nL * 3, 1);
var dt = Math.abs(t[0][0] - t[1][0]);
for (i = 0; i < nL; i++) {
p_init[i][0] = group[i].x;
p_init[i + nL][0] = 1;
p_init[i + 2 * nL][0] = group[i].width;
p_min[i][0] = group[i].x - dt; //-group[i].width/4;
p_min[i + nL][0] = 0;
p_min[i + 2 * nL][0] = group[i].width / 4;
p_max[i][0] = group[i].x + dt; //+group[i].width/4;
p_max[i + nL][0] = 1.5;
p_max[i + 2 * nL][0] = group[i].width * 4;
dx[i][0] = -dt / 1000;
dx[i + nL][0] = -1e-3;
dx[i + 2 * nL][0] = -dt / 1000;
}
var dx = -Math.abs(t[0][0] - t[1][0]) / 10000;
var p_fit = LM.optimize(sumOfLorentzians, p_init, t, y_data, weight, dx, p_min, p_max, consts, opts);
p_fit = p_fit.p; //Put back the result in the correct format
var result = new Array(nL);
for (i = 0; i < nL; i++) {
result[i] = [p_fit[i], [p_fit[i + nL][0] * maxY], p_fit[i + 2 * nL]];
}
return result;
}
/**
*
* @param xy A two column matrix containing the x and y data to be fitted
* @param group A set of initial lorentzian parameters to be optimized [center, heigth, half_width_at_half_height]
* @returns {Array} A set of final lorentzian parameters [center, heigth, hwhh*2]
*/
function optimizeGaussianSum(xy, group, opts) {
var xy2 = parseData(xy);
if (xy2 === null || xy2[0].rows < 3) {
return null; //Cannot run an optimization with less than 3 points
}
var t = xy2[0];
var y_data = xy2[1];
var maxY = xy2[2];
var nbPoints = t.rows,
i;
var weight = new Matrix(nbPoints, 1); //[nbPoints / math.sqrt(y_data.dot(y_data))];
var k = nbPoints / math.sqrt(y_data.dot(y_data));
for (i = 0; i < nbPoints; i++) {
weight[i][0] = k; ///(y_data[i][0]);
//weight[i][0]=k*(2-y_data[i][0]);
}
var opts = Object.create(opts || [3, 100, 1e-3, 1e-3, 1e-3, 1e-2, 1e-2, 11, 9, 2]); //var opts=[ 3, 100, 1e-5, 1e-6, 1e-6, 1e-6, 1e-6, 11, 9, 1 ];
var consts = []; // optional vector of constants
var nL = group.length;
var p_init = new Matrix(nL * 3, 1);
var p_min = new Matrix(nL * 3, 1);
var p_max = new Matrix(nL * 3, 1);
var dx = new Matrix(nL * 3, 1);
var dt = Math.abs(t[0][0] - t[1][0]);
for (i = 0; i < nL; i++) {
p_init[i][0] = group[i].x;
p_init[i + nL][0] = group[i].y / maxY;
p_init[i + 2 * nL][0] = group[i].width;
p_min[i][0] = group[i].x - dt;
p_min[i + nL][0] = group[i].y * 0.8 / maxY;
p_min[i + 2 * nL][0] = group[i].width / 2;
p_max[i][0] = group[i].x + dt;
p_max[i + nL][0] = group[i].y * 1.2 / maxY;
p_max[i + 2 * nL][0] = group[i].width * 2;
dx[i][0] = -dt / 1000;
dx[i + nL][0] = -1e-3;
dx[i + 2 * nL][0] = -dt / 1000;
} //console.log(t);
var p_fit = LM.optimize(sumOfLorentzians, p_init, t, y_data, weight, dx, p_min, p_max, consts, opts);
p_fit = p_fit.p; //Put back the result in the correct format
var result = new Array(nL);
for (i = 0; i < nL; i++) {
result[i] = [p_fit[i], [p_fit[i + nL][0] * maxY], p_fit[i + 2 * nL]];
}
return result;
}
/**
*
* Converts the given input to the required x, y column matrices. y data is normalized to max(y)=1
* @param xy
* @returns {*[]}
*/
function parseData(xy, threshold) {
var nbSeries = xy.length;
var t = null;
var y_data = null,
x,
y;
var maxY = 0,
i,
j;
if (nbSeries == 2) {
//Looks like row wise matrix [x,y]
var nbPoints = xy[0].length; //if(nbPoints<3)
// throw new Exception(nbPoints);
//else{
t = new Array(nbPoints); //new Matrix(nbPoints,1);
y_data = new Array(nbPoints); //new Matrix(nbPoints,1);
x = xy[0];
y = xy[1];
if (typeof x[0] === "number") {
for (i = 0; i < nbPoints; i++) {
t[i] = x[i];
y_data[i] = y[i];
if (y[i] > maxY) maxY = y[i];
}
} else {
//It is a colum matrix
if (typeof x[0] === "object") {
for (i = 0; i < nbPoints; i++) {
t[i] = x[i][0];
y_data[i] = y[i][0];
if (y[i][0] > maxY) maxY = y[i][0];
}
}
} //}
} else {
//Looks like a column wise matrix [[x],[y]]
var nbPoints = nbSeries; //if(nbPoints<3)
// throw new SizeException(nbPoints);
//else {
t = new Array(nbPoints); //new Matrix(nbPoints, 1);
y_data = new Array(nbPoints); //new Matrix(nbPoints, 1);
for (i = 0; i < nbPoints; i++) {
t[i] = xy[i][0];
y_data[i] = xy[i][1];
if (y_data[i] > maxY) maxY = y_data[i];
} //}
}
for (i = 0; i < nbPoints; i++) {
y_data[i] /= maxY;
}
if (threshold) {
for (i = nbPoints - 1; i >= 0; i--) {
if (y_data[i] < threshold) {
y_data.splice(i, 1);
t.splice(i, 1);
}
}
}
if (t.length > 0) return [new Matrix([t]).transpose(), new Matrix([y_data]).transpose(), maxY];
return null;
}
function sizeException(nbPoints) {
return new RangeError("Not enough points to perform the optimization: " + nbPoints + "< 3");
}
module.exports.optimizeSingleLorentzian = optimizeSingleLorentzian;
module.exports.optimizeLorentzianSum = optimizeLorentzianSum;
module.exports.optimizeSingleGaussian = optimizeSingleGaussian;
module.exports.optimizeGaussianSum = optimizeGaussianSum;
module.exports.singleGaussian = singleGaussian;
module.exports.singleLorentzian = singleLorentzian;
module.exports.optimizeGaussianTrain = optimizeGaussianTrain;
module.exports.optimizeLorentzianTrain = optimizeLorentzianTrain;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = abstractMatrix;
var LuDecomposition = __webpack_require__(36);
var SvDecomposition = __webpack_require__(37);
var arrayUtils = __webpack_require__(73);
var util = __webpack_require__(13);
var MatrixTransposeView = __webpack_require__(77);
var MatrixRowView = __webpack_require__(78);
var MatrixSubView = __webpack_require__(79);
var MatrixSelectionView = __webpack_require__(80);
var MatrixColumnView = __webpack_require__(81);
var MatrixFlipRowView = __webpack_require__(82);
var MatrixFlipColumnView = __webpack_require__(83);
function abstractMatrix(superCtor) {
if (superCtor === undefined) superCtor = Object;
/**
* Real matrix
* @class Matrix
* @param {number|Array|Matrix} nRows - Number of rows of the new matrix,
* 2D array containing the data or Matrix instance to clone
* @param {number} [nColumns] - Number of columns of the new matrix
*/
class Matrix extends superCtor {
static get [Symbol.species]() {
return this;
}
/**
* Constructs a Matrix with the chosen dimensions from a 1D array
* @param {number} newRows - Number of rows
* @param {number} newColumns - Number of columns
* @param {Array} newData - A 1D array containing data for the matrix
* @return {Matrix} - The new matrix
*/
static from1DArray(newRows, newColumns, newData) {
var length = newRows * newColumns;
if (length !== newData.length) {
throw new RangeError('Data length does not match given dimensions');
}
var newMatrix = new this(newRows, newColumns);
for (var row = 0; row < newRows; row++) {
for (var column = 0; column < newColumns; column++) {
newMatrix.set(row, column, newData[row * newColumns + column]);
}
}
return newMatrix;
}
/**
* Creates a row vector, a matrix with only one row.
* @param {Array} newData - A 1D array containing data for the vector
* @return {Matrix} - The new matrix
*/
static rowVector(newData) {
var vector = new this(1, newData.length);
for (var i = 0; i < newData.length; i++) {
vector.set(0, i, newData[i]);
}
return vector;
}
/**
* Creates a column vector, a matrix with only one column.
* @param {Array} newData - A 1D array containing data for the vector
* @return {Matrix} - The new matrix
*/
static columnVector(newData) {
var vector = new this(newData.length, 1);
for (var i = 0; i < newData.length; i++) {
vector.set(i, 0, newData[i]);
}
return vector;
}
/**
* Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns).
* @param {number} rows - Number of rows
* @param {number} columns - Number of columns
* @return {Matrix} - The new matrix
*/
static empty(rows, columns) {
return new this(rows, columns);
}
/**
* Creates a matrix with the given dimensions. Values will be set to zero.
* @param {number} rows - Number of rows
* @param {number} columns - Number of columns
* @return {Matrix} - The new matrix
*/
static zeros(rows, columns) {
return this.empty(rows, columns).fill(0);
}
/**
* Creates a matrix with the given dimensions. Values will be set to one.
* @param {number} rows - Number of rows
* @param {number} columns - Number of columns
* @return {Matrix} - The new matrix
*/
static ones(rows, columns) {
return this.empty(rows, columns).fill(1);
}
/**
* Creates a matrix with the given dimensions. Values will be randomly set.
* @param {number} rows - Number of rows
* @param {number} columns - Number of columns
* @param {function} [rng=Math.random] - Random number generator
* @return {Matrix} The new matrix
*/
static rand(rows, columns, rng) {
if (rng === undefined) rng = Math.random;
var matrix = this.empty(rows, columns);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
matrix.set(i, j, rng());
}
}
return matrix;
}
/**
* Creates a matrix with the given dimensions. Values will be random integers.
* @param {number} rows - Number of rows
* @param {number} columns - Number of columns
* @param {number} [maxValue=1000] - Maximum value
* @param {function} [rng=Math.random] - Random number generator
* @return {Matrix} The new matrix
*/
static randInt(rows, columns, maxValue, rng) {
if (maxValue === undefined) maxValue = 1000;
if (rng === undefined) rng = Math.random;
var matrix = this.empty(rows, columns);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
var value = Math.floor(rng() * maxValue);
matrix.set(i, j, value);
}
}
return matrix;
}
/**
* Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0.
* @param {number} rows - Number of rows
* @param {number} [columns=rows] - Number of columns
* @param {number} [value=1] - Value to fill the diagonal with
* @return {Matrix} - The new identity matrix
*/
static eye(rows, columns, value) {
if (columns === undefined) columns = rows;
if (value === undefined) value = 1;
var min = Math.min(rows, columns);
var matrix = this.zeros(rows, columns);
for (var i = 0; i < min; i++) {
matrix.set(i, i, value);
}
return matrix;
}
/**
* Creates a diagonal matrix based on the given array.
* @param {Array} data - Array containing the data for the diagonal
* @param {number} [rows] - Number of rows (Default: data.length)
* @param {number} [columns] - Number of columns (Default: rows)
* @return {Matrix} - The new diagonal matrix
*/
static diag(data, rows, columns) {
var l = data.length;
if (rows === undefined) rows = l;
if (columns === undefined) columns = rows;
var min = Math.min(l, rows, columns);
var matrix = this.zeros(rows, columns);
for (var i = 0; i < min; i++) {
matrix.set(i, i, data[i]);
}
return matrix;
}
/**
* Returns a matrix whose elements are the minimum between matrix1 and matrix2
* @param {Matrix} matrix1
* @param {Matrix} matrix2
* @return {Matrix}
*/
static min(matrix1, matrix2) {
matrix1 = this.checkMatrix(matrix1);
matrix2 = this.checkMatrix(matrix2);
var rows = matrix1.rows;
var columns = matrix1.columns;
var result = new this(rows, columns);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));
}
}
return result;
}
/**
* Returns a matrix whose elements are the maximum between matrix1 and matrix2
* @param {Matrix} matrix1
* @param {Matrix} matrix2
* @return {Matrix}
*/
static max(matrix1, matrix2) {
matrix1 = this.checkMatrix(matrix1);
matrix2 = this.checkMatrix(matrix2);
var rows = matrix1.rows;
var columns = matrix1.columns;
var result = new this(rows, columns);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));
}
}
return result;
}
/**
* Check that the provided value is a Matrix and tries to instantiate one if not
* @param {*} value - The value to check
* @return {Matrix}
*/
static checkMatrix(value) {
return Matrix.isMatrix(value) ? value : new this(value);
}
/**
* Returns true if the argument is a Matrix, false otherwise
* @param {*} value - The value to check
* @return {boolean}
*/
static isMatrix(value) {
return value != null && value.klass === 'Matrix';
}
/**
* @prop {number} size - The number of elements in the matrix.
*/
get size() {
return this.rows * this.columns;
}
/**
* Applies a callback for each element of the matrix. The function is called in the matrix (this) context.
* @param {function} callback - Function that will be called with two parameters : i (row) and j (column)
* @return {Matrix} this
*/
apply(callback) {
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
var ii = this.rows;
var jj = this.columns;
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
callback.call(this, i, j);
}
}
return this;
}
/**
* Returns a new 1D array filled row by row with the matrix values
* @return {Array}
*/
to1DArray() {
var array = new Array(this.size);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
array[i * this.columns + j] = this.get(i, j);
}
}
return array;
}
/**
* Returns a 2D array containing a copy of the data
* @return {Array}
*/
to2DArray() {
var copy = new Array(this.rows);
for (var i = 0; i < this.rows; i++) {
copy[i] = new Array(this.columns);
for (var j = 0; j < this.columns; j++) {
copy[i][j] = this.get(i, j);
}
}
return copy;
}
/**
* @return {boolean} true if the matrix has one row
*/
isRowVector() {
return this.rows === 1;
}
/**
* @return {boolean} true if the matrix has one column
*/
isColumnVector() {
return this.columns === 1;
}
/**
* @return {boolean} true if the matrix has one row or one column
*/
isVector() {
return this.rows === 1 || this.columns === 1;
}
/**
* @return {boolean} true if the matrix has the same number of rows and columns
*/
isSquare() {
return this.rows === this.columns;
}
/**
* @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal
*/
isSymmetric() {
if (this.isSquare()) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j <= i; j++) {
if (this.get(i, j) !== this.get(j, i)) {
return false;
}
}
}
return true;
}
return false;
}
/**
* Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1
* @abstract
* @param {number} rowIndex - Index of the row
* @param {number} columnIndex - Index of the column
* @param {number} value - The new value for the element
* @return {Matrix} this
*/
set(rowIndex, columnIndex, value) {
// eslint-disable-line no-unused-vars
throw new Error('set method is unimplemented');
}
/**
* Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4]
* @abstract
* @param {number} rowIndex - Index of the row
* @param {number} columnIndex - Index of the column
* @return {number}
*/
get(rowIndex, columnIndex) {
// eslint-disable-line no-unused-vars
throw new Error('get method is unimplemented');
}
/**
* Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of
* rows of the matrix, and colRep times the number of columns of the matrix
* @param {number} rowRep - Number of times the rows should be repeated
* @param {number} colRep - Number of times the columns should be re
* @return {Matrix}
* @example
* var matrix = new Matrix([[1,2]]);
* matrix.repeat(2); // [[1,2],[1,2]]
*/
repeat(rowRep, colRep) {
rowRep = rowRep || 1;
colRep = colRep || 1;
var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep);
for (var i = 0; i < rowRep; i++) {
for (var j = 0; j < colRep; j++) {
matrix.setSubMatrix(this, this.rows * i, this.columns * j);
}
}
return matrix;
}
/**
* Fills the matrix with a given value. All elements will be set to this value.
* @param {number} value - New value
* @return {Matrix} this
*/
fill(value) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, value);
}
}
return this;
}
/**
* Negates the matrix. All elements will be multiplied by (-1)
* @return {Matrix} this
*/
neg() {
return this.mulS(-1);
}
/**
* Returns a new array from the given row index
* @param {number} index - Row index
* @return {Array}
*/
getRow(index) {
util.checkRowIndex(this, index);
var row = new Array(this.columns);
for (var i = 0; i < this.columns; i++) {
row[i] = this.get(index, i);
}
return row;
}
/**
* Returns a new row vector from the given row index
* @param {number} index - Row index
* @return {Matrix}
*/
getRowVector(index) {
return this.constructor.rowVector(this.getRow(index));
}
/**
* Sets a row at the given index
* @param {number} index - Row index
* @param {Array|Matrix} array - Array or vector
* @return {Matrix} this
*/
setRow(index, array) {
util.checkRowIndex(this, index);
array = util.checkRowVector(this, array);
for (var i = 0; i < this.columns; i++) {
this.set(index, i, array[i]);
}
return this;
}
/**
* Swaps two rows
* @param {number} row1 - First row index
* @param {number} row2 - Second row index
* @return {Matrix} this
*/
swapRows(row1, row2) {
util.checkRowIndex(this, row1);
util.checkRowIndex(this, row2);
for (var i = 0; i < this.columns; i++) {
var temp = this.get(row1, i);
this.set(row1, i, this.get(row2, i));
this.set(row2, i, temp);
}
return this;
}
/**
* Returns a new array from the given column index
* @param {number} index - Column index
* @return {Array}
*/
getColumn(index) {
util.checkColumnIndex(this, index);
var column = new Array(this.rows);
for (var i = 0; i < this.rows; i++) {
column[i] = this.get(i, index);
}
return column;
}
/**
* Returns a new column vector from the given column index
* @param {number} index - Column index
* @return {Matrix}
*/
getColumnVector(index) {
return this.constructor.columnVector(this.getColumn(index));
}
/**
* Sets a column at the given index
* @param {number} index - Column index
* @param {Array|Matrix} array - Array or vector
* @return {Matrix} this
*/
setColumn(index, array) {
util.checkColumnIndex(this, index);
array = util.checkColumnVector(this, array);
for (var i = 0; i < this.rows; i++) {
this.set(i, index, array[i]);
}
return this;
}
/**
* Swaps two columns
* @param {number} column1 - First column index
* @param {number} column2 - Second column index
* @return {Matrix} this
*/
swapColumns(column1, column2) {
util.checkColumnIndex(this, column1);
util.checkColumnIndex(this, column2);
for (var i = 0; i < this.rows; i++) {
var temp = this.get(i, column1);
this.set(i, column1, this.get(i, column2));
this.set(i, column2, temp);
}
return this;
}
/**
* Adds the values of a vector to each row
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
addRowVector(vector) {
vector = util.checkRowVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) + vector[j]);
}
}
return this;
}
/**
* Subtracts the values of a vector from each row
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
subRowVector(vector) {
vector = util.checkRowVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) - vector[j]);
}
}
return this;
}
/**
* Multiplies the values of a vector with each row
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
mulRowVector(vector) {
vector = util.checkRowVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) * vector[j]);
}
}
return this;
}
/**
* Divides the values of each row by those of a vector
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
divRowVector(vector) {
vector = util.checkRowVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) / vector[j]);
}
}
return this;
}
/**
* Adds the values of a vector to each column
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
addColumnVector(vector) {
vector = util.checkColumnVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) + vector[i]);
}
}
return this;
}
/**
* Subtracts the values of a vector from each column
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
subColumnVector(vector) {
vector = util.checkColumnVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) - vector[i]);
}
}
return this;
}
/**
* Multiplies the values of a vector with each column
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
mulColumnVector(vector) {
vector = util.checkColumnVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) * vector[i]);
}
}
return this;
}
/**
* Divides the values of each column by those of a vector
* @param {Array|Matrix} vector - Array or vector
* @return {Matrix} this
*/
divColumnVector(vector) {
vector = util.checkColumnVector(this, vector);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) / vector[i]);
}
}
return this;
}
/**
* Multiplies the values of a row with a scalar
* @param {number} index - Row index
* @param {number} value
* @return {Matrix} this
*/
mulRow(index, value) {
util.checkRowIndex(this, index);
for (var i = 0; i < this.columns; i++) {
this.set(index, i, this.get(index, i) * value);
}
return this;
}
/**
* Multiplies the values of a column with a scalar
* @param {number} index - Column index
* @param {number} value
* @return {Matrix} this
*/
mulColumn(index, value) {
util.checkColumnIndex(this, index);
for (var i = 0; i < this.rows; i++) {
this.set(i, index, this.get(i, index) * value);
}
return this;
}
/**
* Returns the maximum value of the matrix
* @return {number}
*/
max() {
var v = this.get(0, 0);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
if (this.get(i, j) > v) {
v = this.get(i, j);
}
}
}
return v;
}
/**
* Returns the index of the maximum value
* @return {Array}
*/
maxIndex() {
var v = this.get(0, 0);
var idx = [0, 0];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
if (this.get(i, j) > v) {
v = this.get(i, j);
idx[0] = i;
idx[1] = j;
}
}
}
return idx;
}
/**
* Returns the minimum value of the matrix
* @return {number}
*/
min() {
var v = this.get(0, 0);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
if (this.get(i, j) < v) {
v = this.get(i, j);
}
}
}
return v;
}
/**
* Returns the index of the minimum value
* @return {Array}
*/
minIndex() {
var v = this.get(0, 0);
var idx = [0, 0];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
if (this.get(i, j) < v) {
v = this.get(i, j);
idx[0] = i;
idx[1] = j;
}
}
}
return idx;
}
/**
* Returns the maximum value of one row
* @param {number} row - Row index
* @return {number}
*/
maxRow(row) {
util.checkRowIndex(this, row);
var v = this.get(row, 0);
for (var i = 1; i < this.columns; i++) {
if (this.get(row, i) > v) {
v = this.get(row, i);
}
}
return v;
}
/**
* Returns the index of the maximum value of one row
* @param {number} row - Row index
* @return {Array}
*/
maxRowIndex(row) {
util.checkRowIndex(this, row);
var v = this.get(row, 0);
var idx = [row, 0];
for (var i = 1; i < this.columns; i++) {
if (this.get(row, i) > v) {
v = this.get(row, i);
idx[1] = i;
}
}
return idx;
}
/**
* Returns the minimum value of one row
* @param {number} row - Row index
* @return {number}
*/
minRow(row) {
util.checkRowIndex(this, row);
var v = this.get(row, 0);
for (var i = 1; i < this.columns; i++) {
if (this.get(row, i) < v) {
v = this.get(row, i);
}
}
return v;
}
/**
* Returns the index of the maximum value of one row
* @param {number} row - Row index
* @return {Array}
*/
minRowIndex(row) {
util.checkRowIndex(this, row);
var v = this.get(row, 0);
var idx = [row, 0];
for (var i = 1; i < this.columns; i++) {
if (this.get(row, i) < v) {
v = this.get(row, i);
idx[1] = i;
}
}
return idx;
}
/**
* Returns the maximum value of one column
* @param {number} column - Column index
* @return {number}
*/
maxColumn(column) {
util.checkColumnIndex(this, column);
var v = this.get(0, column);
for (var i = 1; i < this.rows; i++) {
if (this.get(i, column) > v) {
v = this.get(i, column);
}
}
return v;
}
/**
* Returns the index of the maximum value of one column
* @param {number} column - Column index
* @return {Array}
*/
maxColumnIndex(column) {
util.checkColumnIndex(this, column);
var v = this.get(0, column);
var idx = [0, column];
for (var i = 1; i < this.rows; i++) {
if (this.get(i, column) > v) {
v = this.get(i, column);
idx[0] = i;
}
}
return idx;
}
/**
* Returns the minimum value of one column
* @param {number} column - Column index
* @return {number}
*/
minColumn(column) {
util.checkColumnIndex(this, column);
var v = this.get(0, column);
for (var i = 1; i < this.rows; i++) {
if (this.get(i, column) < v) {
v = this.get(i, column);
}
}
return v;
}
/**
* Returns the index of the minimum value of one column
* @param {number} column - Column index
* @return {Array}
*/
minColumnIndex(column) {
util.checkColumnIndex(this, column);
var v = this.get(0, column);
var idx = [0, column];
for (var i = 1; i < this.rows; i++) {
if (this.get(i, column) < v) {
v = this.get(i, column);
idx[0] = i;
}
}
return idx;
}
/**
* Returns an array containing the diagonal values of the matrix
* @return {Array}
*/
diag() {
var min = Math.min(this.rows, this.columns);
var diag = new Array(min);
for (var i = 0; i < min; i++) {
diag[i] = this.get(i, i);
}
return diag;
}
/**
* Returns the sum by the argument given, if no argument given,
* it returns the sum of all elements of the matrix.
* @param {string} by - sum by 'row' or 'column'.
* @return {Matrix|number}
*/
sum(by) {
switch (by) {
case 'row':
return util.sumByRow(this);
case 'column':
return util.sumByColumn(this);
default:
return util.sumAll(this);
}
}
/**
* Returns the mean of all elements of the matrix
* @return {number}
*/
mean() {
return this.sum() / this.size;
}
/**
* Returns the product of all elements of the matrix
* @return {number}
*/
prod() {
var prod = 1;
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
prod *= this.get(i, j);
}
}
return prod;
}
/**
* Computes the cumulative sum of the matrix elements (in place, row by row)
* @return {Matrix} this
*/
cumulativeSum() {
var sum = 0;
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
sum += this.get(i, j);
this.set(i, j, sum);
}
}
return this;
}
/**
* Computes the dot (scalar) product between the matrix and another
* @param {Matrix} vector2 vector
* @return {number}
*/
dot(vector2) {
if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray();
var vector1 = this.to1DArray();
if (vector1.length !== vector2.length) {
throw new RangeError('vectors do not have the same size');
}
var dot = 0;
for (var i = 0; i < vector1.length; i++) {
dot += vector1[i] * vector2[i];
}
return dot;
}
/**
* Returns the matrix product between this and other
* @param {Matrix} other
* @return {Matrix}
*/
mmul(other) {
other = this.constructor.checkMatrix(other);
if (this.columns !== other.rows) {
// eslint-disable-next-line no-console
console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.');
}
var m = this.rows;
var n = this.columns;
var p = other.columns;
var result = new this.constructor[Symbol.species](m, p);
var Bcolj = new Array(n);
for (var j = 0; j < p; j++) {
for (var k = 0; k < n; k++) {
Bcolj[k] = other.get(k, j);
}
for (var i = 0; i < m; i++) {
var s = 0;
for (k = 0; k < n; k++) {
s += this.get(i, k) * Bcolj[k];
}
result.set(i, j, s);
}
}
return result;
}
strassen2x2(other) {
var result = new this.constructor[Symbol.species](2, 2);
const a11 = this.get(0, 0);
const b11 = other.get(0, 0);
const a12 = this.get(0, 1);
const b12 = other.get(0, 1);
const a21 = this.get(1, 0);
const b21 = other.get(1, 0);
const a22 = this.get(1, 1);
const b22 = other.get(1, 1); // Compute intermediate values.
const m1 = (a11 + a22) * (b11 + b22);
const m2 = (a21 + a22) * b11;
const m3 = a11 * (b12 - b22);
const m4 = a22 * (b21 - b11);
const m5 = (a11 + a12) * b22;
const m6 = (a21 - a11) * (b11 + b12);
const m7 = (a12 - a22) * (b21 + b22); // Combine intermediate values into the output.
const c00 = m1 + m4 - m5 + m7;
const c01 = m3 + m5;
const c10 = m2 + m4;
const c11 = m1 - m2 + m3 + m6;
result.set(0, 0, c00);
result.set(0, 1, c01);
result.set(1, 0, c10);
result.set(1, 1, c11);
return result;
}
strassen3x3(other) {
var result = new this.constructor[Symbol.species](3, 3);
const a00 = this.get(0, 0);
const a01 = this.get(0, 1);
const a02 = this.get(0, 2);
const a10 = this.get(1, 0);
const a11 = this.get(1, 1);
const a12 = this.get(1, 2);
const a20 = this.get(2, 0);
const a21 = this.get(2, 1);
const a22 = this.get(2, 2);
const b00 = other.get(0, 0);
const b01 = other.get(0, 1);
const b02 = other.get(0, 2);
const b10 = other.get(1, 0);
const b11 = other.get(1, 1);
const b12 = other.get(1, 2);
const b20 = other.get(2, 0);
const b21 = other.get(2, 1);
const b22 = other.get(2, 2);
const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;
const m2 = (a00 - a10) * (-b01 + b11);
const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);
const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);
const m5 = (a10 + a11) * (-b00 + b01);
const m6 = a00 * b00;
const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);
const m8 = (-a00 + a20) * (b02 - b12);
const m9 = (a20 + a21) * (-b00 + b02);
const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;
const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);
const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);
const m13 = (a02 - a22) * (b11 - b21);
const m14 = a02 * b20;
const m15 = (a21 + a22) * (-b20 + b21);
const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);
const m17 = (a02 - a12) * (b12 - b22);
const m18 = (a11 + a12) * (-b20 + b22);
const m19 = a01 * b10;
const m20 = a12 * b21;
const m21 = a10 * b02;
const m22 = a20 * b01;
const m23 = a22 * b22;
const c00 = m6 + m14 + m19;
const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;
const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;
const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;
const c11 = m2 + m4 + m5 + m6 + m20;
const c12 = m14 + m16 + m17 + m18 + m21;
const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;
const c21 = m12 + m13 + m14 + m15 + m22;
const c22 = m6 + m7 + m8 + m9 + m23;
result.set(0, 0, c00);
result.set(0, 1, c01);
result.set(0, 2, c02);
result.set(1, 0, c10);
result.set(1, 1, c11);
result.set(1, 2, c12);
result.set(2, 0, c20);
result.set(2, 1, c21);
result.set(2, 2, c22);
return result;
}
/**
* Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000.
* @param {Matrix} y
* @return {Matrix}
*/
mmulStrassen(y) {
var x = this.clone();
var r1 = x.rows;
var c1 = x.columns;
var r2 = y.rows;
var c2 = y.columns;
if (c1 !== r2) {
// eslint-disable-next-line no-console
console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);
} // Put a matrix into the top left of a matrix of zeros.
// `rows` and `cols` are the dimensions of the output matrix.
function embed(mat, rows, cols) {
var r = mat.rows;
var c = mat.columns;
if (r === rows && c === cols) {
return mat;
} else {
var resultat = Matrix.zeros(rows, cols);
resultat = resultat.setSubMatrix(mat, 0, 0);
return resultat;
}
} // Make sure both matrices are the same size.
// This is exclusively for simplicity:
// this algorithm can be implemented with matrices of different sizes.
var r = Math.max(r1, r2);
var c = Math.max(c1, c2);
x = embed(x, r, c);
y = embed(y, r, c); // Our recursive multiplication function.
function blockMult(a, b, rows, cols) {
// For small matrices, resort to naive multiplication.
if (rows <= 512 || cols <= 512) {
return a.mmul(b); // a is equivalent to this
} // Apply dynamic padding.
if (rows % 2 === 1 && cols % 2 === 1) {
a = embed(a, rows + 1, cols + 1);
b = embed(b, rows + 1, cols + 1);
} else if (rows % 2 === 1) {
a = embed(a, rows + 1, cols);
b = embed(b, rows + 1, cols);
} else if (cols % 2 === 1) {
a = embed(a, rows, cols + 1);
b = embed(b, rows, cols + 1);
}
var halfRows = parseInt(a.rows / 2);
var halfCols = parseInt(a.columns / 2); // Subdivide input matrices.
var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);
var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);
var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);
var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);
var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);
var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);
var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);
var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); // Compute intermediate values.
var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols);
var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols);
var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols);
var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols);
var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols);
var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols);
var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); // Combine intermediate values into the output.
var c11 = Matrix.add(m1, m4);
c11.sub(m5);
c11.add(m7);
var c12 = Matrix.add(m3, m5);
var c21 = Matrix.add(m2, m4);
var c22 = Matrix.sub(m1, m2);
c22.add(m3);
c22.add(m6); //Crop output to the desired size (undo dynamic padding).
var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns);
resultat = resultat.setSubMatrix(c11, 0, 0);
resultat = resultat.setSubMatrix(c12, c11.rows, 0);
resultat = resultat.setSubMatrix(c21, 0, c11.columns);
resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);
return resultat.subMatrix(0, rows - 1, 0, cols - 1);
}
return blockMult(x, y, r, c);
}
/**
* Returns a row-by-row scaled matrix
* @param {number} [min=0] - Minimum scaled value
* @param {number} [max=1] - Maximum scaled value
* @return {Matrix} - The scaled matrix
*/
scaleRows(min, max) {
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
if (min >= max) {
throw new RangeError('min should be strictly smaller than max');
}
var newMatrix = this.constructor.empty(this.rows, this.columns);
for (var i = 0; i < this.rows; i++) {
var scaled = arrayUtils.scale(this.getRow(i), {
min,
max
});
newMatrix.setRow(i, scaled);
}
return newMatrix;
}
/**
* Returns a new column-by-column scaled matrix
* @param {number} [min=0] - Minimum scaled value
* @param {number} [max=1] - Maximum scaled value
* @return {Matrix} - The new scaled matrix
* @example
* var matrix = new Matrix([[1,2],[-1,0]]);
* var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]]
*/
scaleColumns(min, max) {
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
if (min >= max) {
throw new RangeError('min should be strictly smaller than max');
}
var newMatrix = this.constructor.empty(this.rows, this.columns);
for (var i = 0; i < this.columns; i++) {
var scaled = arrayUtils.scale(this.getColumn(i), {
min: min,
max: max
});
newMatrix.setColumn(i, scaled);
}
return newMatrix;
}
/**
* Returns the Kronecker product (also known as tensor product) between this and other
* See https://en.wikipedia.org/wiki/Kronecker_product
* @param {Matrix} other
* @return {Matrix}
*/
kroneckerProduct(other) {
other = this.constructor.checkMatrix(other);
var m = this.rows;
var n = this.columns;
var p = other.rows;
var q = other.columns;
var result = new this.constructor[Symbol.species](m * p, n * q);
for (var i = 0; i < m; i++) {
for (var j = 0; j < n; j++) {
for (var k = 0; k < p; k++) {
for (var l = 0; l < q; l++) {
result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l);
}
}
}
}
return result;
}
/**
* Transposes the matrix and returns a new one containing the result
* @return {Matrix}
*/
transpose() {
var result = new this.constructor[Symbol.species](this.columns, this.rows);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
result.set(j, i, this.get(i, j));
}
}
return result;
}
/**
* Sorts the rows (in place)
* @param {function} compareFunction - usual Array.prototype.sort comparison function
* @return {Matrix} this
*/
sortRows(compareFunction) {
if (compareFunction === undefined) compareFunction = compareNumbers;
for (var i = 0; i < this.rows; i++) {
this.setRow(i, this.getRow(i).sort(compareFunction));
}
return this;
}
/**
* Sorts the columns (in place)
* @param {function} compareFunction - usual Array.prototype.sort comparison function
* @return {Matrix} this
*/
sortColumns(compareFunction) {
if (compareFunction === undefined) compareFunction = compareNumbers;
for (var i = 0; i < this.columns; i++) {
this.setColumn(i, this.getColumn(i).sort(compareFunction));
}
return this;
}
/**
* Returns a subset of the matrix
* @param {number} startRow - First row index
* @param {number} endRow - Last row index
* @param {number} startColumn - First column index
* @param {number} endColumn - Last column index
* @return {Matrix}
*/
subMatrix(startRow, endRow, startColumn, endColumn) {
util.checkRange(this, startRow, endRow, startColumn, endColumn);
var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1);
for (var i = startRow; i <= endRow; i++) {
for (var j = startColumn; j <= endColumn; j++) {
newMatrix[i - startRow][j - startColumn] = this.get(i, j);
}
}
return newMatrix;
}
/**
* Returns a subset of the matrix based on an array of row indices
* @param {Array} indices - Array containing the row indices
* @param {number} [startColumn = 0] - First column index
* @param {number} [endColumn = this.columns-1] - Last column index
* @return {Matrix}
*/
subMatrixRow(indices, startColumn, endColumn) {
if (startColumn === undefined) startColumn = 0;
if (endColumn === undefined) endColumn = this.columns - 1;
if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) {
throw new RangeError('Argument out of range');
}
var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1);
for (var i = 0; i < indices.length; i++) {
for (var j = startColumn; j <= endColumn; j++) {
if (indices[i] < 0 || indices[i] >= this.rows) {
throw new RangeError('Row index out of range: ' + indices[i]);
}
newMatrix.set(i, j - startColumn, this.get(indices[i], j));
}
}
return newMatrix;
}
/**
* Returns a subset of the matrix based on an array of column indices
* @param {Array} indices - Array containing the column indices
* @param {number} [startRow = 0] - First row index
* @param {number} [endRow = this.rows-1] - Last row index
* @return {Matrix}
*/
subMatrixColumn(indices, startRow, endRow) {
if (startRow === undefined) startRow = 0;
if (endRow === undefined) endRow = this.rows - 1;
if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) {
throw new RangeError('Argument out of range');
}
var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length);
for (var i = 0; i < indices.length; i++) {
for (var j = startRow; j <= endRow; j++) {
if (indices[i] < 0 || indices[i] >= this.columns) {
throw new RangeError('Column index out of range: ' + indices[i]);
}
newMatrix.set(j - startRow, i, this.get(j, indices[i]));
}
}
return newMatrix;
}
/**
* Set a part of the matrix to the given sub-matrix
* @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values.
* @param {number} startRow - The index of the first row to set
* @param {number} startColumn - The index of the first column to set
* @return {Matrix}
*/
setSubMatrix(matrix, startRow, startColumn) {
matrix = this.constructor.checkMatrix(matrix);
var endRow = startRow + matrix.rows - 1;
var endColumn = startColumn + matrix.columns - 1;
util.checkRange(this, startRow, endRow, startColumn, endColumn);
for (var i = 0; i < matrix.rows; i++) {
for (var j = 0; j < matrix.columns; j++) {
this[startRow + i][startColumn + j] = matrix.get(i, j);
}
}
return this;
}
/**
* Return a new matrix based on a selection of rows and columns
* @param {Array} rowIndices - The row indices to select. Order matters and an index can be more than once.
* @param {Array} columnIndices - The column indices to select. Order matters and an index can be use more than once.
* @return {Matrix} The new matrix
*/
selection(rowIndices, columnIndices) {
var indices = util.checkIndices(this, rowIndices, columnIndices);
var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length);
for (var i = 0; i < indices.row.length; i++) {
var rowIndex = indices.row[i];
for (var j = 0; j < indices.column.length; j++) {
var columnIndex = indices.column[j];
newMatrix[i][j] = this.get(rowIndex, columnIndex);
}
}
return newMatrix;
}
/**
* Returns the trace of the matrix (sum of the diagonal elements)
* @return {number}
*/
trace() {
var min = Math.min(this.rows, this.columns);
var trace = 0;
for (var i = 0; i < min; i++) {
trace += this.get(i, i);
}
return trace;
}
/*
Matrix views
*/
/**
* Returns a view of the transposition of the matrix
* @return {MatrixTransposeView}
*/
transposeView() {
return new MatrixTransposeView(this);
}
/**
* Returns a view of the row vector with the given index
* @param {number} row - row index of the vector
* @return {MatrixRowView}
*/
rowView(row) {
util.checkRowIndex(this, row);
return new MatrixRowView(this, row);
}
/**
* Returns a view of the column vector with the given index
* @param {number} column - column index of the vector
* @return {MatrixColumnView}
*/
columnView(column) {
util.checkColumnIndex(this, column);
return new MatrixColumnView(this, column);
}
/**
* Returns a view of the matrix flipped in the row axis
* @return {MatrixFlipRowView}
*/
flipRowView() {
return new MatrixFlipRowView(this);
}
/**
* Returns a view of the matrix flipped in the column axis
* @return {MatrixFlipColumnView}
*/
flipColumnView() {
return new MatrixFlipColumnView(this);
}
/**
* Returns a view of a submatrix giving the index boundaries
* @param {number} startRow - first row index of the submatrix
* @param {number} endRow - last row index of the submatrix
* @param {number} startColumn - first column index of the submatrix
* @param {number} endColumn - last column index of the submatrix
* @return {MatrixSubView}
*/
subMatrixView(startRow, endRow, startColumn, endColumn) {
return new MatrixSubView(this, startRow, endRow, startColumn, endColumn);
}
/**
* Returns a view of the cross of the row indices and the column indices
* @example
* // resulting vector is [[2], [2]]
* var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1])
* @param {Array} rowIndices
* @param {Array} columnIndices
* @return {MatrixSelectionView}
*/
selectionView(rowIndices, columnIndices) {
return new MatrixSelectionView(this, rowIndices, columnIndices);
}
/**
* Calculates and returns the determinant of a matrix as a Number
* @example
* new Matrix([[1,2,3], [4,5,6]]).det()
* @return {number}
*/
det() {
if (this.isSquare()) {
var a, b, c, d;
if (this.columns === 2) {
// 2 x 2 matrix
a = this.get(0, 0);
b = this.get(0, 1);
c = this.get(1, 0);
d = this.get(1, 1);
return a * d - b * c;
} else if (this.columns === 3) {
// 3 x 3 matrix
var subMatrix0, subMatrix1, subMatrix2;
subMatrix0 = this.selectionView([1, 2], [1, 2]);
subMatrix1 = this.selectionView([1, 2], [0, 2]);
subMatrix2 = this.selectionView([1, 2], [0, 1]);
a = this.get(0, 0);
b = this.get(0, 1);
c = this.get(0, 2);
return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det();
} else {
// general purpose determinant using the LU decomposition
return new LuDecomposition(this).determinant;
}
} else {
throw Error('Determinant can only be calculated for a square matrix.');
}
}
/**
* Returns inverse of a matrix if it exists or the pseudoinverse
* @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15)
* @return {Matrix} the (pseudo)inverted matrix.
*/
pseudoInverse(threshold) {
if (threshold === undefined) threshold = Number.EPSILON;
var svdSolution = new SvDecomposition(this, {
autoTranspose: true
});
var U = svdSolution.leftSingularVectors;
var V = svdSolution.rightSingularVectors;
var s = svdSolution.diagonal;
for (var i = 0; i < s.length; i++) {
if (Math.abs(s[i]) > threshold) {
s[i] = 1.0 / s[i];
} else {
s[i] = 0.0;
}
} // convert list to diagonal
s = this.constructor[Symbol.species].diag(s);
return V.mmul(s.mmul(U.transposeView()));
}
}
Matrix.prototype.klass = 'Matrix';
/**
* @private
* Check that two matrices have the same dimensions
* @param {Matrix} matrix
* @param {Matrix} otherMatrix
*/
function checkDimensions(matrix, otherMatrix) {
// eslint-disable-line no-unused-vars
if (matrix.rows !== otherMatrix.rows || matrix.columns !== otherMatrix.columns) {
throw new RangeError('Matrices dimensions must be equal');
}
}
function compareNumbers(a, b) {
return a - b;
}
/*
Synonyms
*/
Matrix.random = Matrix.rand;
Matrix.diagonal = Matrix.diag;
Matrix.prototype.diagonal = Matrix.prototype.diag;
Matrix.identity = Matrix.eye;
Matrix.prototype.negate = Matrix.prototype.neg;
Matrix.prototype.tensorProduct = Matrix.prototype.kroneckerProduct;
Matrix.prototype.determinant = Matrix.prototype.det;
/*
Add dynamically instance and static methods for mathematical operations
*/
var inplaceOperator = `
(function %name%(value) {
if (typeof value === 'number') return this.%name%S(value);
return this.%name%M(value);
})
`;
var inplaceOperatorScalar = `
(function %name%S(value) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) %op% value);
}
}
return this;
})
`;
var inplaceOperatorMatrix = `
(function %name%M(matrix) {
matrix = this.constructor.checkMatrix(matrix);
checkDimensions(this, matrix);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, this.get(i, j) %op% matrix.get(i, j));
}
}
return this;
})
`;
var staticOperator = `
(function %name%(matrix, value) {
var newMatrix = new this[Symbol.species](matrix);
return newMatrix.%name%(value);
})
`;
var inplaceMethod = `
(function %name%() {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, %method%(this.get(i, j)));
}
}
return this;
})
`;
var staticMethod = `
(function %name%(matrix) {
var newMatrix = new this[Symbol.species](matrix);
return newMatrix.%name%();
})
`;
var inplaceMethodWithArgs = `
(function %name%(%args%) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, %method%(this.get(i, j), %args%));
}
}
return this;
})
`;
var staticMethodWithArgs = `
(function %name%(matrix, %args%) {
var newMatrix = new this[Symbol.species](matrix);
return newMatrix.%name%(%args%);
})
`;
var inplaceMethodWithOneArgScalar = `
(function %name%S(value) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, %method%(this.get(i, j), value));
}
}
return this;
})
`;
var inplaceMethodWithOneArgMatrix = `
(function %name%M(matrix) {
matrix = this.constructor.checkMatrix(matrix);
checkDimensions(this, matrix);
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.set(i, j, %method%(this.get(i, j), matrix.get(i, j)));
}
}
return this;
})
`;
var inplaceMethodWithOneArg = `
(function %name%(value) {
if (typeof value === 'number') return this.%name%S(value);
return this.%name%M(value);
})
`;
var staticMethodWithOneArg = staticMethodWithArgs;
var operators = [// Arithmetic operators
['+', 'add'], ['-', 'sub', 'subtract'], ['*', 'mul', 'multiply'], ['/', 'div', 'divide'], ['%', 'mod', 'modulus'], // Bitwise operators
['&', 'and'], ['|', 'or'], ['^', 'xor'], ['<<', 'leftShift'], ['>>', 'signPropagatingRightShift'], ['>>>', 'rightShift', 'zeroFillRightShift']];
var i;
for (var operator of operators) {
var inplaceOp = eval(fillTemplateFunction(inplaceOperator, {
name: operator[1],
op: operator[0]
}));
var inplaceOpS = eval(fillTemplateFunction(inplaceOperatorScalar, {
name: operator[1] + 'S',
op: operator[0]
}));
var inplaceOpM = eval(fillTemplateFunction(inplaceOperatorMatrix, {
name: operator[1] + 'M',
op: operator[0]
}));
var staticOp = eval(fillTemplateFunction(staticOperator, {
name: operator[1]
}));
for (i = 1; i < operator.length; i++) {
Matrix.prototype[operator[i]] = inplaceOp;
Matrix.prototype[operator[i] + 'S'] = inplaceOpS;
Matrix.prototype[operator[i] + 'M'] = inplaceOpM;
Matrix[operator[i]] = staticOp;
}
}
var methods = [['~', 'not']];
['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'log', 'log1p', 'log10', 'log2', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'].forEach(function (mathMethod) {
methods.push(['Math.' + mathMethod, mathMethod]);
});
for (var method of methods) {
var inplaceMeth = eval(fillTemplateFunction(inplaceMethod, {
name: method[1],
method: method[0]
}));
var staticMeth = eval(fillTemplateFunction(staticMethod, {
name: method[1]
}));
for (i = 1; i < method.length; i++) {
Matrix.prototype[method[i]] = inplaceMeth;
Matrix[method[i]] = staticMeth;
}
}
var methodsWithArgs = [['Math.pow', 1, 'pow']];
for (var methodWithArg of methodsWithArgs) {
var args = 'arg0';
for (i = 1; i < methodWithArg[1]; i++) {
args += `, arg${i}`;
}
if (methodWithArg[1] !== 1) {
var inplaceMethWithArgs = eval(fillTemplateFunction(inplaceMethodWithArgs, {
name: methodWithArg[2],
method: methodWithArg[0],
args: args
}));
var staticMethWithArgs = eval(fillTemplateFunction(staticMethodWithArgs, {
name: methodWithArg[2],
args: args
}));
for (i = 2; i < methodWithArg.length; i++) {
Matrix.prototype[methodWithArg[i]] = inplaceMethWithArgs;
Matrix[methodWithArg[i]] = staticMethWithArgs;
}
} else {
var tmplVar = {
name: methodWithArg[2],
args: args,
method: methodWithArg[0]
};
var inplaceMethod2 = eval(fillTemplateFunction(inplaceMethodWithOneArg, tmplVar));
var inplaceMethodS = eval(fillTemplateFunction(inplaceMethodWithOneArgScalar, tmplVar));
var inplaceMethodM = eval(fillTemplateFunction(inplaceMethodWithOneArgMatrix, tmplVar));
var staticMethod2 = eval(fillTemplateFunction(staticMethodWithOneArg, tmplVar));
for (i = 2; i < methodWithArg.length; i++) {
Matrix.prototype[methodWithArg[i]] = inplaceMethod2;
Matrix.prototype[methodWithArg[i] + 'M'] = inplaceMethodM;
Matrix.prototype[methodWithArg[i] + 'S'] = inplaceMethodS;
Matrix[methodWithArg[i]] = staticMethod2;
}
}
}
function fillTemplateFunction(template, values) {
for (var value in values) {
template = template.replace(new RegExp('%' + value + '%', 'g'), values[value]);
}
return template;
}
return Matrix;
}
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Matrix = __webpack_require__(3); // https://github.com/lutzroeder/Mapack/blob/master/Source/LuDecomposition.cs
function LuDecomposition(matrix) {
if (!(this instanceof LuDecomposition)) {
return new LuDecomposition(matrix);
}
matrix = Matrix.Matrix.checkMatrix(matrix);
var lu = matrix.clone(),
rows = lu.rows,
columns = lu.columns,
pivotVector = new Array(rows),
pivotSign = 1,
i,
j,
k,
p,
s,
t,
v,
LUrowi,
LUcolj,
kmax;
for (i = 0; i < rows; i++) {
pivotVector[i] = i;
}
LUcolj = new Array(rows);
for (j = 0; j < columns; j++) {
for (i = 0; i < rows; i++) {
LUcolj[i] = lu[i][j];
}
for (i = 0; i < rows; i++) {
LUrowi = lu[i];
kmax = Math.min(i, j);
s = 0;
for (k = 0; k < kmax; k++) {
s += LUrowi[k] * LUcolj[k];
}
LUrowi[j] = LUcolj[i] -= s;
}
p = j;
for (i = j + 1; i < rows; i++) {
if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {
p = i;
}
}
if (p !== j) {
for (k = 0; k < columns; k++) {
t = lu[p][k];
lu[p][k] = lu[j][k];
lu[j][k] = t;
}
v = pivotVector[p];
pivotVector[p] = pivotVector[j];
pivotVector[j] = v;
pivotSign = -pivotSign;
}
if (j < rows && lu[j][j] !== 0) {
for (i = j + 1; i < rows; i++) {
lu[i][j] /= lu[j][j];
}
}
}
this.LU = lu;
this.pivotVector = pivotVector;
this.pivotSign = pivotSign;
}
LuDecomposition.prototype = {
isSingular: function isSingular() {
var data = this.LU,
col = data.columns;
for (var j = 0; j < col; j++) {
if (data[j][j] === 0) {
return true;
}
}
return false;
},
get determinant() {
var data = this.LU;
if (!data.isSquare()) {
throw new Error('Matrix must be square');
}
var determinant = this.pivotSign,
col = data.columns;
for (var j = 0; j < col; j++) {
determinant *= data[j][j];
}
return determinant;
},
get lowerTriangularMatrix() {
var data = this.LU,
rows = data.rows,
columns = data.columns,
X = new Matrix.Matrix(rows, columns);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
if (i > j) {
X[i][j] = data[i][j];
} else if (i === j) {
X[i][j] = 1;
} else {
X[i][j] = 0;
}
}
}
return X;
},
get upperTriangularMatrix() {
var data = this.LU,
rows = data.rows,
columns = data.columns,
X = new Matrix.Matrix(rows, columns);
for (var i = 0; i < rows; i++) {
for (var j = 0; j < columns; j++) {
if (i <= j) {
X[i][j] = data[i][j];
} else {
X[i][j] = 0;
}
}
}
return X;
},
get pivotPermutationVector() {
return this.pivotVector.slice();
},
solve: function solve(value) {
value = Matrix.Matrix.checkMatrix(value);
var lu = this.LU,
rows = lu.rows;
if (rows !== value.rows) {
throw new Error('Invalid matrix dimensions');
}
if (this.isSingular()) {
throw new Error('LU matrix is singular');
}
var count = value.columns;
var X = value.subMatrixRow(this.pivotVector, 0, count - 1);
var columns = lu.columns;
var i, j, k;
for (k = 0; k < columns; k++) {
for (i = k + 1; i < columns; i++) {
for (j = 0; j < count; j++) {
X[i][j] -= X[k][j] * lu[i][k];
}
}
}
for (k = columns - 1; k >= 0; k--) {
for (j = 0; j < count; j++) {
X[k][j] /= lu[k][k];
}
for (i = 0; i < k; i++) {
for (j = 0; j < count; j++) {
X[i][j] -= X[k][j] * lu[i][k];
}
}
}
return X;
}
};
module.exports = LuDecomposition;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Matrix = __webpack_require__(3);
var util = __webpack_require__(19);
var hypotenuse = util.hypotenuse;
var getFilled2DArray = util.getFilled2DArray; // https://github.com/lutzroeder/Mapack/blob/master/Source/SingularValueDecomposition.cs
function SingularValueDecomposition(value, options) {
if (!(this instanceof SingularValueDecomposition)) {
return new SingularValueDecomposition(value, options);
}
value = Matrix.Matrix.checkMatrix(value);
options = options || {};
var m = value.rows,
n = value.columns,
nu = Math.min(m, n);
var wantu = true,
wantv = true;
if (options.computeLeftSingularVectors === false) wantu = false;
if (options.computeRightSingularVectors === false) wantv = false;
var autoTranspose = options.autoTranspose === true;
var swapped = false;
var a;
if (m < n) {
if (!autoTranspose) {
a = value.clone(); // eslint-disable-next-line no-console
console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');
} else {
a = value.transpose();
m = a.rows;
n = a.columns;
swapped = true;
var aux = wantu;
wantu = wantv;
wantv = aux;
}
} else {
a = value.clone();
}
var s = new Array(Math.min(m + 1, n)),
U = getFilled2DArray(m, nu, 0),
V = getFilled2DArray(n, n, 0),
e = new Array(n),
work = new Array(m);
var nct = Math.min(m - 1, n);
var nrt = Math.max(0, Math.min(n - 2, m));
var i, j, k, p, t, ks, f, cs, sn, max, kase, scale, sp, spm1, epm1, sk, ek, b, c, shift, g;
for (k = 0, max = Math.max(nct, nrt); k < max; k++) {
if (k < nct) {
s[k] = 0;
for (i = k; i < m; i++) {
s[k] = hypotenuse(s[k], a[i][k]);
}
if (s[k] !== 0) {
if (a[k][k] < 0) {
s[k] = -s[k];
}
for (i = k; i < m; i++) {
a[i][k] /= s[k];
}
a[k][k] += 1;
}
s[k] = -s[k];
}
for (j = k + 1; j < n; j++) {
if (k < nct && s[k] !== 0) {
t = 0;
for (i = k; i < m; i++) {
t += a[i][k] * a[i][j];
}
t = -t / a[k][k];
for (i = k; i < m; i++) {
a[i][j] += t * a[i][k];
}
}
e[j] = a[k][j];
}
if (wantu && k < nct) {
for (i = k; i < m; i++) {
U[i][k] = a[i][k];
}
}
if (k < nrt) {
e[k] = 0;
for (i = k + 1; i < n; i++) {
e[k] = hypotenuse(e[k], e[i]);
}
if (e[k] !== 0) {
if (e[k + 1] < 0) {
e[k] = 0 - e[k];
}
for (i = k + 1; i < n; i++) {
e[i] /= e[k];
}
e[k + 1] += 1;
}
e[k] = -e[k];
if (k + 1 < m && e[k] !== 0) {
for (i = k + 1; i < m; i++) {
work[i] = 0;
}
for (j = k + 1; j < n; j++) {
for (i = k + 1; i < m; i++) {
work[i] += e[j] * a[i][j];
}
}
for (j = k + 1; j < n; j++) {
t = -e[j] / e[k + 1];
for (i = k + 1; i < m; i++) {
a[i][j] += t * work[i];
}
}
}
if (wantv) {
for (i = k + 1; i < n; i++) {
V[i][k] = e[i];
}
}
}
}
p = Math.min(n, m + 1);
if (nct < n) {
s[nct] = a[nct][nct];
}
if (m < p) {
s[p - 1] = 0;
}
if (nrt + 1 < p) {
e[nrt] = a[nrt][p - 1];
}
e[p - 1] = 0;
if (wantu) {
for (j = nct; j < nu; j++) {
for (i = 0; i < m; i++) {
U[i][j] = 0;
}
U[j][j] = 1;
}
for (k = nct - 1; k >= 0; k--) {
if (s[k] !== 0) {
for (j = k + 1; j < nu; j++) {
t = 0;
for (i = k; i < m; i++) {
t += U[i][k] * U[i][j];
}
t = -t / U[k][k];
for (i = k; i < m; i++) {
U[i][j] += t * U[i][k];
}
}
for (i = k; i < m; i++) {
U[i][k] = -U[i][k];
}
U[k][k] = 1 + U[k][k];
for (i = 0; i < k - 1; i++) {
U[i][k] = 0;
}
} else {
for (i = 0; i < m; i++) {
U[i][k] = 0;
}
U[k][k] = 1;
}
}
}
if (wantv) {
for (k = n - 1; k >= 0; k--) {
if (k < nrt && e[k] !== 0) {
for (j = k + 1; j < n; j++) {
t = 0;
for (i = k + 1; i < n; i++) {
t += V[i][k] * V[i][j];
}
t = -t / V[k + 1][k];
for (i = k + 1; i < n; i++) {
V[i][j] += t * V[i][k];
}
}
}
for (i = 0; i < n; i++) {
V[i][k] = 0;
}
V[k][k] = 1;
}
}
var pp = p - 1,
iter = 0,
eps = Math.pow(2, -52);
while (p > 0) {
for (k = p - 2; k >= -1; k--) {
if (k === -1) {
break;
}
if (Math.abs(e[k]) <= eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) {
e[k] = 0;
break;
}
}
if (k === p - 2) {
kase = 4;
} else {
for (ks = p - 1; ks >= k; ks--) {
if (ks === k) {
break;
}
t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);
if (Math.abs(s[ks]) <= eps * t) {
s[ks] = 0;
break;
}
}
if (ks === k) {
kase = 3;
} else if (ks === p - 1) {
kase = 1;
} else {
kase = 2;
k = ks;
}
}
k++;
switch (kase) {
case 1:
{
f = e[p - 2];
e[p - 2] = 0;
for (j = p - 2; j >= k; j--) {
t = hypotenuse(s[j], f);
cs = s[j] / t;
sn = f / t;
s[j] = t;
if (j !== k) {
f = -sn * e[j - 1];
e[j - 1] = cs * e[j - 1];
}
if (wantv) {
for (i = 0; i < n; i++) {
t = cs * V[i][j] + sn * V[i][p - 1];
V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1];
V[i][j] = t;
}
}
}
break;
}
case 2:
{
f = e[k - 1];
e[k - 1] = 0;
for (j = k; j < p; j++) {
t = hypotenuse(s[j], f);
cs = s[j] / t;
sn = f / t;
s[j] = t;
f = -sn * e[j];
e[j] = cs * e[j];
if (wantu) {
for (i = 0; i < m; i++) {
t = cs * U[i][j] + sn * U[i][k - 1];
U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1];
U[i][j] = t;
}
}
}
break;
}
case 3:
{
scale = Math.max(Math.max(Math.max(Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2])), Math.abs(e[p - 2])), Math.abs(s[k])), Math.abs(e[k]));
sp = s[p - 1] / scale;
spm1 = s[p - 2] / scale;
epm1 = e[p - 2] / scale;
sk = s[k] / scale;
ek = e[k] / scale;
b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;
c = sp * epm1 * (sp * epm1);
shift = 0;
if (b !== 0 || c !== 0) {
shift = Math.sqrt(b * b + c);
if (b < 0) {
shift = -shift;
}
shift = c / (b + shift);
}
f = (sk + sp) * (sk - sp) + shift;
g = sk * ek;
for (j = k; j < p - 1; j++) {
t = hypotenuse(f, g);
cs = f / t;
sn = g / t;
if (j !== k) {
e[j - 1] = t;
}
f = cs * s[j] + sn * e[j];
e[j] = cs * e[j] - sn * s[j];
g = sn * s[j + 1];
s[j + 1] = cs * s[j + 1];
if (wantv) {
for (i = 0; i < n; i++) {
t = cs * V[i][j] + sn * V[i][j + 1];
V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1];
V[i][j] = t;
}
}
t = hypotenuse(f, g);
cs = f / t;
sn = g / t;
s[j] = t;
f = cs * e[j] + sn * s[j + 1];
s[j + 1] = -sn * e[j] + cs * s[j + 1];
g = sn * e[j + 1];
e[j + 1] = cs * e[j + 1];
if (wantu && j < m - 1) {
for (i = 0; i < m; i++) {
t = cs * U[i][j] + sn * U[i][j + 1];
U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1];
U[i][j] = t;
}
}
}
e[p - 2] = f;
iter = iter + 1;
break;
}
case 4:
{
if (s[k] <= 0) {
s[k] = s[k] < 0 ? -s[k] : 0;
if (wantv) {
for (i = 0; i <= pp; i++) {
V[i][k] = -V[i][k];
}
}
}
while (k < pp) {
if (s[k] >= s[k + 1]) {
break;
}
t = s[k];
s[k] = s[k + 1];
s[k + 1] = t;
if (wantv && k < n - 1) {
for (i = 0; i < n; i++) {
t = V[i][k + 1];
V[i][k + 1] = V[i][k];
V[i][k] = t;
}
}
if (wantu && k < m - 1) {
for (i = 0; i < m; i++) {
t = U[i][k + 1];
U[i][k + 1] = U[i][k];
U[i][k] = t;
}
}
k++;
}
iter = 0;
p--;
break;
}
// no default
}
}
if (swapped) {
var tmp = V;
V = U;
U = tmp;
}
this.m = m;
this.n = n;
this.s = s;
this.U = U;
this.V = V;
}
SingularValueDecomposition.prototype = {
get condition() {
return this.s[0] / this.s[Math.min(this.m, this.n) - 1];
},
get norm2() {
return this.s[0];
},
get rank() {
var eps = Math.pow(2, -52),
tol = Math.max(this.m, this.n) * this.s[0] * eps,
r = 0,
s = this.s;
for (var i = 0, ii = s.length; i < ii; i++) {
if (s[i] > tol) {
r++;
}
}
return r;
},
get diagonal() {
return this.s;
},
// https://github.com/accord-net/framework/blob/development/Sources/Accord.Math/Decompositions/SingularValueDecomposition.cs
get threshold() {
return Math.pow(2, -52) / 2 * Math.max(this.m, this.n) * this.s[0];
},
get leftSingularVectors() {
if (!Matrix.Matrix.isMatrix(this.U)) {
this.U = new Matrix.Matrix(this.U);
}
return this.U;
},
get rightSingularVectors() {
if (!Matrix.Matrix.isMatrix(this.V)) {
this.V = new Matrix.Matrix(this.V);
}
return this.V;
},
get diagonalMatrix() {
return Matrix.Matrix.diag(this.s);
},
solve: function solve(value) {
var Y = value,
e = this.threshold,
scols = this.s.length,
Ls = Matrix.Matrix.zeros(scols, scols),
i;
for (i = 0; i < scols; i++) {
if (Math.abs(this.s[i]) <= e) {
Ls[i][i] = 0;
} else {
Ls[i][i] = 1 / this.s[i];
}
}
var U = this.U;
var V = this.rightSingularVectors;
var VL = V.mmul(Ls),
vrows = V.rows,
urows = U.length,
VLU = Matrix.Matrix.zeros(vrows, urows),
j,
k,
sum;
for (i = 0; i < vrows; i++) {
for (j = 0; j < urows; j++) {
sum = 0;
for (k = 0; k < scols; k++) {
sum += VL[i][k] * U[j][k];
}
VLU[i][j] = sum;
}
}
return VLU.mmul(Y);
},
solveForDiagonal: function solveForDiagonal(value) {
return this.solve(Matrix.Matrix.diag(value));
},
inverse: function inverse() {
var V = this.V;
var e = this.threshold,
vrows = V.length,
vcols = V[0].length,
X = new Matrix.Matrix(vrows, this.s.length),
i,
j;
for (i = 0; i < vrows; i++) {
for (j = 0; j < vcols; j++) {
if (Math.abs(this.s[j]) > e) {
X[i][j] = V[i][j] / this.s[j];
} else {
X[i][j] = 0;
}
}
}
var U = this.U;
var urows = U.length,
ucols = U[0].length,
Y = new Matrix.Matrix(vrows, urows),
k,
sum;
for (i = 0; i < vrows; i++) {
for (j = 0; j < urows; j++) {
sum = 0;
for (k = 0; k < ucols; k++) {
sum += X[i][k] * U[j][k];
}
Y[i][j] = sum;
}
}
return Y;
}
};
module.exports = SingularValueDecomposition;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Created by acastillo on 8/24/15.
*/
/**
* Non in-place function definitions, compatible with mathjs code *
*/
var Matrix = __webpack_require__(0);
function matrix(A, B) {
return new Matrix(A, B);
}
function ones(rows, cols) {
return Matrix.ones(rows, cols);
}
function eye(rows, cols) {
return Matrix.eye(rows, cols);
}
function zeros(rows, cols) {
return Matrix.zeros(rows, cols);
}
function random(rows, cols) {
return Matrix.rand(rows, cols);
}
function transpose(A) {
if (typeof A == 'number') return A;
var result = A.clone();
return result.transpose();
}
function add(A, B) {
if (typeof A == 'number' && typeof B === 'number') return A + B;
if (typeof A == 'number') return this.add(B, A);
var result = A.clone();
return result.add(B);
}
function subtract(A, B) {
if (typeof A == 'number' && typeof B === 'number') return A - B;
if (typeof A == 'number') return this.subtract(B, A);
var result = A.clone();
return result.sub(B);
}
function multiply(A, B) {
if (typeof A == 'number' && typeof B === 'number') return A * B;
if (typeof A == 'number') return this.multiply(B, A);
var result = A.clone();
if (typeof B === 'number') result.mul(B);else result = result.mmul(B);
if (result.rows == 1 && result.columns == 1) return result[0][0];else return result;
}
function dotMultiply(A, B) {
var result = A.clone();
return result.mul(B);
}
function dotDivide(A, B) {
var result = A.clone();
return result.div(B);
}
function diag(A) {
var diag = null;
var rows = A.rows,
cols = A.columns,
j,
r; //It is an array
if (typeof cols === "undefined" && typeof A == 'object') {
if (A[0] && A[0].length) {
rows = A.length;
cols = A[0].length;
r = Math.min(rows, cols);
diag = Matrix.zeros(cols, cols);
for (j = 0; j < cols; j++) {
diag[j][j] = A[j][j];
}
} else {
cols = A.length;
diag = Matrix.zeros(cols, cols);
for (j = 0; j < cols; j++) {
diag[j][j] = A[j];
}
}
}
if (rows == 1) {
diag = Matrix.zeros(cols, cols);
for (j = 0; j < cols; j++) {
diag[j][j] = A[0][j];
}
} else {
if (rows > 0 && cols > 0) {
r = Math.min(rows, cols);
diag = new Array(r);
for (j = 0; j < r; j++) {
diag[j] = A[j][j];
}
}
}
return diag;
}
function min(A, B) {
if (typeof A === 'number' && typeof B === 'number') return Math.min(A, B);
var ii = A.rows,
jj = A.columns;
var result = new Matrix(ii, jj);
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
if (A[i][j] < B[i][j]) {
result[i][j] = A[i][j];
} else {
result[i][j] = B[i][j];
}
}
}
return result;
}
function max(A, B) {
if (typeof A === 'number' && typeof B === 'number') return Math.max(A, B);
var ii = A.rows,
jj = A.columns;
var result = new Matrix(ii, jj);
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
if (A[i][j] > B[i][j]) {
result[i][j] = A[i][j];
} else {
result[i][j] = B[i][j];
}
}
}
return result;
}
function sqrt(A) {
if (typeof A === 'number') return Math.sqrt(A);
var ii = A.rows,
jj = A.columns;
var result = new Matrix(ii, jj);
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
result[i][j] = Math.sqrt(A[i][j]);
}
}
return result;
}
function abs(A) {
if (typeof A === 'number') return Math.abs(A);
var ii = A.rows,
jj = A.columns;
var result = new Matrix(ii, jj);
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
result[i][j] = Math.abs(A[i][j]);
}
}
return result;
}
function exp(A) {
if (typeof A === 'number') return Math.sqrt(A);
var ii = A.rows,
jj = A.columns;
var result = new Matrix(ii, jj);
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
result[i][j] = Math.exp(A[i][j]);
}
}
return result;
}
function dotPow(A, b) {
if (typeof A === 'number') return Math.pow(A, b); //console.log(A);
var ii = A.rows,
jj = A.columns;
var result = new Matrix(ii, jj);
for (var i = 0; i < ii; i++) {
for (var j = 0; j < jj; j++) {
result[i][j] = Math.pow(A[i][j], b);
}
}
return result;
}
function solve(A, B) {
return A.solve(B);
}
function inv(A) {
if (typeof A === "number") return 1 / A;
return A.inverse();
}
module.exports = {
transpose: transpose,
add: add,
subtract: subtract,
multiply: multiply,
dotMultiply: dotMultiply,
dotDivide: dotDivide,
diag: diag,
min: min,
max: max,
solve: solve,
inv: inv,
sqrt: sqrt,
exp: exp,
dotPow: dotPow,
abs: abs,
matrix: matrix,
ones: ones,
zeros: zeros,
random: random,
eye: eye
};
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(92);
var ieee754 = __webpack_require__(93);
var isArray = __webpack_require__(94);
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 foo() {
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.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__(22)))
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It isn't worth it to make additional optimizations as in original.
// Small size is preferable.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function adler32(adler, buf, len, pos) {
var s1 = adler & 0xffff | 0,
s2 = adler >>> 16 & 0xffff | 0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = s1 + buf[pos++] | 0;
s2 = s2 + s1 | 0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return s1 | s2 << 16 | 0;
}
module.exports = adler32;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c,
table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
}
table[n] = c;
}
return table;
} // Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc ^= -1;
for (var i = pos; i < end; i++) {
crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF];
}
return crc ^ -1; // >>> 0;
}
module.exports = crc32;
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// String encode/decode helpers
var utils = __webpack_require__(5); // Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safari
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try {
String.fromCharCode.apply(null, [0]);
} catch (__) {
STR_APPLY_OK = false;
}
try {
String.fromCharCode.apply(null, new Uint8Array(1));
} catch (__) {
STR_APPLY_UIA_OK = false;
} // Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q = 0; q < 256; q++) {
_utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1;
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf,
c,
c2,
m_pos,
i,
str_len = str.length,
buf_len = 0; // count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
} // allocate buffer
buf = new utils.Buf8(buf_len); // convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | c >>> 6;
buf[i++] = 0x80 | c & 0x3f;
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | c >>> 12;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
} else {
/* four bytes */
buf[i++] = 0xf0 | c >>> 18;
buf[i++] = 0x80 | c >>> 12 & 0x3f;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
}
}
return buf;
}; // Helper (used in 2 places)
function buf2binstring(buf, len) {
// On Chrome, the arguments in a function call that are allowed is `65534`.
// If the length of the buffer is smaller than that, we can use this optimization,
// otherwise we will take a slower path.
if (len < 65534) {
if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
} // Convert byte array to binary string
exports.buf2binstring = function (buf) {
return buf2binstring(buf, buf.length);
}; // Convert binary string (typed, when possible)
exports.binstring2buf = function (str) {
var buf = new utils.Buf8(str.length);
for (var i = 0, len = buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
}; // convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length; // Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
c = buf[i++]; // quick process ascii
if (c < 0x80) {
utf16buf[out++] = c;
continue;
}
c_len = _utf8len[c]; // skip 5 & 6 byte codes
if (c_len > 4) {
utf16buf[out++] = 0xfffd;
i += c_len - 1;
continue;
} // apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest
while (c_len > 1 && i < len) {
c = c << 6 | buf[i++] & 0x3f;
c_len--;
} // terminated by end of string?
if (c_len > 1) {
utf16buf[out++] = 0xfffd;
continue;
}
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;
utf16buf[out++] = 0xdc00 | c & 0x3ff;
}
}
return buf2binstring(utf16buf, out);
}; // Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function (buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) {
max = buf.length;
} // go back from last position, until start of sequence found
pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {
pos--;
} // Very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) {
return max;
} // If we came to start of buffer - that means buffer is too small,
// return max too.
if (pos === 0) {
return max;
}
return pos + _utf8len[buf[pos]] > max ? pos : max;
};
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''
/*Z_NULL*/
;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2
/*Z_UNKNOWN*/
;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// (C) 1995-2013 Jean-loup Gailly and Mark Adler
// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type
};
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.LOCAL_FILE_HEADER = "PK\x03\x04";
exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
exports.DATA_DESCRIPTOR = "PK\x07\x08";
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.base64 = false;
exports.binary = false;
exports.dir = false;
exports.createFolders = false;
exports.date = null;
exports.compression = null;
exports.compressionOptions = null;
exports.comment = null;
exports.unixPermissions = null;
exports.dosPermissions = null;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function CompressedObject() {
this.compressedSize = 0;
this.uncompressedSize = 0;
this.crc32 = 0;
this.compressionMethod = null;
this.compressedContent = null;
}
CompressedObject.prototype = {
/**
* Return the decompressed content in an unspecified format.
* The format will depend on the decompressor.
* @return {Object} the decompressed content.
*/
getContent: function getContent() {
return null; // see implementation
},
/**
* Return the compressed content in an unspecified format.
* The format will depend on the compressed conten source.
* @return {Object} the compressed content.
*/
getCompressedContent: function getCompressedContent() {
return null; // see implementation
}
};
module.exports = CompressedObject;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(2);
var support = __webpack_require__(10);
var nodeBuffer = __webpack_require__(25);
/**
* The following functions come from pako, from pako/lib/utils/strings
* released under the MIT license, see pako https://github.com/nodeca/pako/
*/
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new Array(256);
for (var i = 0; i < 256; i++) {
_utf8len[i] = i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1;
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
var string2buf = function string2buf(str) {
var buf,
c,
c2,
m_pos,
i,
str_len = str.length,
buf_len = 0; // count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
} // allocate buffer
if (support.uint8array) {
buf = new Uint8Array(buf_len);
} else {
buf = new Array(buf_len);
} // convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | c >>> 6;
buf[i++] = 0x80 | c & 0x3f;
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | c >>> 12;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
} else {
/* four bytes */
buf[i++] = 0xf0 | c >>> 18;
buf[i++] = 0x80 | c >>> 12 & 0x3f;
buf[i++] = 0x80 | c >>> 6 & 0x3f;
buf[i++] = 0x80 | c & 0x3f;
}
}
return buf;
}; // Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
var utf8border = function utf8border(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) {
max = buf.length;
} // go back from last position, until start of sequence found
pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) {
pos--;
} // Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) {
return max;
} // If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) {
return max;
}
return pos + _utf8len[buf[pos]] > max ? pos : max;
}; // convert array to string
var buf2string = function buf2string(buf) {
var str, i, out, c, c_len;
var len = buf.length; // Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
c = buf[i++]; // quick process ascii
if (c < 0x80) {
utf16buf[out++] = c;
continue;
}
c_len = _utf8len[c]; // skip 5 & 6 byte codes
if (c_len > 4) {
utf16buf[out++] = 0xfffd;
i += c_len - 1;
continue;
} // apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest
while (c_len > 1 && i < len) {
c = c << 6 | buf[i++] & 0x3f;
c_len--;
} // terminated by end of string?
if (c_len > 1) {
utf16buf[out++] = 0xfffd;
continue;
}
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff;
utf16buf[out++] = 0xdc00 | c & 0x3ff;
}
} // shrinkBuf(utf16buf, out)
if (utf16buf.length !== out) {
if (utf16buf.subarray) {
utf16buf = utf16buf.subarray(0, out);
} else {
utf16buf.length = out;
}
} // return String.fromCharCode.apply(null, utf16buf);
return utils.applyFromCharCode(utf16buf);
}; // That's all for the pako functions.
/**
* Transform a javascript string into an array (typed if possible) of bytes,
* UTF-8 encoded.
* @param {String} str the string to encode
* @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
*/
exports.utf8encode = function utf8encode(str) {
if (support.nodebuffer) {
return nodeBuffer(str, "utf-8");
}
return string2buf(str);
};
/**
* Transform a bytes array (or a representation) representing an UTF-8 encoded
* string into a javascript string.
* @param {Array|Uint8Array|Buffer} buf the data de decode
* @return {String} the decoded string.
*/
exports.utf8decode = function utf8decode(buf) {
if (support.nodebuffer) {
return utils.transformTo("nodebuffer", buf).toString("utf-8");
}
buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); // return buf2string(buf);
// Chrome prefers to work with "small" chunks of data
// for the method buf2string.
// Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
var result = [],
k = 0,
len = buf.length,
chunk = 65536;
while (k < len) {
var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
if (support.uint8array) {
result.push(buf2string(buf.subarray(k, nextBoundary)));
} else {
result.push(buf2string(buf.slice(k, nextBoundary)));
}
k = nextBoundary;
}
return result.join("");
}; // vim: set shiftwidth=4 softtabstop=4:
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var DataReader = __webpack_require__(50);
var utils = __webpack_require__(2);
function StringReader(data, optimizedBinaryString) {
this.data = data;
if (!optimizedBinaryString) {
this.data = utils.string2binary(this.data);
}
this.length = this.data.length;
this.index = 0;
this.zero = 0;
}
StringReader.prototype = new DataReader();
/**
* @see DataReader.byteAt
*/
StringReader.prototype.byteAt = function (i) {
return this.data.charCodeAt(this.zero + i);
};
/**
* @see DataReader.lastIndexOfSignature
*/
StringReader.prototype.lastIndexOfSignature = function (sig) {
return this.data.lastIndexOf(sig) - this.zero;
};
/**
* @see DataReader.readData
*/
StringReader.prototype.readData = function (size) {
this.checkOffset(size); // this will work because the constructor applied the "& 0xff" mask.
var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
this.index += size;
return result;
};
module.exports = StringReader;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(2);
function DataReader(data) {
this.data = null; // type : see implementation
this.length = 0;
this.index = 0;
this.zero = 0;
}
DataReader.prototype = {
/**
* Check that the offset will not go too far.
* @param {string} offset the additional offset to check.
* @throws {Error} an Error if the offset is out of bounds.
*/
checkOffset: function checkOffset(offset) {
this.checkIndex(this.index + offset);
},
/**
* Check that the specifed index will not be too far.
* @param {string} newIndex the index to check.
* @throws {Error} an Error if the index is out of bounds.
*/
checkIndex: function checkIndex(newIndex) {
if (this.length < this.zero + newIndex || newIndex < 0) {
throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?");
}
},
/**
* Change the index.
* @param {number} newIndex The new index.
* @throws {Error} if the new index is out of the data.
*/
setIndex: function setIndex(newIndex) {
this.checkIndex(newIndex);
this.index = newIndex;
},
/**
* Skip the next n bytes.
* @param {number} n the number of bytes to skip.
* @throws {Error} if the new index is out of the data.
*/
skip: function skip(n) {
this.setIndex(this.index + n);
},
/**
* Get the byte at the specified index.
* @param {number} i the index to use.
* @return {number} a byte.
*/
byteAt: function byteAt(i) {// see implementations
},
/**
* Get the next number with a given byte size.
* @param {number} size the number of bytes to read.
* @return {number} the corresponding number.
*/
readInt: function readInt(size) {
var result = 0,
i;
this.checkOffset(size);
for (i = this.index + size - 1; i >= this.index; i--) {
result = (result << 8) + this.byteAt(i);
}
this.index += size;
return result;
},
/**
* Get the next string with a given byte size.
* @param {number} size the number of bytes to read.
* @return {string} the corresponding string.
*/
readString: function readString(size) {
return utils.transformTo("string", this.readData(size));
},
/**
* Get raw data without conversion, bytes.
* @param {number} size the number of bytes to read.
* @return {Object} the raw data, implementation specific.
*/
readData: function readData(size) {// see implementations
},
/**
* Find the last occurence of a zip signature (4 bytes).
* @param {string} sig the signature to find.
* @return {number} the index of the last occurence, -1 if not found.
*/
lastIndexOfSignature: function lastIndexOfSignature(sig) {// see implementations
},
/**
* Get the next date.
* @return {Date} the date.
*/
readDate: function readDate() {
var dostime = this.readInt(4);
return new Date((dostime >> 25 & 0x7f) + 1980, // year
(dostime >> 21 & 0x0f) - 1, // month
dostime >> 16 & 0x1f, // day
dostime >> 11 & 0x1f, // hour
dostime >> 5 & 0x3f, // minute
(dostime & 0x1f) << 1); // second
}
};
module.exports = DataReader;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayReader = __webpack_require__(52);
function Uint8ArrayReader(data) {
if (data) {
this.data = data;
this.length = this.data.length;
this.index = 0;
this.zero = 0;
}
}
Uint8ArrayReader.prototype = new ArrayReader();
/**
* @see DataReader.readData
*/
Uint8ArrayReader.prototype.readData = function (size) {
this.checkOffset(size);
if (size === 0) {
// in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
return new Uint8Array(0);
}
var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
this.index += size;
return result;
};
module.exports = Uint8ArrayReader;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var DataReader = __webpack_require__(50);
function ArrayReader(data) {
if (data) {
this.data = data;
this.length = this.data.length;
this.index = 0;
this.zero = 0;
for (var i = 0; i < this.data.length; i++) {
data[i] = data[i] & 0xFF;
}
}
}
ArrayReader.prototype = new DataReader();
/**
* @see DataReader.byteAt
*/
ArrayReader.prototype.byteAt = function (i) {
return this.data[this.zero + i];
};
/**
* @see DataReader.lastIndexOfSignature
*/
ArrayReader.prototype.lastIndexOfSignature = function (sig) {
var sig0 = sig.charCodeAt(0),
sig1 = sig.charCodeAt(1),
sig2 = sig.charCodeAt(2),
sig3 = sig.charCodeAt(3);
for (var i = this.length - 4; i >= 0; --i) {
if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
return i - this.zero;
}
}
return -1;
};
/**
* @see DataReader.readData
*/
ArrayReader.prototype.readData = function (size) {
this.checkOffset(size);
if (size === 0) {
return [];
}
var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);
this.index += size;
return result;
};
module.exports = ArrayReader;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function squaredEuclidean(p, q) {
var d = 0;
for (var i = 0; i < p.length; i++) {
d += (p[i] - q[i]) * (p[i] - q[i]);
}
return d;
}
function euclidean(p, q) {
return Math.sqrt(squaredEuclidean(p, q));
}
module.exports = euclidean;
euclidean.squared = squaredEuclidean;
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const Cluster = __webpack_require__(26);
const util = __webpack_require__(116);
function ClusterLeaf(index) {
Cluster.call(this);
this.index = index;
this.distance = 0;
this.children = [];
}
util.inherits(ClusterLeaf, Cluster);
module.exports = ClusterLeaf;
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Fast Fourier Transform module
* 1D-FFT/IFFT, 2D-FFT/IFFT (radix-2)
*/
var FFT = function () {
var FFT;
if (true) {
FFT = exports; // for CommonJS
} else {}
var version = {
release: '0.3.0',
date: '2013-03'
};
FFT.toString = function () {
return "version " + version.release + ", released " + version.date;
}; // core operations
var _n = 0,
// order
_bitrev = null,
// bit reversal table
_cstb = null; // sin/cos table
var core = {
init: function init(n) {
if (n !== 0 && (n & n - 1) === 0) {
_n = n;
core._initArray();
core._makeBitReversalTable();
core._makeCosSinTable();
} else {
throw new Error("init: radix-2 required");
}
},
// 1D-FFT
fft1d: function fft1d(re, im) {
core.fft(re, im, 1);
},
// 1D-IFFT
ifft1d: function ifft1d(re, im) {
var n = 1 / _n;
core.fft(re, im, -1);
for (var i = 0; i < _n; i++) {
re[i] *= n;
im[i] *= n;
}
},
// 1D-IFFT
bt1d: function bt1d(re, im) {
core.fft(re, im, -1);
},
// 2D-FFT Not very useful if the number of rows have to be equal to cols
fft2d: function fft2d(re, im) {
var tre = [],
tim = [],
i = 0; // x-axis
for (var y = 0; y < _n; y++) {
i = y * _n;
for (var x1 = 0; x1 < _n; x1++) {
tre[x1] = re[x1 + i];
tim[x1] = im[x1 + i];
}
core.fft1d(tre, tim);
for (var x2 = 0; x2 < _n; x2++) {
re[x2 + i] = tre[x2];
im[x2 + i] = tim[x2];
}
} // y-axis
for (var x = 0; x < _n; x++) {
for (var y1 = 0; y1 < _n; y1++) {
i = x + y1 * _n;
tre[y1] = re[i];
tim[y1] = im[i];
}
core.fft1d(tre, tim);
for (var y2 = 0; y2 < _n; y2++) {
i = x + y2 * _n;
re[i] = tre[y2];
im[i] = tim[y2];
}
}
},
// 2D-IFFT
ifft2d: function ifft2d(re, im) {
var tre = [],
tim = [],
i = 0; // x-axis
for (var y = 0; y < _n; y++) {
i = y * _n;
for (var x1 = 0; x1 < _n; x1++) {
tre[x1] = re[x1 + i];
tim[x1] = im[x1 + i];
}
core.ifft1d(tre, tim);
for (var x2 = 0; x2 < _n; x2++) {
re[x2 + i] = tre[x2];
im[x2 + i] = tim[x2];
}
} // y-axis
for (var x = 0; x < _n; x++) {
for (var y1 = 0; y1 < _n; y1++) {
i = x + y1 * _n;
tre[y1] = re[i];
tim[y1] = im[i];
}
core.ifft1d(tre, tim);
for (var y2 = 0; y2 < _n; y2++) {
i = x + y2 * _n;
re[i] = tre[y2];
im[i] = tim[y2];
}
}
},
// core operation of FFT
fft: function fft(re, im, inv) {
var d,
h,
ik,
m,
tmp,
wr,
wi,
xr,
xi,
n4 = _n >> 2; // bit reversal
for (var l = 0; l < _n; l++) {
m = _bitrev[l];
if (l < m) {
tmp = re[l];
re[l] = re[m];
re[m] = tmp;
tmp = im[l];
im[l] = im[m];
im[m] = tmp;
}
} // butterfly operation
for (var k = 1; k < _n; k <<= 1) {
h = 0;
d = _n / (k << 1);
for (var j = 0; j < k; j++) {
wr = _cstb[h + n4];
wi = inv * _cstb[h];
for (var i = j; i < _n; i += k << 1) {
ik = i + k;
xr = wr * re[ik] + wi * im[ik];
xi = wr * im[ik] - wi * re[ik];
re[ik] = re[i] - xr;
re[i] += xr;
im[ik] = im[i] - xi;
im[i] += xi;
}
h += d;
}
}
},
// initialize the array (supports TypedArray)
_initArray: function _initArray() {
if (typeof Uint32Array !== 'undefined') {
_bitrev = new Uint32Array(_n);
} else {
_bitrev = [];
}
if (typeof Float64Array !== 'undefined') {
_cstb = new Float64Array(_n * 1.25);
} else {
_cstb = [];
}
},
// zero padding
_paddingZero: function _paddingZero() {// TODO
},
// makes bit reversal table
_makeBitReversalTable: function _makeBitReversalTable() {
var i = 0,
j = 0,
k = 0;
_bitrev[0] = 0;
while (++i < _n) {
k = _n >> 1;
while (k <= j) {
j -= k;
k >>= 1;
}
j += k;
_bitrev[i] = j;
}
},
// makes trigonometiric function table
_makeCosSinTable: function _makeCosSinTable() {
var n2 = _n >> 1,
n4 = _n >> 2,
n8 = _n >> 3,
n2p4 = n2 + n4,
t = Math.sin(Math.PI / _n),
dc = 2 * t * t,
ds = Math.sqrt(dc * (2 - dc)),
c = _cstb[n4] = 1,
s = _cstb[0] = 0;
t = 2 * dc;
for (var i = 1; i < n8; i++) {
c -= dc;
dc += t * c;
s += ds;
ds -= t * s;
_cstb[i] = s;
_cstb[n4 - i] = c;
}
if (n8 !== 0) {
_cstb[n8] = Math.sqrt(0.5);
}
for (var j = 0; j < n4; j++) {
_cstb[n2 - j] = _cstb[j];
}
for (var k = 0; k < n2p4; k++) {
_cstb[k + n2] = -_cstb[k];
}
}
}; // aliases (public APIs)
var apis = ['init', 'fft1d', 'ifft1d', 'fft2d', 'ifft2d'];
for (var i = 0; i < apis.length; i++) {
FFT[apis[i]] = core[apis[i]];
}
FFT.bt = core.bt1d;
FFT.fft = core.fft1d;
FFT.ifft = core.ifft1d;
return FFT;
}.call(this);
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Fast Fourier Transform module
* 1D-FFT/IFFT, 2D-FFT/IFFT (radix-2)
*/
var FFT = function () {
var FFT;
if (true) {
FFT = exports; // for CommonJS
} else {}
var version = {
release: '0.3.0',
date: '2013-03'
};
FFT.toString = function () {
return "version " + version.release + ", released " + version.date;
}; // core operations
var _n = 0,
// order
_bitrev = null,
// bit reversal table
_cstb = null; // sin/cos table
var core = {
init: function init(n) {
if (n !== 0 && (n & n - 1) === 0) {
_n = n;
core._initArray();
core._makeBitReversalTable();
core._makeCosSinTable();
} else {
throw new Error("init: radix-2 required");
}
},
// 1D-FFT
fft1d: function fft1d(re, im) {
core.fft(re, im, 1);
},
// 1D-IFFT
ifft1d: function ifft1d(re, im) {
var n = 1 / _n;
core.fft(re, im, -1);
for (var i = 0; i < _n; i++) {
re[i] *= n;
im[i] *= n;
}
},
// 1D-IFFT
bt1d: function bt1d(re, im) {
core.fft(re, im, -1);
},
// 2D-FFT Not very useful if the number of rows have to be equal to cols
fft2d: function fft2d(re, im) {
var tre = [],
tim = [],
i = 0; // x-axis
for (var y = 0; y < _n; y++) {
i = y * _n;
for (var x1 = 0; x1 < _n; x1++) {
tre[x1] = re[x1 + i];
tim[x1] = im[x1 + i];
}
core.fft1d(tre, tim);
for (var x2 = 0; x2 < _n; x2++) {
re[x2 + i] = tre[x2];
im[x2 + i] = tim[x2];
}
} // y-axis
for (var x = 0; x < _n; x++) {
for (var y1 = 0; y1 < _n; y1++) {
i = x + y1 * _n;
tre[y1] = re[i];
tim[y1] = im[i];
}
core.fft1d(tre, tim);
for (var y2 = 0; y2 < _n; y2++) {
i = x + y2 * _n;
re[i] = tre[y2];
im[i] = tim[y2];
}
}
},
// 2D-IFFT
ifft2d: function ifft2d(re, im) {
var tre = [],
tim = [],
i = 0; // x-axis
for (var y = 0; y < _n; y++) {
i = y * _n;
for (var x1 = 0; x1 < _n; x1++) {
tre[x1] = re[x1 + i];
tim[x1] = im[x1 + i];
}
core.ifft1d(tre, tim);
for (var x2 = 0; x2 < _n; x2++) {
re[x2 + i] = tre[x2];
im[x2 + i] = tim[x2];
}
} // y-axis
for (var x = 0; x < _n; x++) {
for (var y1 = 0; y1 < _n; y1++) {
i = x + y1 * _n;
tre[y1] = re[i];
tim[y1] = im[i];
}
core.ifft1d(tre, tim);
for (var y2 = 0; y2 < _n; y2++) {
i = x + y2 * _n;
re[i] = tre[y2];
im[i] = tim[y2];
}
}
},
// core operation of FFT
fft: function fft(re, im, inv) {
var d,
h,
ik,
m,
tmp,
wr,
wi,
xr,
xi,
n4 = _n >> 2; // bit reversal
for (var l = 0; l < _n; l++) {
m = _bitrev[l];
if (l < m) {
tmp = re[l];
re[l] = re[m];
re[m] = tmp;
tmp = im[l];
im[l] = im[m];
im[m] = tmp;
}
} // butterfly operation
for (var k = 1; k < _n; k <<= 1) {
h = 0;
d = _n / (k << 1);
for (var j = 0; j < k; j++) {
wr = _cstb[h + n4];
wi = inv * _cstb[h];
for (var i = j; i < _n; i += k << 1) {
ik = i + k;
xr = wr * re[ik] + wi * im[ik];
xi = wr * im[ik] - wi * re[ik];
re[ik] = re[i] - xr;
re[i] += xr;
im[ik] = im[i] - xi;
im[i] += xi;
}
h += d;
}
}
},
// initialize the array (supports TypedArray)
_initArray: function _initArray() {
if (typeof Uint32Array !== 'undefined') {
_bitrev = new Uint32Array(_n);
} else {
_bitrev = [];
}
if (typeof Float64Array !== 'undefined') {
_cstb = new Float64Array(_n * 1.25);
} else {
_cstb = [];
}
},
// zero padding
_paddingZero: function _paddingZero() {// TODO
},
// makes bit reversal table
_makeBitReversalTable: function _makeBitReversalTable() {
var i = 0,
j = 0,
k = 0;
_bitrev[0] = 0;
while (++i < _n) {
k = _n >> 1;
while (k <= j) {
j -= k;
k >>= 1;
}
j += k;
_bitrev[i] = j;
}
},
// makes trigonometiric function table
_makeCosSinTable: function _makeCosSinTable() {
var n2 = _n >> 1,
n4 = _n >> 2,
n8 = _n >> 3,
n2p4 = n2 + n4,
t = Math.sin(Math.PI / _n),
dc = 2 * t * t,
ds = Math.sqrt(dc * (2 - dc)),
c = _cstb[n4] = 1,
s = _cstb[0] = 0;
t = 2 * dc;
for (var i = 1; i < n8; i++) {
c -= dc;
dc += t * c;
s += ds;
ds -= t * s;
_cstb[i] = s;
_cstb[n4 - i] = c;
}
if (n8 !== 0) {
_cstb[n8] = Math.sqrt(0.5);
}
for (var j = 0; j < n4; j++) {
_cstb[n2 - j] = _cstb[j];
}
for (var k = 0; k < n2p4; k++) {
_cstb[k + n2] = -_cstb[k];
}
}
}; // aliases (public APIs)
var apis = ['init', 'fft1d', 'ifft1d', 'fft2d', 'ifft2d'];
for (var i = 0; i < apis.length; i++) {
FFT[apis[i]] = core[apis[i]];
}
FFT.bt = core.bt1d;
FFT.fft = core.fft1d;
FFT.ifft = core.ifft1d;
return FFT;
}.call(this);
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
(function () {
function a(d) {
for (var e = 0, f = d.length - 1, g = void 0, h = void 0, i = void 0, j = c(e, f); !0;) {
if (f <= e) return d[j];
if (f == e + 1) return d[e] > d[f] && b(d, e, f), d[j];
for (g = c(e, f), d[g] > d[f] && b(d, g, f), d[e] > d[f] && b(d, e, f), d[g] > d[e] && b(d, g, e), b(d, g, e + 1), h = e + 1, i = f; !0;) {
do h++; while (d[e] > d[h]);
do i--; while (d[i] > d[e]);
if (i < h) break;
b(d, h, i);
}
b(d, e, i), i <= j && (e = h), i >= j && (f = i - 1);
}
}
var b = function b(d, e, f) {
var _ref;
return _ref = [d[f], d[e]], d[e] = _ref[0], d[f] = _ref[1], _ref;
},
c = function c(d, e) {
return ~~((d + e) / 2);
};
true && module.exports ? module.exports = a : window.median = a;
})();
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.agnes = __webpack_require__(113);
exports.diana = __webpack_require__(121); //exports.birch = require('./birch');
//exports.cure = require('./cure');
//exports.chameleon = require('./chameleon');
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const jcampconverter = __webpack_require__(14);
const SD = __webpack_require__(133);
const getSpectrumType = __webpack_require__(132);
/**
* Object containing parsed metadata
* @name NMRMetadata
* @typedef {object} NMRMetadata
* @property {number} dimension
* @property {number[]} nucleus
* @property {string} title
* @property {string} solvent
* @property {string} pulse
* @property {string} experiment
* @property {number} temperature - Temperature in Kelvin
* @property {number} frequency
* @property {string} probe
* @property {string} acquisitionMode
* @property {number} expno - Experience number
* @property {string} date - Date in ISO string format
* @property {object} ranges
*/
const defaultOptions = {
computeRanges: false
};
const defaultRangesOptions = {
nH: 100,
thresholdFactor: 0.85,
clean: 0.4,
compile: true,
integralType: 'sum'
};
/**
* Returns a metadata object from JCAMP
* @param {string} jcampData
* @param {object} [options]
* @param {boolean} [options.computeRanges=false]
* @param {number} [options.ranges] - options for ranges computation
* @return {NMRMetadata} metadata
*/
exports.parseJcamp = function (jcampData, options) {
options = Object.assign({}, defaultOptions, options);
const jcampString = jcampData.toString();
const jcamp = jcampconverter.convert(jcampString, {
keepRecordsRegExp: /.*/,
withoutXY: true
});
const metadata = {
dimension: jcamp.twoD ? 2 : 1,
nucleus: [],
isFid: false,
isFt: false
};
const info = jcamp.info;
maybeAdd(metadata, 'title', info['TITLE']);
maybeAdd(metadata, 'solvent', info['.SOLVENTNAME']);
maybeAdd(metadata, 'pulse', info['.PULSESEQUENCE'] || info['.PULPROG'] || info['$PULPROG']);
maybeAdd(metadata, 'experiment', getSpectrumType(metadata, info));
maybeAdd(metadata, 'temperature', parseFloat(info['$TE'] || info['.TE']));
maybeAdd(metadata, 'frequency', parseFloat(info['.OBSERVEFREQUENCY']));
maybeAdd(metadata, 'type', info['DATATYPE']);
maybeAdd(metadata, 'probe', info['$PROBHD']);
if (info['$FNTYPE'] !== undefined) {
maybeAdd(metadata, 'acquisitionMode', parseInt(info['$FNTYPE']));
}
maybeAdd(metadata, 'expno', parseInt(info['$EXPNO']));
if (metadata.type) {
if (metadata.type.toUpperCase().indexOf('FID') >= 0) metadata.isFid = true;else if (metadata.type.toUpperCase().indexOf('SPECTRUM') >= 0) {
metadata.isFt = true;
}
}
if (metadata.dimension === 1) {
const nucleus = info['.OBSERVENUCLEUS'];
if (nucleus) {
metadata.nucleus = [nucleus.replace(/[^A-Za-z0-9]/g, '')];
}
} else {
const nucleus = info['.NUCLEUS'];
if (nucleus) {
metadata.nucleus = nucleus.split(',').map(nuc => nuc.trim());
}
}
if (metadata.nucleus.length === 0) {
metadata.nucleus = exports.getNucleusFrom2DExperiment(metadata.experiment);
}
if (info['$DATE']) {
metadata.date = new Date(info['$DATE'] * 1000).toISOString();
}
if (options.computeRanges && metadata.isFt && metadata.dimension === 1 && metadata.nucleus[0] === '1H') {
const rangesOptions = Object.assign({}, defaultRangesOptions, options.ranges);
if (options.removeImpurities && metadata.solvent) rangesOptions.removeImpurity = {
solvent: metadata.solvent
};
const spectrum = SD.NMR.fromJcamp(jcampString);
const ranges = spectrum.getRanges(rangesOptions);
ranges.forEach(function (range) {
// todo remove when there is an option to avoid that
delete range._highlight;
delete range.signalID;
range.signal.forEach(function (signal) {
delete signal.peak;
});
});
metadata.range = ranges;
}
return metadata;
};
/**
* Returns a list of nuclei based on an experiment string
* @param {string} experiment
* @return {string[]}
*/
exports.getNucleusFrom2DExperiment = function (experiment) {
if (typeof experiment !== 'string') {
return [];
}
experiment = experiment.toLowerCase();
if (experiment.includes('jres')) {
return ['1H'];
}
if (experiment.includes('hmbc') || experiment.includes('hsqc')) {
return ['1H', '13C'];
}
return ['1H', '1H'];
};
exports.getSpectrumType = getSpectrumType;
function maybeAdd(obj, name, value) {
if (value !== undefined) {
if (typeof value === 'string') {
if (value.startsWith('<') && value.endsWith('>')) {
value = value.substring(1, value.length - 2);
}
obj[name] = value.trim();
} else {
obj[name] = value;
}
}
}
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const Stat = __webpack_require__(7).array;
/**
* Function that returns an array of points given 1D array as follows:
*
* [x1, y1, .. , x2, y2, ..]
*
* And receive the number of dimensions of each point.
* @param array
* @param dimensions
* @returns {Array} - Array of points.
*/
function coordArrayToPoints(array, dimensions) {
if (array.length % dimensions !== 0) {
throw new RangeError('Dimensions number must be accordance with the size of the array.');
}
var length = array.length / dimensions;
var pointsArr = new Array(length);
var k = 0;
for (var i = 0; i < array.length; i += dimensions) {
var point = new Array(dimensions);
for (var j = 0; j < dimensions; ++j) {
point[j] = array[i + j];
}
pointsArr[k] = point;
k++;
}
return pointsArr;
}
/**
* Function that given an array as follows:
* [x1, y1, .. , x2, y2, ..]
*
* Returns an array as follows:
* [[x1, x2, ..], [y1, y2, ..], [ .. ]]
*
* And receives the number of dimensions of each coordinate.
* @param array
* @param dimensions
* @returns {Array} - Matrix of coordinates
*/
function coordArrayToCoordMatrix(array, dimensions) {
if (array.length % dimensions !== 0) {
throw new RangeError('Dimensions number must be accordance with the size of the array.');
}
var coordinatesArray = new Array(dimensions);
var points = array.length / dimensions;
for (var i = 0; i < coordinatesArray.length; i++) {
coordinatesArray[i] = new Array(points);
}
for (i = 0; i < array.length; i += dimensions) {
for (var j = 0; j < dimensions; ++j) {
var currentPoint = Math.floor(i / dimensions);
coordinatesArray[j][currentPoint] = array[i + j];
}
}
return coordinatesArray;
}
/**
* Function that receives a coordinate matrix as follows:
* [[x1, x2, ..], [y1, y2, ..], [ .. ]]
*
* Returns an array of coordinates as follows:
* [x1, y1, .. , x2, y2, ..]
*
* @param coordMatrix
* @returns {Array}
*/
function coordMatrixToCoordArray(coordMatrix) {
var coodinatesArray = new Array(coordMatrix.length * coordMatrix[0].length);
var k = 0;
for (var i = 0; i < coordMatrix[0].length; ++i) {
for (var j = 0; j < coordMatrix.length; ++j) {
coodinatesArray[k] = coordMatrix[j][i];
++k;
}
}
return coodinatesArray;
}
/**
* Tranpose a matrix, this method is for coordMatrixToPoints and
* pointsToCoordMatrix, that because only transposing the matrix
* you can change your representation.
*
* @param matrix
* @returns {Array}
*/
function transpose(matrix) {
var resultMatrix = new Array(matrix[0].length);
for (var i = 0; i < resultMatrix.length; ++i) {
resultMatrix[i] = new Array(matrix.length);
}
for (i = 0; i < matrix.length; ++i) {
for (var j = 0; j < matrix[0].length; ++j) {
resultMatrix[j][i] = matrix[i][j];
}
}
return resultMatrix;
}
/**
* Function that transform an array of points into a coordinates array
* as follows:
* [x1, y1, .. , x2, y2, ..]
*
* @param points
* @returns {Array}
*/
function pointsToCoordArray(points) {
var coodinatesArray = new Array(points.length * points[0].length);
var k = 0;
for (var i = 0; i < points.length; ++i) {
for (var j = 0; j < points[0].length; ++j) {
coodinatesArray[k] = points[i][j];
++k;
}
}
return coodinatesArray;
}
/**
* Apply the dot product between the smaller vector and a subsets of the
* largest one.
*
* @param firstVector
* @param secondVector
* @returns {Array} each dot product of size of the difference between the
* larger and the smallest one.
*/
function applyDotProduct(firstVector, secondVector) {
var largestVector, smallestVector;
if (firstVector.length <= secondVector.length) {
smallestVector = firstVector;
largestVector = secondVector;
} else {
smallestVector = secondVector;
largestVector = firstVector;
}
var difference = largestVector.length - smallestVector.length + 1;
var dotProductApplied = new Array(difference);
for (var i = 0; i < difference; ++i) {
var sum = 0;
for (var j = 0; j < smallestVector.length; ++j) {
sum += smallestVector[j] * largestVector[i + j];
}
dotProductApplied[i] = sum;
}
return dotProductApplied;
}
/**
* To scale the input array between the specified min and max values. The operation is performed inplace
* if the options.inplace is specified. If only one of the min or max parameters is specified, then the scaling
* will multiply the input array by min/min(input) or max/max(input)
* @param input
* @param options
* @returns {*}
*/
function scale(input) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const min = options.min,
max = options.max;
var y = options.inPlace ? input : new Array(input.length);
var minMax = Stat.minMax(input);
if (typeof max === 'number') {
if (typeof min === 'number') {
let factor = (max - min) / (minMax.max - minMax.min);
for (let i = 0; i < y.length; i++) {
y[i] = (input[i] - minMax.min) * factor + min;
}
} else if (minMax.max !== 0) {
let factor = max / minMax.max;
for (let i = 0; i < y.length; i++) {
y[i] = input[i] * factor;
}
} else {
options.min = minMax.min;
y = scale(input, options);
}
} else if (typeof min === 'number') {
if (minMax.min !== 0) {
let factor = min / minMax.min;
for (let i = 0; i < y.length; i++) {
y[i] = input[i] * factor;
}
} else {
options.max = minMax.max;
y = scale(input, options);
}
}
return y;
}
module.exports = {
coordArrayToPoints: coordArrayToPoints,
coordArrayToCoordMatrix: coordArrayToCoordMatrix,
coordMatrixToCoordArray: coordMatrixToCoordArray,
coordMatrixToPoints: transpose,
pointsToCoordArray: pointsToCoordArray,
pointsToCoordMatrix: transpose,
applyDotProduct: applyDotProduct,
scale: scale
};
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var arrayStat = __webpack_require__(31);
function compareNumbers(a, b) {
return a - b;
}
exports.max = function max(matrix) {
var max = -Infinity;
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > max) max = matrix[i][j];
}
}
return max;
};
exports.min = function min(matrix) {
var min = Infinity;
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < min) min = matrix[i][j];
}
}
return min;
};
exports.minMax = function minMax(matrix) {
var min = Infinity;
var max = -Infinity;
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < min) min = matrix[i][j];
if (matrix[i][j] > max) max = matrix[i][j];
}
}
return {
min: min,
max: max
};
};
exports.entropy = function entropy(matrix, eps) {
if (typeof eps === 'undefined') {
eps = 0;
}
var sum = 0,
l1 = matrix.length,
l2 = matrix[0].length;
for (var i = 0; i < l1; i++) {
for (var j = 0; j < l2; j++) {
sum += matrix[i][j] * Math.log(matrix[i][j] + eps);
}
}
return -sum;
};
exports.mean = function mean(matrix, dimension) {
if (typeof dimension === 'undefined') {
dimension = 0;
}
var rows = matrix.length,
cols = matrix[0].length,
theMean,
N,
i,
j;
if (dimension === -1) {
theMean = [0];
N = rows * cols;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
theMean[0] += matrix[i][j];
}
}
theMean[0] /= N;
} else if (dimension === 0) {
theMean = new Array(cols);
N = rows;
for (j = 0; j < cols; j++) {
theMean[j] = 0;
for (i = 0; i < rows; i++) {
theMean[j] += matrix[i][j];
}
theMean[j] /= N;
}
} else if (dimension === 1) {
theMean = new Array(rows);
N = cols;
for (j = 0; j < rows; j++) {
theMean[j] = 0;
for (i = 0; i < cols; i++) {
theMean[j] += matrix[j][i];
}
theMean[j] /= N;
}
} else {
throw new Error('Invalid dimension');
}
return theMean;
};
exports.sum = function sum(matrix, dimension) {
if (typeof dimension === 'undefined') {
dimension = 0;
}
var rows = matrix.length,
cols = matrix[0].length,
theSum,
i,
j;
if (dimension === -1) {
theSum = [0];
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
theSum[0] += matrix[i][j];
}
}
} else if (dimension === 0) {
theSum = new Array(cols);
for (j = 0; j < cols; j++) {
theSum[j] = 0;
for (i = 0; i < rows; i++) {
theSum[j] += matrix[i][j];
}
}
} else if (dimension === 1) {
theSum = new Array(rows);
for (j = 0; j < rows; j++) {
theSum[j] = 0;
for (i = 0; i < cols; i++) {
theSum[j] += matrix[j][i];
}
}
} else {
throw new Error('Invalid dimension');
}
return theSum;
};
exports.product = function product(matrix, dimension) {
if (typeof dimension === 'undefined') {
dimension = 0;
}
var rows = matrix.length,
cols = matrix[0].length,
theProduct,
i,
j;
if (dimension === -1) {
theProduct = [1];
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
theProduct[0] *= matrix[i][j];
}
}
} else if (dimension === 0) {
theProduct = new Array(cols);
for (j = 0; j < cols; j++) {
theProduct[j] = 1;
for (i = 0; i < rows; i++) {
theProduct[j] *= matrix[i][j];
}
}
} else if (dimension === 1) {
theProduct = new Array(rows);
for (j = 0; j < rows; j++) {
theProduct[j] = 1;
for (i = 0; i < cols; i++) {
theProduct[j] *= matrix[j][i];
}
}
} else {
throw new Error('Invalid dimension');
}
return theProduct;
};
exports.standardDeviation = function standardDeviation(matrix, means, unbiased) {
var vari = exports.variance(matrix, means, unbiased),
l = vari.length;
for (var i = 0; i < l; i++) {
vari[i] = Math.sqrt(vari[i]);
}
return vari;
};
exports.variance = function variance(matrix, means, unbiased) {
if (typeof unbiased === 'undefined') {
unbiased = true;
}
means = means || exports.mean(matrix);
var rows = matrix.length;
if (rows === 0) return [];
var cols = matrix[0].length;
var vari = new Array(cols);
for (var j = 0; j < cols; j++) {
var sum1 = 0,
sum2 = 0,
x = 0;
for (var i = 0; i < rows; i++) {
x = matrix[i][j] - means[j];
sum1 += x;
sum2 += x * x;
}
if (unbiased) {
vari[j] = (sum2 - sum1 * sum1 / rows) / (rows - 1);
} else {
vari[j] = (sum2 - sum1 * sum1 / rows) / rows;
}
}
return vari;
};
exports.median = function median(matrix) {
var rows = matrix.length,
cols = matrix[0].length;
var medians = new Array(cols);
for (var i = 0; i < cols; i++) {
var data = new Array(rows);
for (var j = 0; j < rows; j++) {
data[j] = matrix[j][i];
}
data.sort(compareNumbers);
var N = data.length;
if (N % 2 === 0) {
medians[i] = (data[N / 2] + data[N / 2 - 1]) * 0.5;
} else {
medians[i] = data[Math.floor(N / 2)];
}
}
return medians;
};
exports.mode = function mode(matrix) {
var rows = matrix.length,
cols = matrix[0].length,
modes = new Array(cols),
i,
j;
for (i = 0; i < cols; i++) {
var itemCount = new Array(rows);
for (var k = 0; k < rows; k++) {
itemCount[k] = 0;
}
var itemArray = new Array(rows);
var count = 0;
for (j = 0; j < rows; j++) {
var index = itemArray.indexOf(matrix[j][i]);
if (index >= 0) {
itemCount[index]++;
} else {
itemArray[count] = matrix[j][i];
itemCount[count] = 1;
count++;
}
}
var maxValue = 0,
maxIndex = 0;
for (j = 0; j < count; j++) {
if (itemCount[j] > maxValue) {
maxValue = itemCount[j];
maxIndex = j;
}
}
modes[i] = itemArray[maxIndex];
}
return modes;
};
exports.skewness = function skewness(matrix, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var means = exports.mean(matrix);
var n = matrix.length,
l = means.length;
var skew = new Array(l);
for (var j = 0; j < l; j++) {
var s2 = 0,
s3 = 0;
for (var i = 0; i < n; i++) {
var dev = matrix[i][j] - means[j];
s2 += dev * dev;
s3 += dev * dev * dev;
}
var m2 = s2 / n;
var m3 = s3 / n;
var g = m3 / Math.pow(m2, 3 / 2);
if (unbiased) {
var a = Math.sqrt(n * (n - 1));
var b = n - 2;
skew[j] = a / b * g;
} else {
skew[j] = g;
}
}
return skew;
};
exports.kurtosis = function kurtosis(matrix, unbiased) {
if (typeof unbiased === 'undefined') unbiased = true;
var means = exports.mean(matrix);
var n = matrix.length,
m = matrix[0].length;
var kurt = new Array(m);
for (var j = 0; j < m; j++) {
var s2 = 0,
s4 = 0;
for (var i = 0; i < n; i++) {
var dev = matrix[i][j] - means[j];
s2 += dev * dev;
s4 += dev * dev * dev * dev;
}
var m2 = s2 / n;
var m4 = s4 / n;
if (unbiased) {
var v = s2 / (n - 1);
var a = n * (n + 1) / ((n - 1) * (n - 2) * (n - 3));
var b = s4 / (v * v);
var c = (n - 1) * (n - 1) / ((n - 2) * (n - 3));
kurt[j] = a * b - 3 * c;
} else {
kurt[j] = m4 / (m2 * m2) - 3;
}
}
return kurt;
};
exports.standardError = function standardError(matrix) {
var samples = matrix.length;
var standardDeviations = exports.standardDeviation(matrix);
var l = standardDeviations.length;
var standardErrors = new Array(l);
var sqrtN = Math.sqrt(samples);
for (var i = 0; i < l; i++) {
standardErrors[i] = standardDeviations[i] / sqrtN;
}
return standardErrors;
};
exports.covariance = function covariance(matrix, dimension) {
return exports.scatter(matrix, undefined, dimension);
};
exports.scatter = function scatter(matrix, divisor, dimension) {
if (typeof dimension === 'undefined') {
dimension = 0;
}
if (typeof divisor === 'undefined') {
if (dimension === 0) {
divisor = matrix.length - 1;
} else if (dimension === 1) {
divisor = matrix[0].length - 1;
}
}
var means = exports.mean(matrix, dimension);
var rows = matrix.length;
if (rows === 0) {
return [[]];
}
var cols = matrix[0].length,
cov,
i,
j,
s,
k;
if (dimension === 0) {
cov = new Array(cols);
for (i = 0; i < cols; i++) {
cov[i] = new Array(cols);
}
for (i = 0; i < cols; i++) {
for (j = i; j < cols; j++) {
s = 0;
for (k = 0; k < rows; k++) {
s += (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);
}
s /= divisor;
cov[i][j] = s;
cov[j][i] = s;
}
}
} else if (dimension === 1) {
cov = new Array(rows);
for (i = 0; i < rows; i++) {
cov[i] = new Array(rows);
}
for (i = 0; i < rows; i++) {
for (j = i; j < rows; j++) {
s = 0;
for (k = 0; k < cols; k++) {
s += (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);
}
s /= divisor;
cov[i][j] = s;
cov[j][i] = s;
}
}
} else {
throw new Error('Invalid dimension');
}
return cov;
};
exports.correlation = function correlation(matrix) {
var means = exports.mean(matrix),
standardDeviations = exports.standardDeviation(matrix, true, means),
scores = exports.zScores(matrix, means, standardDeviations),
rows = matrix.length,
cols = matrix[0].length,
i,
j;
var cor = new Array(cols);
for (i = 0; i < cols; i++) {
cor[i] = new Array(cols);
}
for (i = 0; i < cols; i++) {
for (j = i; j < cols; j++) {
var c = 0;
for (var k = 0, l = scores.length; k < l; k++) {
c += scores[k][j] * scores[k][i];
}
c /= rows - 1;
cor[i][j] = c;
cor[j][i] = c;
}
}
return cor;
};
exports.zScores = function zScores(matrix, means, standardDeviations) {
means = means || exports.mean(matrix);
if (typeof standardDeviations === 'undefined') standardDeviations = exports.standardDeviation(matrix, true, means);
return exports.standardize(exports.center(matrix, means, false), standardDeviations, true);
};
exports.center = function center(matrix, means, inPlace) {
means = means || exports.mean(matrix);
var result = matrix,
l = matrix.length,
i,
j,
jj;
if (!inPlace) {
result = new Array(l);
for (i = 0; i < l; i++) {
result[i] = new Array(matrix[i].length);
}
}
for (i = 0; i < l; i++) {
var row = result[i];
for (j = 0, jj = row.length; j < jj; j++) {
row[j] = matrix[i][j] - means[j];
}
}
return result;
};
exports.standardize = function standardize(matrix, standardDeviations, inPlace) {
if (typeof standardDeviations === 'undefined') standardDeviations = exports.standardDeviation(matrix);
var result = matrix,
l = matrix.length,
i,
j,
jj;
if (!inPlace) {
result = new Array(l);
for (i = 0; i < l; i++) {
result[i] = new Array(matrix[i].length);
}
}
for (i = 0; i < l; i++) {
var resultRow = result[i];
var sourceRow = matrix[i];
for (j = 0, jj = resultRow.length; j < jj; j++) {
if (standardDeviations[j] !== 0 && !isNaN(standardDeviations[j])) {
resultRow[j] = sourceRow[j] / standardDeviations[j];
}
}
}
return result;
};
exports.weightedVariance = function weightedVariance(matrix, weights) {
var means = exports.mean(matrix);
var rows = matrix.length;
if (rows === 0) return [];
var cols = matrix[0].length;
var vari = new Array(cols);
for (var j = 0; j < cols; j++) {
var sum = 0;
var a = 0,
b = 0;
for (var i = 0; i < rows; i++) {
var z = matrix[i][j] - means[j];
var w = weights[i];
sum += w * (z * z);
b += w;
a += w * w;
}
vari[j] = sum * (b / (b * b - a));
}
return vari;
};
exports.weightedMean = function weightedMean(matrix, weights, dimension) {
if (typeof dimension === 'undefined') {
dimension = 0;
}
var rows = matrix.length;
if (rows === 0) return [];
var cols = matrix[0].length,
means,
i,
ii,
j,
w,
row;
if (dimension === 0) {
means = new Array(cols);
for (i = 0; i < cols; i++) {
means[i] = 0;
}
for (i = 0; i < rows; i++) {
row = matrix[i];
w = weights[i];
for (j = 0; j < cols; j++) {
means[j] += row[j] * w;
}
}
} else if (dimension === 1) {
means = new Array(rows);
for (i = 0; i < rows; i++) {
means[i] = 0;
}
for (j = 0; j < rows; j++) {
row = matrix[j];
w = weights[j];
for (i = 0; i < cols; i++) {
means[j] += row[i] * w;
}
}
} else {
throw new Error('Invalid dimension');
}
var weightSum = arrayStat.sum(weights);
if (weightSum !== 0) {
for (i = 0, ii = means.length; i < ii; i++) {
means[i] /= weightSum;
}
}
return means;
};
exports.weightedCovariance = function weightedCovariance(matrix, weights, means, dimension) {
dimension = dimension || 0;
means = means || exports.weightedMean(matrix, weights, dimension);
var s1 = 0,
s2 = 0;
for (var i = 0, ii = weights.length; i < ii; i++) {
s1 += weights[i];
s2 += weights[i] * weights[i];
}
var factor = s1 / (s1 * s1 - s2);
return exports.weightedScatter(matrix, weights, means, factor, dimension);
};
exports.weightedScatter = function weightedScatter(matrix, weights, means, factor, dimension) {
dimension = dimension || 0;
means = means || exports.weightedMean(matrix, weights, dimension);
if (typeof factor === 'undefined') {
factor = 1;
}
var rows = matrix.length;
if (rows === 0) {
return [[]];
}
var cols = matrix[0].length,
cov,
i,
j,
k,
s;
if (dimension === 0) {
cov = new Array(cols);
for (i = 0; i < cols; i++) {
cov[i] = new Array(cols);
}
for (i = 0; i < cols; i++) {
for (j = i; j < cols; j++) {
s = 0;
for (k = 0; k < rows; k++) {
s += weights[k] * (matrix[k][j] - means[j]) * (matrix[k][i] - means[i]);
}
cov[i][j] = s * factor;
cov[j][i] = s * factor;
}
}
} else if (dimension === 1) {
cov = new Array(rows);
for (i = 0; i < rows; i++) {
cov[i] = new Array(rows);
}
for (i = 0; i < rows; i++) {
for (j = i; j < rows; j++) {
s = 0;
for (k = 0; k < cols; k++) {
s += weights[k] * (matrix[j][k] - means[j]) * (matrix[i][k] - means[i]);
}
cov[i][j] = s * factor;
cov[j][i] = s * factor;
}
}
} else {
throw new Error('Invalid dimension');
}
return cov;
};
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
*
* Function that returns a Number array of equally spaced numberOfPoints
* containing a representation of intensities of the spectra arguments x
* and y.
*
* The options parameter contains an object in the following form:
* from: starting point
* to: last point
* numberOfPoints: number of points between from and to
* variant: "slot" or "smooth" - smooth is the default option
*
* The slot variant consist that each point in the new array is calculated
* averaging the existing points between the slot that belongs to the current
* value. The smooth variant is the same but takes the integral of the range
* of the slot and divide by the step size between two points in the new array.
*
* @param x - sorted increasing x values
* @param y
* @param options
* @returns {Array} new array with the equally spaced data.
*
*/
function getEquallySpacedData(x, y) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var xLength = x.length;
if (x.length > 1 && x[0] > x[1]) {
x = x.slice().reverse();
y = y.slice().reverse();
}
var _options$from = options.from,
from = _options$from === void 0 ? x[0] : _options$from,
_options$to = options.to,
to = _options$to === void 0 ? x[xLength - 1] : _options$to,
_options$variant = options.variant,
variant = _options$variant === void 0 ? 'smooth' : _options$variant,
_options$numberOfPoin = options.numberOfPoints,
numberOfPoints = _options$numberOfPoin === void 0 ? 100 : _options$numberOfPoin;
if (xLength !== y.length) {
throw new RangeError("the x and y vector doesn't have the same size.");
}
if (typeof from !== 'number' || isNaN(from)) {
throw new RangeError("'from' option must be a number");
}
if (typeof to !== 'number' || isNaN(to)) {
throw new RangeError("'to' option must be a number");
}
var reverse = from > to;
if (reverse) {
var _ref = [to, from];
from = _ref[0];
to = _ref[1];
}
if (typeof numberOfPoints !== 'number' || isNaN(numberOfPoints)) {
throw new RangeError("'numberOfPoints' option must be a number");
}
if (numberOfPoints < 1) {
throw new RangeError('the number of points must be at least 1');
}
var output = variant === 'slot' ? getEquallySpacedSlot(x, y, from, to, numberOfPoints) : getEquallySpacedSmooth(x, y, from, to, numberOfPoints);
return reverse ? output.reverse() : output;
}
/**
* function that retrieves the getEquallySpacedData with the variant "smooth"
*
* @param x
* @param y
* @param from - Initial point
* @param to - Final point
* @param numberOfPoints
* @returns {Array} - Array of y's equally spaced with the variant "smooth"
*/
function getEquallySpacedSmooth(x, y, from, to, numberOfPoints) {
var xLength = x.length;
var step = (to - from) / (numberOfPoints - 1);
var halfStep = step / 2;
var output = new Array(numberOfPoints);
var initialOriginalStep = x[1] - x[0];
var lastOriginalStep = x[xLength - 1] - x[xLength - 2]; // Init main variables
var min = from - halfStep;
var max = from + halfStep;
var previousX = Number.MIN_VALUE;
var previousY = 0;
var nextX = x[0] - initialOriginalStep;
var nextY = 0;
var currentValue = 0;
var slope = 0;
var intercept = 0;
var sumAtMin = 0;
var sumAtMax = 0;
var i = 0; // index of input
var j = 0; // index of output
function getSlope(x0, y0, x1, y1) {
return (y1 - y0) / (x1 - x0);
}
main: while (true) {
if (previousX <= min && min <= nextX) {
add = integral(0, min - previousX, slope, previousY);
sumAtMin = currentValue + add;
}
while (nextX - max >= 0) {
// no overlap with original point, just consume current value
var add = integral(0, max - previousX, slope, previousY);
sumAtMax = currentValue + add;
output[j++] = (sumAtMax - sumAtMin) / step;
if (j === numberOfPoints) {
break main;
}
min = max;
max += step;
sumAtMin = sumAtMax;
}
currentValue += integral(previousX, nextX, slope, intercept);
previousX = nextX;
previousY = nextY;
if (i < xLength) {
nextX = x[i];
nextY = y[i];
i++;
} else if (i === xLength) {
nextX += lastOriginalStep;
nextY = 0;
}
slope = getSlope(previousX, previousY, nextX, nextY);
intercept = -slope * previousX + previousY;
}
return output;
}
/**
* function that retrieves the getEquallySpacedData with the variant "slot"
*
* @param x
* @param y
* @param from - Initial point
* @param to - Final point
* @param numberOfPoints
* @returns {Array} - Array of y's equally spaced with the variant "slot"
*/
function getEquallySpacedSlot(x, y, from, to, numberOfPoints) {
var xLength = x.length;
var step = (to - from) / (numberOfPoints - 1);
var halfStep = step / 2;
var lastStep = x[x.length - 1] - x[x.length - 2];
var start = from - halfStep;
var output = new Array(numberOfPoints); // Init main variables
var min = start;
var max = start + step;
var previousX = -Number.MAX_VALUE;
var previousY = 0;
var nextX = x[0];
var nextY = y[0];
var frontOutsideSpectra = 0;
var backOutsideSpectra = true;
var currentValue = 0; // for slot algorithm
var currentPoints = 0;
var i = 1; // index of input
var j = 0; // index of output
main: while (true) {
if (previousX >= nextX) throw new Error('x must be an increasing serie');
while (previousX - max > 0) {
// no overlap with original point, just consume current value
if (backOutsideSpectra) {
currentPoints++;
backOutsideSpectra = false;
}
output[j] = currentPoints <= 0 ? 0 : currentValue / currentPoints;
j++;
if (j === numberOfPoints) {
break main;
}
min = max;
max += step;
currentValue = 0;
currentPoints = 0;
}
if (previousX > min) {
currentValue += previousY;
currentPoints++;
}
if (previousX === -Number.MAX_VALUE || frontOutsideSpectra > 1) {
currentPoints--;
}
previousX = nextX;
previousY = nextY;
if (i < xLength) {
nextX = x[i];
nextY = y[i];
i++;
} else {
nextX += lastStep;
nextY = 0;
frontOutsideSpectra++;
}
}
return output;
}
/**
* Function that calculates the integral of the line between two
* x-coordinates, given the slope and intercept of the line.
* @param x0
* @param x1
* @param slope
* @param intercept
* @returns {number} integral value.
*/
function integral(x0, x1, slope, intercept) {
return 0.5 * slope * x1 * x1 + intercept * x1 - (0.5 * slope * x0 * x0 + intercept * x0);
}
exports.getEquallySpacedData = getEquallySpacedData;
exports.integral = integral;
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.SNV = SNV;
var Stat = __webpack_require__(7).array;
/**
* Function that applies the standard normal variate (SNV) to an array of values.
*
* @param data - Array of values.
* @returns {Array} - applied the SNV.
*/
function SNV(data) {
var mean = Stat.mean(data);
var std = Stat.standardDeviation(data);
var result = data.slice();
for (var i = 0; i < data.length; i++) {
result[i] = (result[i] - mean) / std;
}
return result;
}
/***/ }),
/* 64 */
/***/ (function(module) {
module.exports = {"_from":"spectra-data@3.4.5","_id":"spectra-data@3.4.5","_inBundle":false,"_integrity":"sha512-xDKg4neffK+O/yzcKsfMHlAqpjl7MNvV7+a3F8+/cTd55z1M8z40lwsk7Gi3Ae9Pk02Ah/lmy/V0RliJnWABwA==","_location":"/spectra-data","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"spectra-data@3.4.5","name":"spectra-data","escapedName":"spectra-data","rawSpec":"3.4.5","saveSpec":null,"fetchSpec":"3.4.5"},"_requiredBy":["#USER","/"],"_resolved":"https://registry.npmjs.org/spectra-data/-/spectra-data-3.4.5.tgz","_shasum":"dde5e7c37ec030b3b94f02c5bc6ccd4fa9911f9c","_spec":"spectra-data@3.4.5","_where":"/usr/local/www/sites/www.lactame.com/node/grm-data/git/cheminfo/nmr-metadata","author":{"name":"Andres Castillo"},"bugs":{"url":"https://github.com/cheminfo-js/spectra/issues"},"bundleDependencies":false,"contributors":[{"name":"Michaël Zasso"},{"name":"Luc Patiny"}],"dependencies":{"brukerconverter":"^1.0.1","jcampconverter":"^2.9.2","lodash.round":"^4.0.4","ml-array-max":"^1.0.1","ml-array-median":"^1.0.0","ml-array-min":"^1.0.1","ml-array-rescale":"^1.1.0","ml-array-utils":"^0.4.0","ml-curve-fitting":"^0.0.7","ml-fft":"^1.3.5","ml-gsd":"^2.0.1","ml-matrix-peaks-finder":"^0.2.1","ml-simple-clustering":"^0.1.0","nmr-simulation":"^1.0.17","spectra-data-ranges":"^1.1.5","spectra-nmr-utilities":"^1.0.5"},"deprecated":false,"description":"spectra-data project - manipulate spectra","devDependencies":{"jsdoc":"^3.5.5","nmr-predictor":"^1.1.11","should":"^13.2.3"},"files":["lib","src"],"homepage":"https://github.com/cheminfo-js/spectra/packages/spectra-data","jest":{"testEnvironment":"node"},"keywords":["spectra-data","project"],"license":"MIT","main":"./lib/index.js","module":"./src/index.js","name":"spectra-data","repository":{"type":"git","url":"git+https://github.com/cheminfo-js/spectra.git"},"version":"3.4.5"};
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
const extend = __webpack_require__(32);
const SG = __webpack_require__(66);
const defaultOptions = {
sgOptions: {
windowSize: 9,
polynomial: 3
},
minMaxRatio: 0.00025,
broadRatio: 0.00,
maxCriteria: true,
smoothY: true,
realTopDetection: false,
heightFactor: 0,
boundaries: false,
derivativeThreshold: -1
};
/**
* Global spectra deconvolution
* @param {Array} x - Independent variable
* @param {Array} yIn - Dependent variable
* @param {object} [options] - Options object
* @param {object} [options.sgOptions] - Options object for Savitzky-Golay filter. See https://github.com/mljs/savitzky-golay-generalized#options
* @param {number} [options.sgOptions.windowSize = 9] - points to use in the approximations
* @param {number} [options.sgOptions.polynomial = 3] - degree of the polynomial to use in the approximations
* @param {number} [options.minMaxRatio = 0.00025] - Threshold to determine if a given peak should be considered as a noise
* @param {number} [options.broadRatio = 0.00] - If `broadRatio` is higher than 0, then all the peaks which second derivative
* smaller than `broadRatio * maxAbsSecondDerivative` will be marked with the soft mask equal to true.
* @param {number} [options.noiseLevel = 0] - Noise threshold in spectrum units
* @param {boolean} [options.maxCriteria = true] - Peaks are local maximum(true) or minimum(false)
* @param {boolean} [options.smoothY = true] - Select the peak intensities from a smoothed version of the independent variables
* @param {boolean} [options.realTopDetection = false] - Use a quadratic optimizations with the peak and its 3 closest neighbors
* to determine the true x,y values of the peak?
* @param {number} [options.heightFactor = 0] - Factor to multiply the calculated height (usually 2)
* @param {boolean} [options.boundaries = false] - Return also the inflection points of the peaks
* @param {number} [options.derivativeThreshold = -1] - Filters based on the amplitude of the first derivative
* @return {Array