/*
 * ir-spectrum v4.0.0
 * Package used to handle IR spectra in SciPeaks.
 * https://github.com/cheminfo/ir-spectrum#readme
 *
 * Licensed under the MIT license.
 */
// eslint-disable-next-line @typescript-eslint/unbound-method
const toString = Object.prototype.toString;
/**
 * Checks if an object is an instance of an Array (array or typed array, except those that contain bigint values).
 *
 * @param value - Object to check.
 * @returns True if the object is an array or a typed array.
 */
function isAnyArray$1(value) {
  const tag = toString.call(value);
  return tag.endsWith('Array]') && !tag.includes('Big');
}

var libEsm = /*#__PURE__*/Object.freeze({
    __proto__: null,
    isAnyArray: isAnyArray$1
});

/**
 * This function
 * @param output - undefined or a new array
 * @param length - length of the output array
 * @returns
 */
function getOutputArray(output, length) {
  if (output !== undefined) {
    if (!isAnyArray$1(output)) {
      throw new TypeError('output option must be an array if specified');
    }
    if (output.length !== length) {
      throw new TypeError('the output array does not have the correct length');
    }
    return output;
  } else {
    return new Float64Array(length);
  }
}

/**
 * Calculates the median of an array.
 * @param input - Array containing values
 * @param options
 * @returns - median
 */
function xMedian(input, options = {}) {
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  const {
    exact = false
  } = options || {};
  const array = input.slice();
  const middleIndex = calcMiddle(0, array.length - 1);
  const median = quickSelect(array, middleIndex);
  if (array.length % 2 === 1 || !exact) {
    return median;
  }
  const medianNext = quickSelect(array, middleIndex + 1);
  return (median + medianNext) / 2;
}
function quickSelect(array, middleIndex) {
  let low = 0;
  let high = array.length - 1;
  let middle = 0;
  let currentLow = 0;
  let currentHigh = 0;
  while (true) {
    if (high <= low) {
      return array[middleIndex];
    }
    if (high === low + 1) {
      if (array[low] > array[high]) {
        swap(array, low, high);
      }
      return array[middleIndex];
    }
    // Find median of low, middle and high items; swap into position low
    middle = calcMiddle(low, high);
    if (array[middle] > array[high]) swap(array, middle, high);
    if (array[low] > array[high]) swap(array, low, high);
    if (array[middle] > array[low]) swap(array, middle, low);
    // Swap low item (now in position middle) into position (low+1)
    swap(array, middle, low + 1);
    // Nibble from each end towards middle, swapping items when stuck
    currentLow = low + 1;
    currentHigh = high;
    while (true) {
      do currentLow++; while (array[low] > array[currentLow]);
      do currentHigh--; while (array[currentHigh] > array[low]);
      if (currentHigh < currentLow) {
        break;
      }
      swap(array, currentLow, currentHigh);
    }
    // Swap middle item (in position low) back into correct position
    swap(array, low, currentHigh);
    // Re-set active partition
    if (currentHigh <= middleIndex) {
      low = currentLow;
    }
    if (currentHigh >= middleIndex) {
      high = currentHigh - 1;
    }
  }
}
function swap(array, i, j) {
  const temp = array[j];
  array[j] = array[i];
  array[i] = temp;
}
function calcMiddle(i, j) {
  return Math.floor((i + j) / 2);
}

/**
 * Checks if the input is a non-empty array of numbers.
 * Only checks the first element.
 * @param input - Array to check.
 * @param options - Additional checks.
 */
function xCheck(input, options = {}) {
  const {
    minLength
  } = options;
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  if (typeof input[0] !== 'number') {
    throw new TypeError('input must contain numbers');
  }
  if (minLength && input.length < minLength) {
    throw new Error(`input must have a length of at least ${minLength}`);
  }
}

/**
 * Returns the closest index of a `target`
 * @param array - array of numbers
 * @param target - target
 * @param options
 * @returns - closest index
 */
function xFindClosestIndex(array, target, options = {}) {
  const {
    sorted = true
  } = options;
  if (sorted) {
    let low = 0;
    let high = array.length - 1;
    let middle = 0;
    while (high - low > 1) {
      middle = low + (high - low >> 1);
      if (array[middle] < target) {
        low = middle;
      } else if (array[middle] > target) {
        high = middle;
      } else {
        return middle;
      }
    }
    if (low < array.length - 1) {
      if (Math.abs(target - array[low]) < Math.abs(array[low + 1] - target)) {
        return low;
      } else {
        return low + 1;
      }
    } else {
      return low;
    }
  } else {
    let index = 0;
    let diff = Number.POSITIVE_INFINITY;
    for (let i = 0; i < array.length; i++) {
      const currentDiff = Math.abs(array[i] - target);
      if (currentDiff < diff) {
        diff = currentDiff;
        index = i;
      }
    }
    return index;
  }
}

/**
 * Returns an object with {fromIndex, toIndex} for a specific from / to
 * @param x - array of numbers
 * @param options - Options
 */
function xGetFromToIndex(x, options = {}) {
  let {
    fromIndex,
    toIndex
  } = options;
  const {
    from,
    to
  } = options;
  if (fromIndex === undefined) {
    if (from !== undefined) {
      fromIndex = xFindClosestIndex(x, from);
    } else {
      fromIndex = 0;
    }
  }
  if (toIndex === undefined) {
    if (to !== undefined) {
      toIndex = xFindClosestIndex(x, to);
    } else {
      toIndex = x.length - 1;
    }
  }
  if (fromIndex < 0) fromIndex = 0;
  if (toIndex < 0) toIndex = 0;
  if (fromIndex >= x.length) fromIndex = x.length - 1;
  if (toIndex >= x.length) toIndex = x.length - 1;
  if (fromIndex > toIndex) [fromIndex, toIndex] = [toIndex, fromIndex];
  return {
    fromIndex,
    toIndex
  };
}

function xAbsoluteSum(array, options = {}) {
  xCheck(array);
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(array, options);
  let sum = 0;
  for (let i = fromIndex; i <= toIndex; i++) {
    sum += Math.abs(array[i]);
  }
  return sum;
}

/**
 * This function xAdd the first array by the second array or a constant value to each element of the first array
 * @param array1 - the first array
 * @param array2 - the second array or number
 * @returns the result of the addition
 */
function xAdd(array1, array2) {
  let isConstant = false;
  let constant = 0;
  if (isAnyArray$1(array2)) {
    if (array1.length !== array2.length) {
      throw new Error('size of array1 and array2 must be identical');
    }
  } else {
    isConstant = true;
    constant = array2;
  }
  const array3 = new Float64Array(array1.length);
  if (isConstant) {
    for (let i = 0; i < array1.length; i++) {
      array3[i] = array1[i] + constant;
    }
  } else {
    for (let i = 0; i < array1.length; i++) {
      array3[i] = array1[i] + array2[i];
    }
  }
  return array3;
}

/**
 * Will apply a function on each element of the array described as a string
 * By default we will use as variable 'x'
 * In front of sequence of lowercase we will add 'Math.'. This allows to write
 * `sin(x) + cos(x)` and it will be replace internally by (x) => (Math.sin(x) + Math.cos(x))
 * @param array
 * @param options
 * @returns
 */
function xApplyFunctionStr(array, options = {}) {
  const {
    variableLabel = 'x',
    fctString = variableLabel
  } = options;
  const fct = new Function(variableLabel, `return Number(${fctString.replaceAll(/(?<before>^|\W)(?<after>[\da-z]{2,}\()/g, '$<before>Math.$<after>').replaceAll('Math.Math', 'Math')})`);
  const toReturn = Float64Array.from(array);
  for (let i = 0; i < array.length; i++) {
    toReturn[i] = fct(array[i]);
    if (Number.isNaN(toReturn[i])) {
      throw new Error(`The callback ${fctString} does not return a number: ${array[i]}`);
    }
  }
  return toReturn;
}

/**
 * This function xMultiply the first array by the second array or a constant value to each element of the first array
 * @param array1 - first array
 * @param array2 - second array
 * @param options - options
 */
function xMultiply(array1, array2, options = {}) {
  let isConstant = false;
  let constant = 0;
  if (isAnyArray$1(array2)) {
    if (array1.length !== array2.length) {
      throw new Error('size of array1 and array2 must be identical');
    }
  } else {
    isConstant = true;
    constant = array2;
  }
  const array3 = getOutputArray(options.output, array1.length);
  if (isConstant) {
    for (let i = 0; i < array1.length; i++) {
      array3[i] = array1[i] * constant;
    }
  } else {
    for (let i = 0; i < array1.length; i++) {
      array3[i] = array1[i] * array2[i];
    }
  }
  return array3;
}

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

function getAugmentedNamespace(n) {
  if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			var isInstance = false;
      try {
        isInstance = this instanceof a;
      } catch {}
			if (isInstance) {
        return Reflect.construct(f, arguments, this.constructor);
			}
			return f.apply(this, arguments);
		};
		a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, '__esModule', {value: true});
	Object.keys(n).forEach(function (k) {
		var d = Object.getOwnPropertyDescriptor(n, k);
		Object.defineProperty(a, k, d.get ? d : {
			enumerable: true,
			get: function () {
				return n[k];
			}
		});
	});
	return a;
}

var matrix = {};

var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEsm);

function max(input) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  var _options$fromIndex = options.fromIndex,
    fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,
    _options$toIndex = options.toIndex,
    toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;
  if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {
    throw new Error('fromIndex must be a positive integer smaller than length');
  }
  if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {
    throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');
  }
  var maxValue = input[fromIndex];
  for (var i = fromIndex + 1; i < toIndex; i++) {
    if (input[i] > maxValue) maxValue = input[i];
  }
  return maxValue;
}

function min(input) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  var _options$fromIndex = options.fromIndex,
    fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,
    _options$toIndex = options.toIndex,
    toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;
  if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {
    throw new Error('fromIndex must be a positive integer smaller than length');
  }
  if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {
    throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');
  }
  var minValue = input[fromIndex];
  for (var i = fromIndex + 1; i < toIndex; i++) {
    if (input[i] < minValue) minValue = input[i];
  }
  return minValue;
}

function rescale$2(input) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  } else if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  var output;
  if (options.output !== undefined) {
    if (!isAnyArray$1(options.output)) {
      throw new TypeError('output option must be an array if specified');
    }
    output = options.output;
  } else {
    output = new Array(input.length);
  }
  var currentMin = min(input);
  var currentMax = max(input);
  if (currentMin === currentMax) {
    throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');
  }
  var _options$min = options.min,
    minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,
    _options$max = options.max,
    maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;
  if (minValue >= maxValue) {
    throw new RangeError('min option must be smaller than max option');
  }
  var factor = (maxValue - minValue) / (currentMax - currentMin);
  for (var i = 0; i < input.length; i++) {
    output[i] = (input[i] - currentMin) * factor + minValue;
  }
  return output;
}

var libEs6 = /*#__PURE__*/Object.freeze({
    __proto__: null,
    default: rescale$2
});

var require$$1 = /*@__PURE__*/getAugmentedNamespace(libEs6);

Object.defineProperty(matrix, '__esModule', {
  value: true
});
var isAnyArray = require$$0;
var rescale$1 = require$$1;
const indent = ' '.repeat(2);
const indentData = ' '.repeat(4);

/**
 * @this {Matrix}
 * @returns {string}
 */
function inspectMatrix() {
  return inspectMatrixWithOptions(this);
}
function inspectMatrixWithOptions(matrix, options = {}) {
  const {
    maxRows = 15,
    maxColumns = 10,
    maxNumSize = 8,
    padMinus = 'auto'
  } = options;
  return `${matrix.constructor.name} {
${indent}[
${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus)}
${indent}]
${indent}rows: ${matrix.rows}
${indent}columns: ${matrix.columns}
}`;
}
function inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus) {
  const {
    rows,
    columns
  } = matrix;
  const maxI = Math.min(rows, maxRows);
  const maxJ = Math.min(columns, maxColumns);
  const result = [];
  if (padMinus === 'auto') {
    padMinus = false;
    loop: for (let i = 0; i < maxI; i++) {
      for (let j = 0; j < maxJ; j++) {
        if (matrix.get(i, j) < 0) {
          padMinus = true;
          break loop;
        }
      }
    }
  }
  for (let i = 0; i < maxI; i++) {
    let line = [];
    for (let j = 0; j < maxJ; j++) {
      line.push(formatNumber(matrix.get(i, j), maxNumSize, padMinus));
    }
    result.push(`${line.join(' ')}`);
  }
  if (maxJ !== columns) {
    result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;
  }
  if (maxI !== rows) {
    result.push(`... ${rows - maxRows} more rows`);
  }
  return result.join(`\n${indentData}`);
}
function formatNumber(num, maxNumSize, padMinus) {
  return (num >= 0 && padMinus ? ` ${formatNumber2(num, maxNumSize - 1)}` : formatNumber2(num, maxNumSize)).padEnd(maxNumSize);
}
function formatNumber2(num, len) {
  // small.length numbers should be as is
  let str = num.toString();
  if (str.length <= len) return str;

  // (7)'0.00123' is better then (7)'1.23e-2'
  // (8)'0.000123' is worse then (7)'1.23e-3',
  let fix = num.toFixed(len);
  if (fix.length > len) {
    fix = num.toFixed(Math.max(0, len - (fix.length - len)));
  }
  if (fix.length <= len && !fix.startsWith('0.000') && !fix.startsWith('-0.000')) {
    return fix;
  }

  // well, if it's still too long the user should've used longer numbers
  let exp = num.toExponential(len);
  if (exp.length > len) {
    exp = num.toExponential(Math.max(0, len - (exp.length - len)));
  }
  return exp.slice(0);
}
function installMathOperations(AbstractMatrix, Matrix) {
  AbstractMatrix.prototype.add = function add(value) {
    if (typeof value === 'number') return this.addS(value);
    return this.addM(value);
  };
  AbstractMatrix.prototype.addS = function addS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.addM = function addM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.add = function add(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.add(value);
  };
  AbstractMatrix.prototype.sub = function sub(value) {
    if (typeof value === 'number') return this.subS(value);
    return this.subM(value);
  };
  AbstractMatrix.prototype.subS = function subS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.subM = function subM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.sub = function sub(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sub(value);
  };
  AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;
  AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;
  AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;
  AbstractMatrix.subtract = AbstractMatrix.sub;
  AbstractMatrix.prototype.mul = function mul(value) {
    if (typeof value === 'number') return this.mulS(value);
    return this.mulM(value);
  };
  AbstractMatrix.prototype.mulS = function mulS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.mulM = function mulM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.mul = function mul(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.mul(value);
  };
  AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;
  AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;
  AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;
  AbstractMatrix.multiply = AbstractMatrix.mul;
  AbstractMatrix.prototype.div = function div(value) {
    if (typeof value === 'number') return this.divS(value);
    return this.divM(value);
  };
  AbstractMatrix.prototype.divS = function divS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.divM = function divM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.div = function div(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.div(value);
  };
  AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;
  AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;
  AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;
  AbstractMatrix.divide = AbstractMatrix.div;
  AbstractMatrix.prototype.mod = function mod(value) {
    if (typeof value === 'number') return this.modS(value);
    return this.modM(value);
  };
  AbstractMatrix.prototype.modS = function modS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) % value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.modM = function modM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) % matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.mod = function mod(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.mod(value);
  };
  AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;
  AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;
  AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;
  AbstractMatrix.modulus = AbstractMatrix.mod;
  AbstractMatrix.prototype.and = function and(value) {
    if (typeof value === 'number') return this.andS(value);
    return this.andM(value);
  };
  AbstractMatrix.prototype.andS = function andS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) & value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.andM = function andM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) & matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.and = function and(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.and(value);
  };
  AbstractMatrix.prototype.or = function or(value) {
    if (typeof value === 'number') return this.orS(value);
    return this.orM(value);
  };
  AbstractMatrix.prototype.orS = function orS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) | value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.orM = function orM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) | matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.or = function or(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.or(value);
  };
  AbstractMatrix.prototype.xor = function xor(value) {
    if (typeof value === 'number') return this.xorS(value);
    return this.xorM(value);
  };
  AbstractMatrix.prototype.xorS = function xorS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ^ value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.xorM = function xorM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ^ matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.xor = function xor(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.xor(value);
  };
  AbstractMatrix.prototype.leftShift = function leftShift(value) {
    if (typeof value === 'number') return this.leftShiftS(value);
    return this.leftShiftM(value);
  };
  AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) << value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) << matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.leftShift = function leftShift(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.leftShift(value);
  };
  AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {
    if (typeof value === 'number') return this.signPropagatingRightShiftS(value);
    return this.signPropagatingRightShiftM(value);
  };
  AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >> value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >> matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.signPropagatingRightShift(value);
  };
  AbstractMatrix.prototype.rightShift = function rightShift(value) {
    if (typeof value === 'number') return this.rightShiftS(value);
    return this.rightShiftM(value);
  };
  AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >>> value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >>> matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.rightShift = function rightShift(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.rightShift(value);
  };
  AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;
  AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;
  AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;
  AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;
  AbstractMatrix.prototype.not = function not() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, ~this.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.not = function not(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.not();
  };
  AbstractMatrix.prototype.abs = function abs() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.abs(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.abs = function abs(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.abs();
  };
  AbstractMatrix.prototype.acos = function acos() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.acos(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.acos = function acos(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.acos();
  };
  AbstractMatrix.prototype.acosh = function acosh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.acosh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.acosh = function acosh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.acosh();
  };
  AbstractMatrix.prototype.asin = function asin() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.asin(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.asin = function asin(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.asin();
  };
  AbstractMatrix.prototype.asinh = function asinh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.asinh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.asinh = function asinh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.asinh();
  };
  AbstractMatrix.prototype.atan = function atan() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.atan(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.atan = function atan(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.atan();
  };
  AbstractMatrix.prototype.atanh = function atanh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.atanh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.atanh = function atanh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.atanh();
  };
  AbstractMatrix.prototype.cbrt = function cbrt() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.cbrt(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.cbrt = function cbrt(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.cbrt();
  };
  AbstractMatrix.prototype.ceil = function ceil() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.ceil(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.ceil = function ceil(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.ceil();
  };
  AbstractMatrix.prototype.clz32 = function clz32() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.clz32(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.clz32 = function clz32(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.clz32();
  };
  AbstractMatrix.prototype.cos = function cos() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.cos(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.cos = function cos(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.cos();
  };
  AbstractMatrix.prototype.cosh = function cosh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.cosh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.cosh = function cosh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.cosh();
  };
  AbstractMatrix.prototype.exp = function exp() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.exp(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.exp = function exp(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.exp();
  };
  AbstractMatrix.prototype.expm1 = function expm1() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.expm1(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.expm1 = function expm1(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.expm1();
  };
  AbstractMatrix.prototype.floor = function floor() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.floor(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.floor = function floor(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.floor();
  };
  AbstractMatrix.prototype.fround = function fround() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.fround(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.fround = function fround(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.fround();
  };
  AbstractMatrix.prototype.log = function log() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log = function log(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log();
  };
  AbstractMatrix.prototype.log1p = function log1p() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log1p(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log1p = function log1p(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log1p();
  };
  AbstractMatrix.prototype.log10 = function log10() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log10(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log10 = function log10(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log10();
  };
  AbstractMatrix.prototype.log2 = function log2() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log2(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log2 = function log2(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log2();
  };
  AbstractMatrix.prototype.round = function round() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.round(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.round = function round(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.round();
  };
  AbstractMatrix.prototype.sign = function sign() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sign(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sign = function sign(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sign();
  };
  AbstractMatrix.prototype.sin = function sin() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sin(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sin = function sin(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sin();
  };
  AbstractMatrix.prototype.sinh = function sinh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sinh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sinh = function sinh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sinh();
  };
  AbstractMatrix.prototype.sqrt = function sqrt() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sqrt(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sqrt = function sqrt(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sqrt();
  };
  AbstractMatrix.prototype.tan = function tan() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.tan(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.tan = function tan(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.tan();
  };
  AbstractMatrix.prototype.tanh = function tanh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.tanh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.tanh = function tanh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.tanh();
  };
  AbstractMatrix.prototype.trunc = function trunc() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.trunc(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.trunc = function trunc(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.trunc();
  };
  AbstractMatrix.pow = function pow(matrix, arg0) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.pow(arg0);
  };
  AbstractMatrix.prototype.pow = function pow(value) {
    if (typeof value === 'number') return this.powS(value);
    return this.powM(value);
  };
  AbstractMatrix.prototype.powS = function powS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ** value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.powM = function powM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ** matrix.get(i, j));
      }
    }
    return this;
  };
}

/**
 * @private
 * Check that a row index is not out of bounds
 * @param {Matrix} matrix
 * @param {number} index
 * @param {boolean} [outer]
 */
function checkRowIndex(matrix, index, outer) {
  let 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]
 */
function checkColumnIndex(matrix, index, outer) {
  let 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}
 */
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}
 */
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;
}
function checkRowIndices(matrix, rowIndices) {
  if (!isAnyArray.isAnyArray(rowIndices)) {
    throw new TypeError('row indices must be an array');
  }
  for (let i = 0; i < rowIndices.length; i++) {
    if (rowIndices[i] < 0 || rowIndices[i] >= matrix.rows) {
      throw new RangeError('row indices are out of range');
    }
  }
}
function checkColumnIndices(matrix, columnIndices) {
  if (!isAnyArray.isAnyArray(columnIndices)) {
    throw new TypeError('column indices must be an array');
  }
  for (let i = 0; i < columnIndices.length; i++) {
    if (columnIndices[i] < 0 || columnIndices[i] >= matrix.columns) {
      throw new RangeError('column indices are out of range');
    }
  }
}
function checkRange(matrix, startRow, endRow, startColumn, endColumn) {
  if (arguments.length !== 5) {
    throw new RangeError('expected 4 arguments');
  }
  checkNumber('startRow', startRow);
  checkNumber('endRow', endRow);
  checkNumber('startColumn', startColumn);
  checkNumber('endColumn', endColumn);
  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');
  }
}
function newArray(length, value = 0) {
  let array = [];
  for (let i = 0; i < length; i++) {
    array.push(value);
  }
  return array;
}
function checkNumber(name, value) {
  if (typeof value !== 'number') {
    throw new TypeError(`${name} must be a number`);
  }
}
function checkNonEmpty(matrix) {
  if (matrix.isEmpty()) {
    throw new Error('Empty matrix has no elements to index');
  }
}
function sumByRow(matrix) {
  let sum = newArray(matrix.rows);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[i] += matrix.get(i, j);
    }
  }
  return sum;
}
function sumByColumn(matrix) {
  let sum = newArray(matrix.columns);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[j] += matrix.get(i, j);
    }
  }
  return sum;
}
function sumAll(matrix) {
  let v = 0;
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      v += matrix.get(i, j);
    }
  }
  return v;
}
function productByRow(matrix) {
  let sum = newArray(matrix.rows, 1);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[i] *= matrix.get(i, j);
    }
  }
  return sum;
}
function productByColumn(matrix) {
  let sum = newArray(matrix.columns, 1);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[j] *= matrix.get(i, j);
    }
  }
  return sum;
}
function productAll(matrix) {
  let v = 1;
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      v *= matrix.get(i, j);
    }
  }
  return v;
}
function varianceByRow(matrix, unbiased, mean) {
  const rows = matrix.rows;
  const cols = matrix.columns;
  const variance = [];
  for (let i = 0; i < rows; i++) {
    let sum1 = 0;
    let sum2 = 0;
    let x = 0;
    for (let j = 0; j < cols; j++) {
      x = matrix.get(i, j) - mean[i];
      sum1 += x;
      sum2 += x * x;
    }
    if (unbiased) {
      variance.push((sum2 - sum1 * sum1 / cols) / (cols - 1));
    } else {
      variance.push((sum2 - sum1 * sum1 / cols) / cols);
    }
  }
  return variance;
}
function varianceByColumn(matrix, unbiased, mean) {
  const rows = matrix.rows;
  const cols = matrix.columns;
  const variance = [];
  for (let j = 0; j < cols; j++) {
    let sum1 = 0;
    let sum2 = 0;
    let x = 0;
    for (let i = 0; i < rows; i++) {
      x = matrix.get(i, j) - mean[j];
      sum1 += x;
      sum2 += x * x;
    }
    if (unbiased) {
      variance.push((sum2 - sum1 * sum1 / rows) / (rows - 1));
    } else {
      variance.push((sum2 - sum1 * sum1 / rows) / rows);
    }
  }
  return variance;
}
function varianceAll(matrix, unbiased, mean) {
  const rows = matrix.rows;
  const cols = matrix.columns;
  const size = rows * cols;
  let sum1 = 0;
  let sum2 = 0;
  let x = 0;
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      x = matrix.get(i, j) - mean;
      sum1 += x;
      sum2 += x * x;
    }
  }
  if (unbiased) {
    return (sum2 - sum1 * sum1 / size) / (size - 1);
  } else {
    return (sum2 - sum1 * sum1 / size) / size;
  }
}
function centerByRow(matrix, mean) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) - mean[i]);
    }
  }
}
function centerByColumn(matrix, mean) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) - mean[j]);
    }
  }
}
function centerAll(matrix, mean) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) - mean);
    }
  }
}
function getScaleByRow(matrix) {
  const scale = [];
  for (let i = 0; i < matrix.rows; i++) {
    let sum = 0;
    for (let j = 0; j < matrix.columns; j++) {
      sum += matrix.get(i, j) ** 2 / (matrix.columns - 1);
    }
    scale.push(Math.sqrt(sum));
  }
  return scale;
}
function scaleByRow(matrix, scale) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) / scale[i]);
    }
  }
}
function getScaleByColumn(matrix) {
  const scale = [];
  for (let j = 0; j < matrix.columns; j++) {
    let sum = 0;
    for (let i = 0; i < matrix.rows; i++) {
      sum += matrix.get(i, j) ** 2 / (matrix.rows - 1);
    }
    scale.push(Math.sqrt(sum));
  }
  return scale;
}
function scaleByColumn(matrix, scale) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) / scale[j]);
    }
  }
}
function getScaleAll(matrix) {
  const divider = matrix.size - 1;
  let sum = 0;
  for (let j = 0; j < matrix.columns; j++) {
    for (let i = 0; i < matrix.rows; i++) {
      sum += matrix.get(i, j) ** 2 / divider;
    }
  }
  return Math.sqrt(sum);
}
function scaleAll(matrix, scale) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) / scale);
    }
  }
}
class AbstractMatrix {
  static from1DArray(newRows, newColumns, newData) {
    let length = newRows * newColumns;
    if (length !== newData.length) {
      throw new RangeError('data length does not match given dimensions');
    }
    let newMatrix = new Matrix$1(newRows, newColumns);
    for (let row = 0; row < newRows; row++) {
      for (let column = 0; column < newColumns; column++) {
        newMatrix.set(row, column, newData[row * newColumns + column]);
      }
    }
    return newMatrix;
  }
  static rowVector(newData) {
    let vector = new Matrix$1(1, newData.length);
    for (let i = 0; i < newData.length; i++) {
      vector.set(0, i, newData[i]);
    }
    return vector;
  }
  static columnVector(newData) {
    let vector = new Matrix$1(newData.length, 1);
    for (let i = 0; i < newData.length; i++) {
      vector.set(i, 0, newData[i]);
    }
    return vector;
  }
  static zeros(rows, columns) {
    return new Matrix$1(rows, columns);
  }
  static ones(rows, columns) {
    return new Matrix$1(rows, columns).fill(1);
  }
  static rand(rows, columns, options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      random = Math.random
    } = options;
    let matrix = new Matrix$1(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        matrix.set(i, j, random());
      }
    }
    return matrix;
  }
  static randInt(rows, columns, options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      min = 0,
      max = 1000,
      random = Math.random
    } = options;
    if (!Number.isInteger(min)) throw new TypeError('min must be an integer');
    if (!Number.isInteger(max)) throw new TypeError('max must be an integer');
    if (min >= max) throw new RangeError('min must be smaller than max');
    let interval = max - min;
    let matrix = new Matrix$1(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        let value = min + Math.round(random() * interval);
        matrix.set(i, j, value);
      }
    }
    return matrix;
  }
  static eye(rows, columns, value) {
    if (columns === undefined) columns = rows;
    if (value === undefined) value = 1;
    let min = Math.min(rows, columns);
    let matrix = this.zeros(rows, columns);
    for (let i = 0; i < min; i++) {
      matrix.set(i, i, value);
    }
    return matrix;
  }
  static diag(data, rows, columns) {
    let l = data.length;
    if (rows === undefined) rows = l;
    if (columns === undefined) columns = rows;
    let min = Math.min(l, rows, columns);
    let matrix = this.zeros(rows, columns);
    for (let i = 0; i < min; i++) {
      matrix.set(i, i, data[i]);
    }
    return matrix;
  }
  static min(matrix1, matrix2) {
    matrix1 = this.checkMatrix(matrix1);
    matrix2 = this.checkMatrix(matrix2);
    let rows = matrix1.rows;
    let columns = matrix1.columns;
    let result = new Matrix$1(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));
      }
    }
    return result;
  }
  static max(matrix1, matrix2) {
    matrix1 = this.checkMatrix(matrix1);
    matrix2 = this.checkMatrix(matrix2);
    let rows = matrix1.rows;
    let columns = matrix1.columns;
    let result = new this(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));
      }
    }
    return result;
  }
  static checkMatrix(value) {
    return AbstractMatrix.isMatrix(value) ? value : new Matrix$1(value);
  }
  static isMatrix(value) {
    return value != null && value.klass === 'Matrix';
  }
  get size() {
    return this.rows * this.columns;
  }
  apply(callback) {
    if (typeof callback !== 'function') {
      throw new TypeError('callback must be a function');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        callback.call(this, i, j);
      }
    }
    return this;
  }
  to1DArray() {
    let array = [];
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        array.push(this.get(i, j));
      }
    }
    return array;
  }
  to2DArray() {
    let copy = [];
    for (let i = 0; i < this.rows; i++) {
      copy.push([]);
      for (let j = 0; j < this.columns; j++) {
        copy[i].push(this.get(i, j));
      }
    }
    return copy;
  }
  toJSON() {
    return this.to2DArray();
  }
  isRowVector() {
    return this.rows === 1;
  }
  isColumnVector() {
    return this.columns === 1;
  }
  isVector() {
    return this.rows === 1 || this.columns === 1;
  }
  isSquare() {
    return this.rows === this.columns;
  }
  isEmpty() {
    return this.rows === 0 || this.columns === 0;
  }
  isSymmetric() {
    if (this.isSquare()) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j <= i; j++) {
          if (this.get(i, j) !== this.get(j, i)) {
            return false;
          }
        }
      }
      return true;
    }
    return false;
  }
  isDistance() {
    if (!this.isSymmetric()) return false;
    for (let i = 0; i < this.rows; i++) {
      if (this.get(i, i) !== 0) return false;
    }
    return true;
  }
  isEchelonForm() {
    let i = 0;
    let j = 0;
    let previousColumn = -1;
    let isEchelonForm = true;
    let checked = false;
    while (i < this.rows && isEchelonForm) {
      j = 0;
      checked = false;
      while (j < this.columns && checked === false) {
        if (this.get(i, j) === 0) {
          j++;
        } else if (this.get(i, j) === 1 && j > previousColumn) {
          checked = true;
          previousColumn = j;
        } else {
          isEchelonForm = false;
          checked = true;
        }
      }
      i++;
    }
    return isEchelonForm;
  }
  isReducedEchelonForm() {
    let i = 0;
    let j = 0;
    let previousColumn = -1;
    let isReducedEchelonForm = true;
    let checked = false;
    while (i < this.rows && isReducedEchelonForm) {
      j = 0;
      checked = false;
      while (j < this.columns && checked === false) {
        if (this.get(i, j) === 0) {
          j++;
        } else if (this.get(i, j) === 1 && j > previousColumn) {
          checked = true;
          previousColumn = j;
        } else {
          isReducedEchelonForm = false;
          checked = true;
        }
      }
      for (let k = j + 1; k < this.rows; k++) {
        if (this.get(i, k) !== 0) {
          isReducedEchelonForm = false;
        }
      }
      i++;
    }
    return isReducedEchelonForm;
  }
  echelonForm() {
    let result = this.clone();
    let h = 0;
    let k = 0;
    while (h < result.rows && k < result.columns) {
      let iMax = h;
      for (let i = h; i < result.rows; i++) {
        if (result.get(i, k) > result.get(iMax, k)) {
          iMax = i;
        }
      }
      if (result.get(iMax, k) === 0) {
        k++;
      } else {
        result.swapRows(h, iMax);
        let tmp = result.get(h, k);
        for (let j = k; j < result.columns; j++) {
          result.set(h, j, result.get(h, j) / tmp);
        }
        for (let i = h + 1; i < result.rows; i++) {
          let factor = result.get(i, k) / result.get(h, k);
          result.set(i, k, 0);
          for (let j = k + 1; j < result.columns; j++) {
            result.set(i, j, result.get(i, j) - result.get(h, j) * factor);
          }
        }
        h++;
        k++;
      }
    }
    return result;
  }
  reducedEchelonForm() {
    let result = this.echelonForm();
    let m = result.columns;
    let n = result.rows;
    let h = n - 1;
    while (h >= 0) {
      if (result.maxRow(h) === 0) {
        h--;
      } else {
        let p = 0;
        let pivot = false;
        while (p < n && pivot === false) {
          if (result.get(h, p) === 1) {
            pivot = true;
          } else {
            p++;
          }
        }
        for (let i = 0; i < h; i++) {
          let factor = result.get(i, p);
          for (let j = p; j < m; j++) {
            let tmp = result.get(i, j) - factor * result.get(h, j);
            result.set(i, j, tmp);
          }
        }
        h--;
      }
    }
    return result;
  }
  set() {
    throw new Error('set method is unimplemented');
  }
  get() {
    throw new Error('get method is unimplemented');
  }
  repeat(options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      rows = 1,
      columns = 1
    } = options;
    if (!Number.isInteger(rows) || rows <= 0) {
      throw new TypeError('rows must be a positive integer');
    }
    if (!Number.isInteger(columns) || columns <= 0) {
      throw new TypeError('columns must be a positive integer');
    }
    let matrix = new Matrix$1(this.rows * rows, this.columns * columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        matrix.setSubMatrix(this, this.rows * i, this.columns * j);
      }
    }
    return matrix;
  }
  fill(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, value);
      }
    }
    return this;
  }
  neg() {
    return this.mulS(-1);
  }
  getRow(index) {
    checkRowIndex(this, index);
    let row = [];
    for (let i = 0; i < this.columns; i++) {
      row.push(this.get(index, i));
    }
    return row;
  }
  getRowVector(index) {
    return Matrix$1.rowVector(this.getRow(index));
  }
  setRow(index, array) {
    checkRowIndex(this, index);
    array = checkRowVector(this, array);
    for (let i = 0; i < this.columns; i++) {
      this.set(index, i, array[i]);
    }
    return this;
  }
  swapRows(row1, row2) {
    checkRowIndex(this, row1);
    checkRowIndex(this, row2);
    for (let i = 0; i < this.columns; i++) {
      let temp = this.get(row1, i);
      this.set(row1, i, this.get(row2, i));
      this.set(row2, i, temp);
    }
    return this;
  }
  getColumn(index) {
    checkColumnIndex(this, index);
    let column = [];
    for (let i = 0; i < this.rows; i++) {
      column.push(this.get(i, index));
    }
    return column;
  }
  getColumnVector(index) {
    return Matrix$1.columnVector(this.getColumn(index));
  }
  setColumn(index, array) {
    checkColumnIndex(this, index);
    array = checkColumnVector(this, array);
    for (let i = 0; i < this.rows; i++) {
      this.set(i, index, array[i]);
    }
    return this;
  }
  swapColumns(column1, column2) {
    checkColumnIndex(this, column1);
    checkColumnIndex(this, column2);
    for (let i = 0; i < this.rows; i++) {
      let temp = this.get(i, column1);
      this.set(i, column1, this.get(i, column2));
      this.set(i, column2, temp);
    }
    return this;
  }
  addRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + vector[j]);
      }
    }
    return this;
  }
  subRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - vector[j]);
      }
    }
    return this;
  }
  mulRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * vector[j]);
      }
    }
    return this;
  }
  divRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / vector[j]);
      }
    }
    return this;
  }
  addColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + vector[i]);
      }
    }
    return this;
  }
  subColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - vector[i]);
      }
    }
    return this;
  }
  mulColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * vector[i]);
      }
    }
    return this;
  }
  divColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / vector[i]);
      }
    }
    return this;
  }
  mulRow(index, value) {
    checkRowIndex(this, index);
    for (let i = 0; i < this.columns; i++) {
      this.set(index, i, this.get(index, i) * value);
    }
    return this;
  }
  mulColumn(index, value) {
    checkColumnIndex(this, index);
    for (let i = 0; i < this.rows; i++) {
      this.set(i, index, this.get(i, index) * value);
    }
    return this;
  }
  max(by) {
    if (this.isEmpty()) {
      return NaN;
    }
    switch (by) {
      case 'row':
        {
          const max = new Array(this.rows).fill(Number.NEGATIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) > max[row]) {
                max[row] = this.get(row, column);
              }
            }
          }
          return max;
        }
      case 'column':
        {
          const max = new Array(this.columns).fill(Number.NEGATIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) > max[column]) {
                max[column] = this.get(row, column);
              }
            }
          }
          return max;
        }
      case undefined:
        {
          let max = this.get(0, 0);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) > max) {
                max = this.get(row, column);
              }
            }
          }
          return max;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  maxIndex() {
    checkNonEmpty(this);
    let v = this.get(0, 0);
    let idx = [0, 0];
    for (let i = 0; i < this.rows; i++) {
      for (let 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;
  }
  min(by) {
    if (this.isEmpty()) {
      return NaN;
    }
    switch (by) {
      case 'row':
        {
          const min = new Array(this.rows).fill(Number.POSITIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) < min[row]) {
                min[row] = this.get(row, column);
              }
            }
          }
          return min;
        }
      case 'column':
        {
          const min = new Array(this.columns).fill(Number.POSITIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) < min[column]) {
                min[column] = this.get(row, column);
              }
            }
          }
          return min;
        }
      case undefined:
        {
          let min = this.get(0, 0);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) < min) {
                min = this.get(row, column);
              }
            }
          }
          return min;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  minIndex() {
    checkNonEmpty(this);
    let v = this.get(0, 0);
    let idx = [0, 0];
    for (let i = 0; i < this.rows; i++) {
      for (let 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;
  }
  maxRow(row) {
    checkRowIndex(this, row);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(row, 0);
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) > v) {
        v = this.get(row, i);
      }
    }
    return v;
  }
  maxRowIndex(row) {
    checkRowIndex(this, row);
    checkNonEmpty(this);
    let v = this.get(row, 0);
    let idx = [row, 0];
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) > v) {
        v = this.get(row, i);
        idx[1] = i;
      }
    }
    return idx;
  }
  minRow(row) {
    checkRowIndex(this, row);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(row, 0);
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) < v) {
        v = this.get(row, i);
      }
    }
    return v;
  }
  minRowIndex(row) {
    checkRowIndex(this, row);
    checkNonEmpty(this);
    let v = this.get(row, 0);
    let idx = [row, 0];
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) < v) {
        v = this.get(row, i);
        idx[1] = i;
      }
    }
    return idx;
  }
  maxColumn(column) {
    checkColumnIndex(this, column);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(0, column);
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) > v) {
        v = this.get(i, column);
      }
    }
    return v;
  }
  maxColumnIndex(column) {
    checkColumnIndex(this, column);
    checkNonEmpty(this);
    let v = this.get(0, column);
    let idx = [0, column];
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) > v) {
        v = this.get(i, column);
        idx[0] = i;
      }
    }
    return idx;
  }
  minColumn(column) {
    checkColumnIndex(this, column);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(0, column);
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) < v) {
        v = this.get(i, column);
      }
    }
    return v;
  }
  minColumnIndex(column) {
    checkColumnIndex(this, column);
    checkNonEmpty(this);
    let v = this.get(0, column);
    let idx = [0, column];
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) < v) {
        v = this.get(i, column);
        idx[0] = i;
      }
    }
    return idx;
  }
  diag() {
    let min = Math.min(this.rows, this.columns);
    let diag = [];
    for (let i = 0; i < min; i++) {
      diag.push(this.get(i, i));
    }
    return diag;
  }
  norm(type = 'frobenius') {
    switch (type) {
      case 'max':
        return this.max();
      case 'frobenius':
        return Math.sqrt(this.dot(this));
      default:
        throw new RangeError(`unknown norm type: ${type}`);
    }
  }
  cumulativeSum() {
    let sum = 0;
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        sum += this.get(i, j);
        this.set(i, j, sum);
      }
    }
    return this;
  }
  dot(vector2) {
    if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();
    let vector1 = this.to1DArray();
    if (vector1.length !== vector2.length) {
      throw new RangeError('vectors do not have the same size');
    }
    let dot = 0;
    for (let i = 0; i < vector1.length; i++) {
      dot += vector1[i] * vector2[i];
    }
    return dot;
  }
  mmul(other) {
    other = Matrix$1.checkMatrix(other);
    let m = this.rows;
    let n = this.columns;
    let p = other.columns;
    let result = new Matrix$1(m, p);
    let Bcolj = new Float64Array(n);
    for (let j = 0; j < p; j++) {
      for (let k = 0; k < n; k++) {
        Bcolj[k] = other.get(k, j);
      }
      for (let i = 0; i < m; i++) {
        let s = 0;
        for (let k = 0; k < n; k++) {
          s += this.get(i, k) * Bcolj[k];
        }
        result.set(i, j, s);
      }
    }
    return result;
  }
  mpow(scalar) {
    if (!this.isSquare()) {
      throw new RangeError('Matrix must be square');
    }
    if (!Number.isInteger(scalar) || scalar < 0) {
      throw new RangeError('Exponent must be a non-negative integer');
    }
    // Russian Peasant exponentiation, i.e. exponentiation by squaring
    let result = Matrix$1.eye(this.rows);
    let bb = this;
    // Note: Don't bit shift. In JS, that would truncate at 32 bits
    for (let e = scalar; e >= 1; e /= 2) {
      if ((e & 1) !== 0) {
        result = result.mmul(bb);
      }
      bb = bb.mmul(bb);
    }
    return result;
  }
  strassen2x2(other) {
    other = Matrix$1.checkMatrix(other);
    let result = new Matrix$1(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) {
    other = Matrix$1.checkMatrix(other);
    let result = new Matrix$1(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;
  }
  mmulStrassen(y) {
    y = Matrix$1.checkMatrix(y);
    let x = this.clone();
    let r1 = x.rows;
    let c1 = x.columns;
    let r2 = y.rows;
    let 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) {
      let r = mat.rows;
      let c = mat.columns;
      if (r === rows && c === cols) {
        return mat;
      } else {
        let resultat = AbstractMatrix.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.

    let r = Math.max(r1, r2);
    let 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);
      }
      let halfRows = parseInt(a.rows / 2, 10);
      let halfCols = parseInt(a.columns / 2, 10);
      // Subdivide input matrices.
      let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);
      let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);
      let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);
      let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);
      let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);
      let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);
      let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);
      let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);

      // Compute intermediate values.
      let m1 = blockMult(AbstractMatrix.add(a11, a22), AbstractMatrix.add(b11, b22), halfRows, halfCols);
      let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);
      let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);
      let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);
      let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);
      let m6 = blockMult(AbstractMatrix.sub(a21, a11), AbstractMatrix.add(b11, b12), halfRows, halfCols);
      let m7 = blockMult(AbstractMatrix.sub(a12, a22), AbstractMatrix.add(b21, b22), halfRows, halfCols);

      // Combine intermediate values into the output.
      let c11 = AbstractMatrix.add(m1, m4);
      c11.sub(m5);
      c11.add(m7);
      let c12 = AbstractMatrix.add(m3, m5);
      let c21 = AbstractMatrix.add(m2, m4);
      let c22 = AbstractMatrix.sub(m1, m2);
      c22.add(m3);
      c22.add(m6);

      // Crop output to the desired size (undo dynamic padding).
      let result = AbstractMatrix.zeros(2 * c11.rows, 2 * c11.columns);
      result = result.setSubMatrix(c11, 0, 0);
      result = result.setSubMatrix(c12, c11.rows, 0);
      result = result.setSubMatrix(c21, 0, c11.columns);
      result = result.setSubMatrix(c22, c11.rows, c11.columns);
      return result.subMatrix(0, rows - 1, 0, cols - 1);
    }
    return blockMult(x, y, r, c);
  }
  scaleRows(options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      min = 0,
      max = 1
    } = options;
    if (!Number.isFinite(min)) throw new TypeError('min must be a number');
    if (!Number.isFinite(max)) throw new TypeError('max must be a number');
    if (min >= max) throw new RangeError('min must be smaller than max');
    let newMatrix = new Matrix$1(this.rows, this.columns);
    for (let i = 0; i < this.rows; i++) {
      const row = this.getRow(i);
      if (row.length > 0) {
        rescale$1(row, {
          min,
          max,
          output: row
        });
      }
      newMatrix.setRow(i, row);
    }
    return newMatrix;
  }
  scaleColumns(options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      min = 0,
      max = 1
    } = options;
    if (!Number.isFinite(min)) throw new TypeError('min must be a number');
    if (!Number.isFinite(max)) throw new TypeError('max must be a number');
    if (min >= max) throw new RangeError('min must be smaller than max');
    let newMatrix = new Matrix$1(this.rows, this.columns);
    for (let i = 0; i < this.columns; i++) {
      const column = this.getColumn(i);
      if (column.length) {
        rescale$1(column, {
          min,
          max,
          output: column
        });
      }
      newMatrix.setColumn(i, column);
    }
    return newMatrix;
  }
  flipRows() {
    const middle = Math.ceil(this.columns / 2);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < middle; j++) {
        let first = this.get(i, j);
        let last = this.get(i, this.columns - 1 - j);
        this.set(i, j, last);
        this.set(i, this.columns - 1 - j, first);
      }
    }
    return this;
  }
  flipColumns() {
    const middle = Math.ceil(this.rows / 2);
    for (let j = 0; j < this.columns; j++) {
      for (let i = 0; i < middle; i++) {
        let first = this.get(i, j);
        let last = this.get(this.rows - 1 - i, j);
        this.set(i, j, last);
        this.set(this.rows - 1 - i, j, first);
      }
    }
    return this;
  }
  kroneckerProduct(other) {
    other = Matrix$1.checkMatrix(other);
    let m = this.rows;
    let n = this.columns;
    let p = other.rows;
    let q = other.columns;
    let result = new Matrix$1(m * p, n * q);
    for (let i = 0; i < m; i++) {
      for (let j = 0; j < n; j++) {
        for (let k = 0; k < p; k++) {
          for (let l = 0; l < q; l++) {
            result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));
          }
        }
      }
    }
    return result;
  }
  kroneckerSum(other) {
    other = Matrix$1.checkMatrix(other);
    if (!this.isSquare() || !other.isSquare()) {
      throw new Error('Kronecker Sum needs two Square Matrices');
    }
    let m = this.rows;
    let n = other.rows;
    let AxI = this.kroneckerProduct(Matrix$1.eye(n, n));
    let IxB = Matrix$1.eye(m, m).kroneckerProduct(other);
    return AxI.add(IxB);
  }
  transpose() {
    let result = new Matrix$1(this.columns, this.rows);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        result.set(j, i, this.get(i, j));
      }
    }
    return result;
  }
  sortRows(compareFunction = compareNumbers) {
    for (let i = 0; i < this.rows; i++) {
      this.setRow(i, this.getRow(i).sort(compareFunction));
    }
    return this;
  }
  sortColumns(compareFunction = compareNumbers) {
    for (let i = 0; i < this.columns; i++) {
      this.setColumn(i, this.getColumn(i).sort(compareFunction));
    }
    return this;
  }
  subMatrix(startRow, endRow, startColumn, endColumn) {
    checkRange(this, startRow, endRow, startColumn, endColumn);
    let newMatrix = new Matrix$1(endRow - startRow + 1, endColumn - startColumn + 1);
    for (let i = startRow; i <= endRow; i++) {
      for (let j = startColumn; j <= endColumn; j++) {
        newMatrix.set(i - startRow, j - startColumn, this.get(i, j));
      }
    }
    return newMatrix;
  }
  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');
    }
    let newMatrix = new Matrix$1(indices.length, endColumn - startColumn + 1);
    for (let i = 0; i < indices.length; i++) {
      for (let 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;
  }
  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');
    }
    let newMatrix = new Matrix$1(endRow - startRow + 1, indices.length);
    for (let i = 0; i < indices.length; i++) {
      for (let 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;
  }
  setSubMatrix(matrix, startRow, startColumn) {
    matrix = Matrix$1.checkMatrix(matrix);
    if (matrix.isEmpty()) {
      return this;
    }
    let endRow = startRow + matrix.rows - 1;
    let endColumn = startColumn + matrix.columns - 1;
    checkRange(this, startRow, endRow, startColumn, endColumn);
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        this.set(startRow + i, startColumn + j, matrix.get(i, j));
      }
    }
    return this;
  }
  selection(rowIndices, columnIndices) {
    checkRowIndices(this, rowIndices);
    checkColumnIndices(this, columnIndices);
    let newMatrix = new Matrix$1(rowIndices.length, columnIndices.length);
    for (let i = 0; i < rowIndices.length; i++) {
      let rowIndex = rowIndices[i];
      for (let j = 0; j < columnIndices.length; j++) {
        let columnIndex = columnIndices[j];
        newMatrix.set(i, j, this.get(rowIndex, columnIndex));
      }
    }
    return newMatrix;
  }
  trace() {
    let min = Math.min(this.rows, this.columns);
    let trace = 0;
    for (let i = 0; i < min; i++) {
      trace += this.get(i, i);
    }
    return trace;
  }
  clone() {
    return this.constructor.copy(this, new Matrix$1(this.rows, this.columns));
  }

  /**
   * @template {AbstractMatrix} M
   * @param {AbstractMatrix} from
   * @param {M} to
   * @return {M}
   */
  static copy(from, to) {
    for (const [row, column, value] of from.entries()) {
      to.set(row, column, value);
    }
    return to;
  }
  sum(by) {
    switch (by) {
      case 'row':
        return sumByRow(this);
      case 'column':
        return sumByColumn(this);
      case undefined:
        return sumAll(this);
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  product(by) {
    switch (by) {
      case 'row':
        return productByRow(this);
      case 'column':
        return productByColumn(this);
      case undefined:
        return productAll(this);
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  mean(by) {
    const sum = this.sum(by);
    switch (by) {
      case 'row':
        {
          for (let i = 0; i < this.rows; i++) {
            sum[i] /= this.columns;
          }
          return sum;
        }
      case 'column':
        {
          for (let i = 0; i < this.columns; i++) {
            sum[i] /= this.rows;
          }
          return sum;
        }
      case undefined:
        return sum / this.size;
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  variance(by, options = {}) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      unbiased = true,
      mean = this.mean(by)
    } = options;
    if (typeof unbiased !== 'boolean') {
      throw new TypeError('unbiased must be a boolean');
    }
    switch (by) {
      case 'row':
        {
          if (!isAnyArray.isAnyArray(mean)) {
            throw new TypeError('mean must be an array');
          }
          return varianceByRow(this, unbiased, mean);
        }
      case 'column':
        {
          if (!isAnyArray.isAnyArray(mean)) {
            throw new TypeError('mean must be an array');
          }
          return varianceByColumn(this, unbiased, mean);
        }
      case undefined:
        {
          if (typeof mean !== 'number') {
            throw new TypeError('mean must be a number');
          }
          return varianceAll(this, unbiased, mean);
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  standardDeviation(by, options) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    const variance = this.variance(by, options);
    if (by === undefined) {
      return Math.sqrt(variance);
    } else {
      for (let i = 0; i < variance.length; i++) {
        variance[i] = Math.sqrt(variance[i]);
      }
      return variance;
    }
  }
  center(by, options = {}) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      center = this.mean(by)
    } = options;
    switch (by) {
      case 'row':
        {
          if (!isAnyArray.isAnyArray(center)) {
            throw new TypeError('center must be an array');
          }
          centerByRow(this, center);
          return this;
        }
      case 'column':
        {
          if (!isAnyArray.isAnyArray(center)) {
            throw new TypeError('center must be an array');
          }
          centerByColumn(this, center);
          return this;
        }
      case undefined:
        {
          if (typeof center !== 'number') {
            throw new TypeError('center must be a number');
          }
          centerAll(this, center);
          return this;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  scale(by, options = {}) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    let scale = options.scale;
    switch (by) {
      case 'row':
        {
          if (scale === undefined) {
            scale = getScaleByRow(this);
          } else if (!isAnyArray.isAnyArray(scale)) {
            throw new TypeError('scale must be an array');
          }
          scaleByRow(this, scale);
          return this;
        }
      case 'column':
        {
          if (scale === undefined) {
            scale = getScaleByColumn(this);
          } else if (!isAnyArray.isAnyArray(scale)) {
            throw new TypeError('scale must be an array');
          }
          scaleByColumn(this, scale);
          return this;
        }
      case undefined:
        {
          if (scale === undefined) {
            scale = getScaleAll(this);
          } else if (typeof scale !== 'number') {
            throw new TypeError('scale must be a number');
          }
          scaleAll(this, scale);
          return this;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  toString(options) {
    return inspectMatrixWithOptions(this, options);
  }
  [Symbol.iterator]() {
    return this.entries();
  }

  /**
   * iterator from left to right, from top to bottom
   * yield [row, column, value]
   * @returns {Generator<[number, number, number], void, void>}
   */
  *entries() {
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.columns; col++) {
        yield [row, col, this.get(row, col)];
      }
    }
  }

  /**
   * iterator from left to right, from top to bottom
   * yield value
   * @returns {Generator<number, void, void>}
   */
  *values() {
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.columns; col++) {
        yield this.get(row, col);
      }
    }
  }
}
AbstractMatrix.prototype.klass = 'Matrix';
if (typeof Symbol !== 'undefined') {
  AbstractMatrix.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspectMatrix;
}
function compareNumbers(a, b) {
  return a - b;
}
function isArrayOfNumbers(array) {
  return array.every(element => {
    return typeof element === 'number';
  });
}

// Synonyms
AbstractMatrix.random = AbstractMatrix.rand;
AbstractMatrix.randomInt = AbstractMatrix.randInt;
AbstractMatrix.diagonal = AbstractMatrix.diag;
AbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;
AbstractMatrix.identity = AbstractMatrix.eye;
AbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;
AbstractMatrix.prototype.tensorProduct = AbstractMatrix.prototype.kroneckerProduct;
let Matrix$1 = class Matrix extends AbstractMatrix {
  /**
   * @type {Float64Array[]}
   */
  data;

  /**
   * Init an empty matrix
   * @param {number} nRows
   * @param {number} nColumns
   */
  #initData(nRows, nColumns) {
    this.data = [];
    if (Number.isInteger(nColumns) && nColumns >= 0) {
      for (let i = 0; i < nRows; i++) {
        this.data.push(new Float64Array(nColumns));
      }
    } else {
      throw new TypeError('nColumns must be a positive integer');
    }
    this.rows = nRows;
    this.columns = nColumns;
  }
  constructor(nRows, nColumns) {
    super();
    if (Matrix.isMatrix(nRows)) {
      this.#initData(nRows.rows, nRows.columns);
      Matrix.copy(nRows, this);
    } else if (Number.isInteger(nRows) && nRows >= 0) {
      this.#initData(nRows, nColumns);
    } else if (isAnyArray.isAnyArray(nRows)) {
      // Copy the values from the 2D array
      const arrayData = nRows;
      nRows = arrayData.length;
      nColumns = nRows ? arrayData[0].length : 0;
      if (typeof nColumns !== 'number') {
        throw new TypeError('Data must be a 2D array with at least one element');
      }
      this.data = [];
      for (let i = 0; i < nRows; i++) {
        if (arrayData[i].length !== nColumns) {
          throw new RangeError('Inconsistent array dimensions');
        }
        if (!isArrayOfNumbers(arrayData[i])) {
          throw new TypeError('Input data contains non-numeric values');
        }
        this.data.push(Float64Array.from(arrayData[i]));
      }
      this.rows = nRows;
      this.columns = nColumns;
    } else {
      throw new TypeError('First argument must be a positive number or an array');
    }
  }
  set(rowIndex, columnIndex, value) {
    this.data[rowIndex][columnIndex] = value;
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.data[rowIndex][columnIndex];
  }
  removeRow(index) {
    checkRowIndex(this, index);
    this.data.splice(index, 1);
    this.rows -= 1;
    return this;
  }
  addRow(index, array) {
    if (array === undefined) {
      array = index;
      index = this.rows;
    }
    checkRowIndex(this, index, true);
    array = Float64Array.from(checkRowVector(this, array));
    this.data.splice(index, 0, array);
    this.rows += 1;
    return this;
  }
  removeColumn(index) {
    checkColumnIndex(this, index);
    for (let i = 0; i < this.rows; i++) {
      const newRow = new Float64Array(this.columns - 1);
      for (let j = 0; j < index; j++) {
        newRow[j] = this.data[i][j];
      }
      for (let j = index + 1; j < this.columns; j++) {
        newRow[j - 1] = this.data[i][j];
      }
      this.data[i] = newRow;
    }
    this.columns -= 1;
    return this;
  }
  addColumn(index, array) {
    if (typeof array === 'undefined') {
      array = index;
      index = this.columns;
    }
    checkColumnIndex(this, index, true);
    array = checkColumnVector(this, array);
    for (let i = 0; i < this.rows; i++) {
      const newRow = new Float64Array(this.columns + 1);
      let j = 0;
      for (; j < index; j++) {
        newRow[j] = this.data[i][j];
      }
      newRow[j++] = array[i];
      for (; j < this.columns + 1; j++) {
        newRow[j] = this.data[i][j - 1];
      }
      this.data[i] = newRow;
    }
    this.columns += 1;
    return this;
  }
};
installMathOperations(AbstractMatrix, Matrix$1);

/**
 * @typedef {0 | 1 | number | boolean} Mask
 */

class SymmetricMatrix extends AbstractMatrix {
  /** @type {Matrix} */
  #matrix;
  get size() {
    return this.#matrix.size;
  }
  get rows() {
    return this.#matrix.rows;
  }
  get columns() {
    return this.#matrix.columns;
  }
  get diagonalSize() {
    return this.rows;
  }

  /**
   * not the same as matrix.isSymmetric()
   * Here is to check if it's instanceof SymmetricMatrix without bundling issues
   *
   * @param value
   * @returns {boolean}
   */
  static isSymmetricMatrix(value) {
    return Matrix$1.isMatrix(value) && value.klassType === 'SymmetricMatrix';
  }

  /**
   * @param diagonalSize
   * @return {SymmetricMatrix}
   */
  static zeros(diagonalSize) {
    return new this(diagonalSize);
  }

  /**
   * @param diagonalSize
   * @return {SymmetricMatrix}
   */
  static ones(diagonalSize) {
    return new this(diagonalSize).fill(1);
  }

  /**
   * @param {number | AbstractMatrix | ArrayLike<ArrayLike<number>>} diagonalSize
   * @return {this}
   */
  constructor(diagonalSize) {
    super();
    if (Matrix$1.isMatrix(diagonalSize)) {
      if (!diagonalSize.isSymmetric()) {
        throw new TypeError('not symmetric data');
      }
      this.#matrix = Matrix$1.copy(diagonalSize, new Matrix$1(diagonalSize.rows, diagonalSize.rows));
    } else if (Number.isInteger(diagonalSize) && diagonalSize >= 0) {
      this.#matrix = new Matrix$1(diagonalSize, diagonalSize);
    } else {
      this.#matrix = new Matrix$1(diagonalSize);
      if (!this.isSymmetric()) {
        throw new TypeError('not symmetric data');
      }
    }
  }
  clone() {
    const matrix = new SymmetricMatrix(this.diagonalSize);
    for (const [row, col, value] of this.upperRightEntries()) {
      matrix.set(row, col, value);
    }
    return matrix;
  }
  toMatrix() {
    return new Matrix$1(this);
  }
  get(rowIndex, columnIndex) {
    return this.#matrix.get(rowIndex, columnIndex);
  }
  set(rowIndex, columnIndex, value) {
    // symmetric set
    this.#matrix.set(rowIndex, columnIndex, value);
    this.#matrix.set(columnIndex, rowIndex, value);
    return this;
  }
  removeCross(index) {
    // symmetric remove side
    this.#matrix.removeRow(index);
    this.#matrix.removeColumn(index);
    return this;
  }
  addCross(index, array) {
    if (array === undefined) {
      array = index;
      index = this.diagonalSize;
    }
    const row = array.slice();
    row.splice(index, 1);
    this.#matrix.addRow(index, row);
    this.#matrix.addColumn(index, array);
    return this;
  }

  /**
   * @param {Mask[]} mask
   */
  applyMask(mask) {
    if (mask.length !== this.diagonalSize) {
      throw new RangeError('Mask size do not match with matrix size');
    }

    // prepare sides to remove from matrix from mask
    /** @type {number[]} */
    const sidesToRemove = [];
    for (const [index, passthroughs] of mask.entries()) {
      if (passthroughs) continue;
      sidesToRemove.push(index);
    }
    // to remove from highest to lowest for no mutation shifting
    sidesToRemove.reverse();

    // remove sides
    for (const sideIndex of sidesToRemove) {
      this.removeCross(sideIndex);
    }
    return this;
  }

  /**
   * Compact format upper-right corner of matrix
   * iterate from left to right, from top to bottom.
   *
   * ```
   *   A B C D
   * A 1 2 3 4
   * B 2 5 6 7
   * C 3 6 8 9
   * D 4 7 9 10
   * ```
   *
   * will return compact 1D array `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
   *
   * length is S(i=0, n=sideSize) => 10 for a 4 sideSized matrix
   *
   * @returns {number[]}
   */
  toCompact() {
    const {
      diagonalSize
    } = this;

    /** @type {number[]} */
    const compact = new Array(diagonalSize * (diagonalSize + 1) / 2);
    for (let col = 0, row = 0, index = 0; index < compact.length; index++) {
      compact[index] = this.get(row, col);
      if (++col >= diagonalSize) col = ++row;
    }
    return compact;
  }

  /**
   * @param {number[]} compact
   * @return {SymmetricMatrix}
   */
  static fromCompact(compact) {
    const compactSize = compact.length;
    // compactSize = (sideSize * (sideSize + 1)) / 2
    // https://mathsolver.microsoft.com/fr/solve-problem/y%20%3D%20%20x%20%60cdot%20%20%20%60frac%7B%20%20%60left(%20x%2B1%20%20%60right)%20%20%20%20%7D%7B%202%20%20%7D
    // sideSize = (Sqrt(8 × compactSize + 1) - 1) / 2
    const diagonalSize = (Math.sqrt(8 * compactSize + 1) - 1) / 2;
    if (!Number.isInteger(diagonalSize)) {
      throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(compact)}`);
    }
    const matrix = new SymmetricMatrix(diagonalSize);
    for (let col = 0, row = 0, index = 0; index < compactSize; index++) {
      matrix.set(col, row, compact[index]);
      if (++col >= diagonalSize) col = ++row;
    }
    return matrix;
  }

  /**
   * half iterator upper-right-corner from left to right, from top to bottom
   * yield [row, column, value]
   *
   * @returns {Generator<[number, number, number], void, void>}
   */
  *upperRightEntries() {
    for (let row = 0, col = 0; row < this.diagonalSize; void 0) {
      const value = this.get(row, col);
      yield [row, col, value];

      // at the end of row, move cursor to next row at diagonal position
      if (++col >= this.diagonalSize) col = ++row;
    }
  }

  /**
   * half iterator upper-right-corner from left to right, from top to bottom
   * yield value
   *
   * @returns {Generator<[number, number, number], void, void>}
   */
  *upperRightValues() {
    for (let row = 0, col = 0; row < this.diagonalSize; void 0) {
      const value = this.get(row, col);
      yield value;

      // at the end of row, move cursor to next row at diagonal position
      if (++col >= this.diagonalSize) col = ++row;
    }
  }
}
SymmetricMatrix.prototype.klassType = 'SymmetricMatrix';
class DistanceMatrix extends SymmetricMatrix {
  /**
   * not the same as matrix.isSymmetric()
   * Here is to check if it's instanceof SymmetricMatrix without bundling issues
   *
   * @param value
   * @returns {boolean}
   */
  static isDistanceMatrix(value) {
    return SymmetricMatrix.isSymmetricMatrix(value) && value.klassSubType === 'DistanceMatrix';
  }
  constructor(sideSize) {
    super(sideSize);
    if (!this.isDistance()) {
      throw new TypeError('Provided arguments do no produce a distance matrix');
    }
  }
  set(rowIndex, columnIndex, value) {
    // distance matrix diagonal is 0
    if (rowIndex === columnIndex) value = 0;
    return super.set(rowIndex, columnIndex, value);
  }
  addCross(index, array) {
    if (array === undefined) {
      array = index;
      index = this.diagonalSize;
    }

    // ensure distance
    array = array.slice();
    array[index] = 0;
    return super.addCross(index, array);
  }
  toSymmetricMatrix() {
    return new SymmetricMatrix(this);
  }
  clone() {
    const matrix = new DistanceMatrix(this.diagonalSize);
    for (const [row, col, value] of this.upperRightEntries()) {
      if (row === col) continue;
      matrix.set(row, col, value);
    }
    return matrix;
  }

  /**
   * Compact format upper-right corner of matrix
   * no diagonal (only zeros)
   * iterable from left to right, from top to bottom.
   *
   * ```
   *   A B C D
   * A 0 1 2 3
   * B 1 0 4 5
   * C 2 4 0 6
   * D 3 5 6 0
   * ```
   *
   * will return compact 1D array `[1, 2, 3, 4, 5, 6]`
   *
   * length is S(i=0, n=sideSize-1) => 6 for a 4 side sized matrix
   *
   * @returns {number[]}
   */
  toCompact() {
    const {
      diagonalSize
    } = this;
    const compactLength = (diagonalSize - 1) * diagonalSize / 2;

    /** @type {number[]} */
    const compact = new Array(compactLength);
    for (let col = 1, row = 0, index = 0; index < compact.length; index++) {
      compact[index] = this.get(row, col);
      if (++col >= diagonalSize) col = ++row + 1;
    }
    return compact;
  }

  /**
   * @param {number[]} compact
   */
  static fromCompact(compact) {
    const compactSize = compact.length;
    if (compactSize === 0) {
      return new this(0);
    }

    // compactSize in Natural integer range ]0;∞]
    // compactSize = (sideSize * (sideSize - 1)) / 2
    // sideSize = (Sqrt(8 × compactSize + 1) + 1) / 2
    const diagonalSize = (Math.sqrt(8 * compactSize + 1) + 1) / 2;
    if (!Number.isInteger(diagonalSize)) {
      throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(compact)}`);
    }
    const matrix = new this(diagonalSize);
    for (let col = 1, row = 0, index = 0; index < compactSize; index++) {
      matrix.set(col, row, compact[index]);
      if (++col >= diagonalSize) col = ++row + 1;
    }
    return matrix;
  }
}
DistanceMatrix.prototype.klassSubType = 'DistanceMatrix';
class BaseView extends AbstractMatrix {
  constructor(matrix, rows, columns) {
    super();
    this.matrix = matrix;
    this.rows = rows;
    this.columns = columns;
  }
}
class MatrixColumnView extends BaseView {
  constructor(matrix, column) {
    checkColumnIndex(matrix, column);
    super(matrix, matrix.rows, 1);
    this.column = column;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(rowIndex, this.column, value);
    return this;
  }
  get(rowIndex) {
    return this.matrix.get(rowIndex, this.column);
  }
}
class MatrixColumnSelectionView extends BaseView {
  constructor(matrix, columnIndices) {
    checkColumnIndices(matrix, columnIndices);
    super(matrix, matrix.rows, columnIndices.length);
    this.columnIndices = columnIndices;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);
  }
}
class MatrixFlipColumnView extends BaseView {
  constructor(matrix) {
    super(matrix, matrix.rows, matrix.columns);
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(rowIndex, this.columns - columnIndex - 1);
  }
}
class MatrixFlipRowView extends BaseView {
  constructor(matrix) {
    super(matrix, matrix.rows, matrix.columns);
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.rows - rowIndex - 1, columnIndex);
  }
}
class MatrixRowView extends BaseView {
  constructor(matrix, row) {
    checkRowIndex(matrix, row);
    super(matrix, 1, matrix.columns);
    this.row = row;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.row, columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.row, columnIndex);
  }
}
class MatrixRowSelectionView extends BaseView {
  constructor(matrix, rowIndices) {
    checkRowIndices(matrix, rowIndices);
    super(matrix, rowIndices.length, matrix.columns);
    this.rowIndices = rowIndices;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.rowIndices[rowIndex], columnIndex);
  }
}
class MatrixSelectionView extends BaseView {
  constructor(matrix, rowIndices, columnIndices) {
    checkRowIndices(matrix, rowIndices);
    checkColumnIndices(matrix, columnIndices);
    super(matrix, rowIndices.length, columnIndices.length);
    this.rowIndices = rowIndices;
    this.columnIndices = columnIndices;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);
  }
}
class MatrixSubView extends BaseView {
  constructor(matrix, startRow, endRow, startColumn, endColumn) {
    checkRange(matrix, startRow, endRow, startColumn, endColumn);
    super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);
    this.startRow = startRow;
    this.startColumn = startColumn;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);
  }
}
let MatrixTransposeView$1 = class MatrixTransposeView extends BaseView {
  constructor(matrix) {
    super(matrix, matrix.columns, matrix.rows);
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(columnIndex, rowIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(columnIndex, rowIndex);
  }
};
class WrapperMatrix1D extends AbstractMatrix {
  constructor(data, options = {}) {
    const {
      rows = 1
    } = options;
    if (data.length % rows !== 0) {
      throw new Error('the data length is not divisible by the number of rows');
    }
    super();
    this.rows = rows;
    this.columns = data.length / rows;
    this.data = data;
  }
  set(rowIndex, columnIndex, value) {
    let index = this._calculateIndex(rowIndex, columnIndex);
    this.data[index] = value;
    return this;
  }
  get(rowIndex, columnIndex) {
    let index = this._calculateIndex(rowIndex, columnIndex);
    return this.data[index];
  }
  _calculateIndex(row, column) {
    return row * this.columns + column;
  }
}
class WrapperMatrix2D extends AbstractMatrix {
  constructor(data) {
    super();
    this.data = data;
    this.rows = data.length;
    this.columns = data[0].length;
  }
  set(rowIndex, columnIndex, value) {
    this.data[rowIndex][columnIndex] = value;
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.data[rowIndex][columnIndex];
  }
}
function wrap(array, options) {
  if (isAnyArray.isAnyArray(array)) {
    if (array[0] && isAnyArray.isAnyArray(array[0])) {
      return new WrapperMatrix2D(array);
    } else {
      return new WrapperMatrix1D(array, options);
    }
  } else {
    throw new Error('the argument is not an array');
  }
}
class LuDecomposition {
  constructor(matrix) {
    matrix = WrapperMatrix2D.checkMatrix(matrix);
    let lu = matrix.clone();
    let rows = lu.rows;
    let columns = lu.columns;
    let pivotVector = new Float64Array(rows);
    let pivotSign = 1;
    let i, j, k, p, s, t, v;
    let LUcolj, kmax;
    for (i = 0; i < rows; i++) {
      pivotVector[i] = i;
    }
    LUcolj = new Float64Array(rows);
    for (j = 0; j < columns; j++) {
      for (i = 0; i < rows; i++) {
        LUcolj[i] = lu.get(i, j);
      }
      for (i = 0; i < rows; i++) {
        kmax = Math.min(i, j);
        s = 0;
        for (k = 0; k < kmax; k++) {
          s += lu.get(i, k) * LUcolj[k];
        }
        LUcolj[i] -= s;
        lu.set(i, j, LUcolj[i]);
      }
      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.get(p, k);
          lu.set(p, k, lu.get(j, k));
          lu.set(j, k, t);
        }
        v = pivotVector[p];
        pivotVector[p] = pivotVector[j];
        pivotVector[j] = v;
        pivotSign = -pivotSign;
      }
      if (j < rows && lu.get(j, j) !== 0) {
        for (i = j + 1; i < rows; i++) {
          lu.set(i, j, lu.get(i, j) / lu.get(j, j));
        }
      }
    }
    this.LU = lu;
    this.pivotVector = pivotVector;
    this.pivotSign = pivotSign;
  }
  isSingular() {
    let data = this.LU;
    let col = data.columns;
    for (let j = 0; j < col; j++) {
      if (data.get(j, j) === 0) {
        return true;
      }
    }
    return false;
  }
  solve(value) {
    value = Matrix$1.checkMatrix(value);
    let lu = this.LU;
    let rows = lu.rows;
    if (rows !== value.rows) {
      throw new Error('Invalid matrix dimensions');
    }
    if (this.isSingular()) {
      throw new Error('LU matrix is singular');
    }
    let count = value.columns;
    let X = value.subMatrixRow(this.pivotVector, 0, count - 1);
    let columns = lu.columns;
    let i, j, k;
    for (k = 0; k < columns; k++) {
      for (i = k + 1; i < columns; i++) {
        for (j = 0; j < count; j++) {
          X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));
        }
      }
    }
    for (k = columns - 1; k >= 0; k--) {
      for (j = 0; j < count; j++) {
        X.set(k, j, X.get(k, j) / lu.get(k, k));
      }
      for (i = 0; i < k; i++) {
        for (j = 0; j < count; j++) {
          X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));
        }
      }
    }
    return X;
  }
  get determinant() {
    let data = this.LU;
    if (!data.isSquare()) {
      throw new Error('Matrix must be square');
    }
    let determinant = this.pivotSign;
    let col = data.columns;
    for (let j = 0; j < col; j++) {
      determinant *= data.get(j, j);
    }
    return determinant;
  }
  get lowerTriangularMatrix() {
    let data = this.LU;
    let rows = data.rows;
    let columns = data.columns;
    let X = new Matrix$1(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        if (i > j) {
          X.set(i, j, data.get(i, j));
        } else if (i === j) {
          X.set(i, j, 1);
        } else {
          X.set(i, j, 0);
        }
      }
    }
    return X;
  }
  get upperTriangularMatrix() {
    let data = this.LU;
    let rows = data.rows;
    let columns = data.columns;
    let X = new Matrix$1(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        if (i <= j) {
          X.set(i, j, data.get(i, j));
        } else {
          X.set(i, j, 0);
        }
      }
    }
    return X;
  }
  get pivotPermutationVector() {
    return Array.from(this.pivotVector);
  }
}
function hypotenuse(a, b) {
  let r = 0;
  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;
}
class QrDecomposition {
  constructor(value) {
    value = WrapperMatrix2D.checkMatrix(value);
    let qr = value.clone();
    let m = value.rows;
    let n = value.columns;
    let rdiag = new Float64Array(n);
    let i, j, k, s;
    for (k = 0; k < n; k++) {
      let nrm = 0;
      for (i = k; i < m; i++) {
        nrm = hypotenuse(nrm, qr.get(i, k));
      }
      if (nrm !== 0) {
        if (qr.get(k, k) < 0) {
          nrm = -nrm;
        }
        for (i = k; i < m; i++) {
          qr.set(i, k, qr.get(i, k) / nrm);
        }
        qr.set(k, k, qr.get(k, k) + 1);
        for (j = k + 1; j < n; j++) {
          s = 0;
          for (i = k; i < m; i++) {
            s += qr.get(i, k) * qr.get(i, j);
          }
          s = -s / qr.get(k, k);
          for (i = k; i < m; i++) {
            qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));
          }
        }
      }
      rdiag[k] = -nrm;
    }
    this.QR = qr;
    this.Rdiag = rdiag;
  }
  solve(value) {
    value = Matrix$1.checkMatrix(value);
    let qr = this.QR;
    let m = qr.rows;
    if (value.rows !== m) {
      throw new Error('Matrix row dimensions must agree');
    }
    if (!this.isFullRank()) {
      throw new Error('Matrix is rank deficient');
    }
    let count = value.columns;
    let X = value.clone();
    let n = qr.columns;
    let i, j, k, s;
    for (k = 0; k < n; k++) {
      for (j = 0; j < count; j++) {
        s = 0;
        for (i = k; i < m; i++) {
          s += qr.get(i, k) * X.get(i, j);
        }
        s = -s / qr.get(k, k);
        for (i = k; i < m; i++) {
          X.set(i, j, X.get(i, j) + s * qr.get(i, k));
        }
      }
    }
    for (k = n - 1; k >= 0; k--) {
      for (j = 0; j < count; j++) {
        X.set(k, j, X.get(k, j) / this.Rdiag[k]);
      }
      for (i = 0; i < k; i++) {
        for (j = 0; j < count; j++) {
          X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));
        }
      }
    }
    return X.subMatrix(0, n - 1, 0, count - 1);
  }
  isFullRank() {
    let columns = this.QR.columns;
    for (let i = 0; i < columns; i++) {
      if (this.Rdiag[i] === 0) {
        return false;
      }
    }
    return true;
  }
  get upperTriangularMatrix() {
    let qr = this.QR;
    let n = qr.columns;
    let X = new Matrix$1(n, n);
    let i, j;
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        if (i < j) {
          X.set(i, j, qr.get(i, j));
        } else if (i === j) {
          X.set(i, j, this.Rdiag[i]);
        } else {
          X.set(i, j, 0);
        }
      }
    }
    return X;
  }
  get orthogonalMatrix() {
    let qr = this.QR;
    let rows = qr.rows;
    let columns = qr.columns;
    let X = new Matrix$1(rows, columns);
    let i, j, k, s;
    for (k = columns - 1; k >= 0; k--) {
      for (i = 0; i < rows; i++) {
        X.set(i, k, 0);
      }
      X.set(k, k, 1);
      for (j = k; j < columns; j++) {
        if (qr.get(k, k) !== 0) {
          s = 0;
          for (i = k; i < rows; i++) {
            s += qr.get(i, k) * X.get(i, j);
          }
          s = -s / qr.get(k, k);
          for (i = k; i < rows; i++) {
            X.set(i, j, X.get(i, j) + s * qr.get(i, k));
          }
        }
      }
    }
    return X;
  }
}
class SingularValueDecomposition {
  constructor(value, options = {}) {
    value = WrapperMatrix2D.checkMatrix(value);
    if (value.isEmpty()) {
      throw new Error('Matrix must be non-empty');
    }
    let m = value.rows;
    let n = value.columns;
    const {
      computeLeftSingularVectors = true,
      computeRightSingularVectors = true,
      autoTranspose = false
    } = options;
    let wantu = Boolean(computeLeftSingularVectors);
    let wantv = Boolean(computeRightSingularVectors);
    let swapped = false;
    let 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;
        let aux = wantu;
        wantu = wantv;
        wantv = aux;
      }
    } else {
      a = value.clone();
    }
    let nu = Math.min(m, n);
    let ni = Math.min(m + 1, n);
    let s = new Float64Array(ni);
    let U = new Matrix$1(m, nu);
    let V = new Matrix$1(n, n);
    let e = new Float64Array(n);
    let work = new Float64Array(m);
    let si = new Float64Array(ni);
    for (let i = 0; i < ni; i++) si[i] = i;
    let nct = Math.min(m - 1, n);
    let nrt = Math.max(0, Math.min(n - 2, m));
    let mrc = Math.max(nct, nrt);
    for (let k = 0; k < mrc; k++) {
      if (k < nct) {
        s[k] = 0;
        for (let i = k; i < m; i++) {
          s[k] = hypotenuse(s[k], a.get(i, k));
        }
        if (s[k] !== 0) {
          if (a.get(k, k) < 0) {
            s[k] = -s[k];
          }
          for (let i = k; i < m; i++) {
            a.set(i, k, a.get(i, k) / s[k]);
          }
          a.set(k, k, a.get(k, k) + 1);
        }
        s[k] = -s[k];
      }
      for (let j = k + 1; j < n; j++) {
        if (k < nct && s[k] !== 0) {
          let t = 0;
          for (let i = k; i < m; i++) {
            t += a.get(i, k) * a.get(i, j);
          }
          t = -t / a.get(k, k);
          for (let i = k; i < m; i++) {
            a.set(i, j, a.get(i, j) + t * a.get(i, k));
          }
        }
        e[j] = a.get(k, j);
      }
      if (wantu && k < nct) {
        for (let i = k; i < m; i++) {
          U.set(i, k, a.get(i, k));
        }
      }
      if (k < nrt) {
        e[k] = 0;
        for (let 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 (let 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 (let i = k + 1; i < m; i++) {
            work[i] = 0;
          }
          for (let i = k + 1; i < m; i++) {
            for (let j = k + 1; j < n; j++) {
              work[i] += e[j] * a.get(i, j);
            }
          }
          for (let j = k + 1; j < n; j++) {
            let t = -e[j] / e[k + 1];
            for (let i = k + 1; i < m; i++) {
              a.set(i, j, a.get(i, j) + t * work[i]);
            }
          }
        }
        if (wantv) {
          for (let i = k + 1; i < n; i++) {
            V.set(i, k, e[i]);
          }
        }
      }
    }
    let p = Math.min(n, m + 1);
    if (nct < n) {
      s[nct] = a.get(nct, nct);
    }
    if (m < p) {
      s[p - 1] = 0;
    }
    if (nrt + 1 < p) {
      e[nrt] = a.get(nrt, p - 1);
    }
    e[p - 1] = 0;
    if (wantu) {
      for (let j = nct; j < nu; j++) {
        for (let i = 0; i < m; i++) {
          U.set(i, j, 0);
        }
        U.set(j, j, 1);
      }
      for (let k = nct - 1; k >= 0; k--) {
        if (s[k] !== 0) {
          for (let j = k + 1; j < nu; j++) {
            let t = 0;
            for (let i = k; i < m; i++) {
              t += U.get(i, k) * U.get(i, j);
            }
            t = -t / U.get(k, k);
            for (let i = k; i < m; i++) {
              U.set(i, j, U.get(i, j) + t * U.get(i, k));
            }
          }
          for (let i = k; i < m; i++) {
            U.set(i, k, -U.get(i, k));
          }
          U.set(k, k, 1 + U.get(k, k));
          for (let i = 0; i < k - 1; i++) {
            U.set(i, k, 0);
          }
        } else {
          for (let i = 0; i < m; i++) {
            U.set(i, k, 0);
          }
          U.set(k, k, 1);
        }
      }
    }
    if (wantv) {
      for (let k = n - 1; k >= 0; k--) {
        if (k < nrt && e[k] !== 0) {
          for (let j = k + 1; j < n; j++) {
            let t = 0;
            for (let i = k + 1; i < n; i++) {
              t += V.get(i, k) * V.get(i, j);
            }
            t = -t / V.get(k + 1, k);
            for (let i = k + 1; i < n; i++) {
              V.set(i, j, V.get(i, j) + t * V.get(i, k));
            }
          }
        }
        for (let i = 0; i < n; i++) {
          V.set(i, k, 0);
        }
        V.set(k, k, 1);
      }
    }
    let pp = p - 1;
    let eps = Number.EPSILON;
    while (p > 0) {
      let k, kase;
      for (k = p - 2; k >= -1; k--) {
        if (k === -1) {
          break;
        }
        const alpha = Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));
        if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {
          e[k] = 0;
          break;
        }
      }
      if (k === p - 2) {
        kase = 4;
      } else {
        let ks;
        for (ks = p - 1; ks >= k; ks--) {
          if (ks === k) {
            break;
          }
          let 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:
          {
            let f = e[p - 2];
            e[p - 2] = 0;
            for (let j = p - 2; j >= k; j--) {
              let t = hypotenuse(s[j], f);
              let cs = s[j] / t;
              let sn = f / t;
              s[j] = t;
              if (j !== k) {
                f = -sn * e[j - 1];
                e[j - 1] = cs * e[j - 1];
              }
              if (wantv) {
                for (let i = 0; i < n; i++) {
                  t = cs * V.get(i, j) + sn * V.get(i, p - 1);
                  V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));
                  V.set(i, j, t);
                }
              }
            }
            break;
          }
        case 2:
          {
            let f = e[k - 1];
            e[k - 1] = 0;
            for (let j = k; j < p; j++) {
              let t = hypotenuse(s[j], f);
              let cs = s[j] / t;
              let sn = f / t;
              s[j] = t;
              f = -sn * e[j];
              e[j] = cs * e[j];
              if (wantu) {
                for (let i = 0; i < m; i++) {
                  t = cs * U.get(i, j) + sn * U.get(i, k - 1);
                  U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));
                  U.set(i, j, t);
                }
              }
            }
            break;
          }
        case 3:
          {
            const scale = 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]));
            const sp = s[p - 1] / scale;
            const spm1 = s[p - 2] / scale;
            const epm1 = e[p - 2] / scale;
            const sk = s[k] / scale;
            const ek = e[k] / scale;
            const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;
            const c = sp * epm1 * (sp * epm1);
            let shift = 0;
            if (b !== 0 || c !== 0) {
              if (b < 0) {
                shift = 0 - Math.sqrt(b * b + c);
              } else {
                shift = Math.sqrt(b * b + c);
              }
              shift = c / (b + shift);
            }
            let f = (sk + sp) * (sk - sp) + shift;
            let g = sk * ek;
            for (let j = k; j < p - 1; j++) {
              let t = hypotenuse(f, g);
              if (t === 0) t = Number.MIN_VALUE;
              let cs = f / t;
              let 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 (let i = 0; i < n; i++) {
                  t = cs * V.get(i, j) + sn * V.get(i, j + 1);
                  V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));
                  V.set(i, j, t);
                }
              }
              t = hypotenuse(f, g);
              if (t === 0) t = Number.MIN_VALUE;
              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 (let i = 0; i < m; i++) {
                  t = cs * U.get(i, j) + sn * U.get(i, j + 1);
                  U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));
                  U.set(i, j, t);
                }
              }
            }
            e[p - 2] = f;
            break;
          }
        case 4:
          {
            if (s[k] <= 0) {
              s[k] = s[k] < 0 ? -s[k] : 0;
              if (wantv) {
                for (let i = 0; i <= pp; i++) {
                  V.set(i, k, -V.get(i, k));
                }
              }
            }
            while (k < pp) {
              if (s[k] >= s[k + 1]) {
                break;
              }
              let t = s[k];
              s[k] = s[k + 1];
              s[k + 1] = t;
              if (wantv && k < n - 1) {
                for (let i = 0; i < n; i++) {
                  t = V.get(i, k + 1);
                  V.set(i, k + 1, V.get(i, k));
                  V.set(i, k, t);
                }
              }
              if (wantu && k < m - 1) {
                for (let i = 0; i < m; i++) {
                  t = U.get(i, k + 1);
                  U.set(i, k + 1, U.get(i, k));
                  U.set(i, k, t);
                }
              }
              k++;
            }
            p--;
            break;
          }
        // no default
      }
    }
    if (swapped) {
      let tmp = V;
      V = U;
      U = tmp;
    }
    this.m = m;
    this.n = n;
    this.s = s;
    this.U = U;
    this.V = V;
  }
  solve(value) {
    let Y = value;
    let e = this.threshold;
    let scols = this.s.length;
    let Ls = Matrix$1.zeros(scols, scols);
    for (let i = 0; i < scols; i++) {
      if (Math.abs(this.s[i]) <= e) {
        Ls.set(i, i, 0);
      } else {
        Ls.set(i, i, 1 / this.s[i]);
      }
    }
    let U = this.U;
    let V = this.rightSingularVectors;
    let VL = V.mmul(Ls);
    let vrows = V.rows;
    let urows = U.rows;
    let VLU = Matrix$1.zeros(vrows, urows);
    for (let i = 0; i < vrows; i++) {
      for (let j = 0; j < urows; j++) {
        let sum = 0;
        for (let k = 0; k < scols; k++) {
          sum += VL.get(i, k) * U.get(j, k);
        }
        VLU.set(i, j, sum);
      }
    }
    return VLU.mmul(Y);
  }
  solveForDiagonal(value) {
    return this.solve(Matrix$1.diag(value));
  }
  inverse() {
    let V = this.V;
    let e = this.threshold;
    let vrows = V.rows;
    let vcols = V.columns;
    let X = new Matrix$1(vrows, this.s.length);
    for (let i = 0; i < vrows; i++) {
      for (let j = 0; j < vcols; j++) {
        if (Math.abs(this.s[j]) > e) {
          X.set(i, j, V.get(i, j) / this.s[j]);
        }
      }
    }
    let U = this.U;
    let urows = U.rows;
    let ucols = U.columns;
    let Y = new Matrix$1(vrows, urows);
    for (let i = 0; i < vrows; i++) {
      for (let j = 0; j < urows; j++) {
        let sum = 0;
        for (let k = 0; k < ucols; k++) {
          sum += X.get(i, k) * U.get(j, k);
        }
        Y.set(i, j, sum);
      }
    }
    return Y;
  }
  get condition() {
    return this.s[0] / this.s[Math.min(this.m, this.n) - 1];
  }
  get norm2() {
    return this.s[0];
  }
  get rank() {
    let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;
    let r = 0;
    let s = this.s;
    for (let i = 0, ii = s.length; i < ii; i++) {
      if (s[i] > tol) {
        r++;
      }
    }
    return r;
  }
  get diagonal() {
    return Array.from(this.s);
  }
  get threshold() {
    return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];
  }
  get leftSingularVectors() {
    return this.U;
  }
  get rightSingularVectors() {
    return this.V;
  }
  get diagonalMatrix() {
    return Matrix$1.diag(this.s);
  }
}
function inverse$1(matrix, useSVD = false) {
  matrix = WrapperMatrix2D.checkMatrix(matrix);
  if (useSVD) {
    return new SingularValueDecomposition(matrix).inverse();
  } else {
    return solve$1(matrix, Matrix$1.eye(matrix.rows));
  }
}
function solve$1(leftHandSide, rightHandSide, useSVD = false) {
  leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);
  rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);
  if (useSVD) {
    return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);
  } else {
    return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);
  }
}
function determinant(matrix) {
  matrix = Matrix$1.checkMatrix(matrix);
  if (matrix.isSquare()) {
    if (matrix.columns === 0) {
      return 1;
    }
    let a, b, c, d;
    if (matrix.columns === 2) {
      // 2 x 2 matrix
      a = matrix.get(0, 0);
      b = matrix.get(0, 1);
      c = matrix.get(1, 0);
      d = matrix.get(1, 1);
      return a * d - b * c;
    } else if (matrix.columns === 3) {
      // 3 x 3 matrix
      let subMatrix0, subMatrix1, subMatrix2;
      subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);
      subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);
      subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);
      a = matrix.get(0, 0);
      b = matrix.get(0, 1);
      c = matrix.get(0, 2);
      return a * determinant(subMatrix0) - b * determinant(subMatrix1) + c * determinant(subMatrix2);
    } else {
      // general purpose determinant using the LU decomposition
      return new LuDecomposition(matrix).determinant;
    }
  } else {
    throw Error('determinant can only be calculated for a square matrix');
  }
}
function xrange(n, exception) {
  let range = [];
  for (let i = 0; i < n; i++) {
    if (i !== exception) {
      range.push(i);
    }
  }
  return range;
}
function dependenciesOneRow(error, matrix, index, thresholdValue = 10e-10, thresholdError = 10e-10) {
  if (error > thresholdError) {
    return new Array(matrix.rows + 1).fill(0);
  } else {
    let returnArray = matrix.addRow(index, [0]);
    for (let i = 0; i < returnArray.rows; i++) {
      if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {
        returnArray.set(i, 0, 0);
      }
    }
    return returnArray.to1DArray();
  }
}
function linearDependencies(matrix, options = {}) {
  const {
    thresholdValue = 10e-10,
    thresholdError = 10e-10
  } = options;
  matrix = Matrix$1.checkMatrix(matrix);
  let n = matrix.rows;
  let results = new Matrix$1(n, n);
  for (let i = 0; i < n; i++) {
    let b = Matrix$1.columnVector(matrix.getRow(i));
    let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();
    let svd = new SingularValueDecomposition(Abis);
    let x = svd.solve(b);
    let error = Matrix$1.sub(b, Abis.mmul(x)).abs().max();
    results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError));
  }
  return results;
}
function pseudoInverse(matrix, threshold = Number.EPSILON) {
  matrix = Matrix$1.checkMatrix(matrix);
  if (matrix.isEmpty()) {
    // with a zero dimension, the pseudo-inverse is the transpose, since all 0xn and nx0 matrices are singular
    // (0xn)*(nx0)*(0xn) = 0xn
    // (nx0)*(0xn)*(nx0) = nx0
    return matrix.transpose();
  }
  let svdSolution = new SingularValueDecomposition(matrix, {
    autoTranspose: true
  });
  let U = svdSolution.leftSingularVectors;
  let V = svdSolution.rightSingularVectors;
  let s = svdSolution.diagonal;
  for (let i = 0; i < s.length; i++) {
    if (Math.abs(s[i]) > threshold) {
      s[i] = 1.0 / s[i];
    } else {
      s[i] = 0.0;
    }
  }
  return V.mmul(Matrix$1.diag(s).mmul(U.transpose()));
}
function covariance(xMatrix, yMatrix = xMatrix, options = {}) {
  xMatrix = new Matrix$1(xMatrix);
  let yIsSame = false;
  if (typeof yMatrix === 'object' && !Matrix$1.isMatrix(yMatrix) && !isAnyArray.isAnyArray(yMatrix)) {
    options = yMatrix;
    yMatrix = xMatrix;
    yIsSame = true;
  } else {
    yMatrix = new Matrix$1(yMatrix);
  }
  if (xMatrix.rows !== yMatrix.rows) {
    throw new TypeError('Both matrices must have the same number of rows');
  }
  const {
    center = true
  } = options;
  if (center) {
    xMatrix = xMatrix.center('column');
    if (!yIsSame) {
      yMatrix = yMatrix.center('column');
    }
  }
  const cov = xMatrix.transpose().mmul(yMatrix);
  for (let i = 0; i < cov.rows; i++) {
    for (let j = 0; j < cov.columns; j++) {
      cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));
    }
  }
  return cov;
}
function correlation(xMatrix, yMatrix = xMatrix, options = {}) {
  xMatrix = new Matrix$1(xMatrix);
  let yIsSame = false;
  if (typeof yMatrix === 'object' && !Matrix$1.isMatrix(yMatrix) && !isAnyArray.isAnyArray(yMatrix)) {
    options = yMatrix;
    yMatrix = xMatrix;
    yIsSame = true;
  } else {
    yMatrix = new Matrix$1(yMatrix);
  }
  if (xMatrix.rows !== yMatrix.rows) {
    throw new TypeError('Both matrices must have the same number of rows');
  }
  const {
    center = true,
    scale = true
  } = options;
  if (center) {
    xMatrix.center('column');
    if (!yIsSame) {
      yMatrix.center('column');
    }
  }
  if (scale) {
    xMatrix.scale('column');
    if (!yIsSame) {
      yMatrix.scale('column');
    }
  }
  const sdx = xMatrix.standardDeviation('column', {
    unbiased: true
  });
  const sdy = yIsSame ? sdx : yMatrix.standardDeviation('column', {
    unbiased: true
  });
  const corr = xMatrix.transpose().mmul(yMatrix);
  for (let i = 0; i < corr.rows; i++) {
    for (let j = 0; j < corr.columns; j++) {
      corr.set(i, j, corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)));
    }
  }
  return corr;
}
class EigenvalueDecomposition {
  constructor(matrix, options = {}) {
    const {
      assumeSymmetric = false
    } = options;
    matrix = WrapperMatrix2D.checkMatrix(matrix);
    if (!matrix.isSquare()) {
      throw new Error('Matrix is not a square matrix');
    }
    if (matrix.isEmpty()) {
      throw new Error('Matrix must be non-empty');
    }
    let n = matrix.columns;
    let V = new Matrix$1(n, n);
    let d = new Float64Array(n);
    let e = new Float64Array(n);
    let value = matrix;
    let i, j;
    let isSymmetric = false;
    if (assumeSymmetric) {
      isSymmetric = true;
    } else {
      isSymmetric = matrix.isSymmetric();
    }
    if (isSymmetric) {
      for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
          V.set(i, j, value.get(i, j));
        }
      }
      tred2(n, e, d, V);
      tql2(n, e, d, V);
    } else {
      let H = new Matrix$1(n, n);
      let ort = new Float64Array(n);
      for (j = 0; j < n; j++) {
        for (i = 0; i < n; i++) {
          H.set(i, j, value.get(i, j));
        }
      }
      orthes(n, H, ort, V);
      hqr2(n, e, d, V, H);
    }
    this.n = n;
    this.e = e;
    this.d = d;
    this.V = V;
  }
  get realEigenvalues() {
    return Array.from(this.d);
  }
  get imaginaryEigenvalues() {
    return Array.from(this.e);
  }
  get eigenvectorMatrix() {
    return this.V;
  }
  get diagonalMatrix() {
    let n = this.n;
    let e = this.e;
    let d = this.d;
    let X = new Matrix$1(n, n);
    let i, j;
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        X.set(i, j, 0);
      }
      X.set(i, i, d[i]);
      if (e[i] > 0) {
        X.set(i, i + 1, e[i]);
      } else if (e[i] < 0) {
        X.set(i, i - 1, e[i]);
      }
    }
    return X;
  }
}
function tred2(n, e, d, V) {
  let f, g, h, i, j, k, hh, scale;
  for (j = 0; j < n; j++) {
    d[j] = V.get(n - 1, j);
  }
  for (i = n - 1; i > 0; i--) {
    scale = 0;
    h = 0;
    for (k = 0; k < i; k++) {
      scale = scale + Math.abs(d[k]);
    }
    if (scale === 0) {
      e[i] = d[i - 1];
      for (j = 0; j < i; j++) {
        d[j] = V.get(i - 1, j);
        V.set(i, j, 0);
        V.set(j, i, 0);
      }
    } else {
      for (k = 0; k < i; k++) {
        d[k] /= scale;
        h += d[k] * d[k];
      }
      f = d[i - 1];
      g = Math.sqrt(h);
      if (f > 0) {
        g = -g;
      }
      e[i] = scale * g;
      h = h - f * g;
      d[i - 1] = f - g;
      for (j = 0; j < i; j++) {
        e[j] = 0;
      }
      for (j = 0; j < i; j++) {
        f = d[j];
        V.set(j, i, f);
        g = e[j] + V.get(j, j) * f;
        for (k = j + 1; k <= i - 1; k++) {
          g += V.get(k, j) * d[k];
          e[k] += V.get(k, j) * f;
        }
        e[j] = g;
      }
      f = 0;
      for (j = 0; j < i; j++) {
        e[j] /= h;
        f += e[j] * d[j];
      }
      hh = f / (h + h);
      for (j = 0; j < i; j++) {
        e[j] -= hh * d[j];
      }
      for (j = 0; j < i; j++) {
        f = d[j];
        g = e[j];
        for (k = j; k <= i - 1; k++) {
          V.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));
        }
        d[j] = V.get(i - 1, j);
        V.set(i, j, 0);
      }
    }
    d[i] = h;
  }
  for (i = 0; i < n - 1; i++) {
    V.set(n - 1, i, V.get(i, i));
    V.set(i, i, 1);
    h = d[i + 1];
    if (h !== 0) {
      for (k = 0; k <= i; k++) {
        d[k] = V.get(k, i + 1) / h;
      }
      for (j = 0; j <= i; j++) {
        g = 0;
        for (k = 0; k <= i; k++) {
          g += V.get(k, i + 1) * V.get(k, j);
        }
        for (k = 0; k <= i; k++) {
          V.set(k, j, V.get(k, j) - g * d[k]);
        }
      }
    }
    for (k = 0; k <= i; k++) {
      V.set(k, i + 1, 0);
    }
  }
  for (j = 0; j < n; j++) {
    d[j] = V.get(n - 1, j);
    V.set(n - 1, j, 0);
  }
  V.set(n - 1, n - 1, 1);
  e[0] = 0;
}
function tql2(n, e, d, V) {
  let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2;
  for (i = 1; i < n; i++) {
    e[i - 1] = e[i];
  }
  e[n - 1] = 0;
  let f = 0;
  let tst1 = 0;
  let eps = Number.EPSILON;
  for (l = 0; l < n; l++) {
    tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));
    m = l;
    while (m < n) {
      if (Math.abs(e[m]) <= eps * tst1) {
        break;
      }
      m++;
    }
    if (m > l) {
      do {
        g = d[l];
        p = (d[l + 1] - g) / (2 * e[l]);
        r = hypotenuse(p, 1);
        if (p < 0) {
          r = -r;
        }
        d[l] = e[l] / (p + r);
        d[l + 1] = e[l] * (p + r);
        dl1 = d[l + 1];
        h = g - d[l];
        for (i = l + 2; i < n; i++) {
          d[i] -= h;
        }
        f = f + h;
        p = d[m];
        c = 1;
        c2 = c;
        c3 = c;
        el1 = e[l + 1];
        s = 0;
        s2 = 0;
        for (i = m - 1; i >= l; i--) {
          c3 = c2;
          c2 = c;
          s2 = s;
          g = c * e[i];
          h = c * p;
          r = hypotenuse(p, e[i]);
          e[i + 1] = s * r;
          s = e[i] / r;
          c = p / r;
          p = c * d[i] - s * g;
          d[i + 1] = h + s * (c * g + s * d[i]);
          for (k = 0; k < n; k++) {
            h = V.get(k, i + 1);
            V.set(k, i + 1, s * V.get(k, i) + c * h);
            V.set(k, i, c * V.get(k, i) - s * h);
          }
        }
        p = -s * s2 * c3 * el1 * e[l] / dl1;
        e[l] = s * p;
        d[l] = c * p;
      } while (Math.abs(e[l]) > eps * tst1);
    }
    d[l] = d[l] + f;
    e[l] = 0;
  }
  for (i = 0; i < n - 1; i++) {
    k = i;
    p = d[i];
    for (j = i + 1; j < n; j++) {
      if (d[j] < p) {
        k = j;
        p = d[j];
      }
    }
    if (k !== i) {
      d[k] = d[i];
      d[i] = p;
      for (j = 0; j < n; j++) {
        p = V.get(j, i);
        V.set(j, i, V.get(j, k));
        V.set(j, k, p);
      }
    }
  }
}
function orthes(n, H, ort, V) {
  let low = 0;
  let high = n - 1;
  let f, g, h, i, j, m;
  let scale;
  for (m = low + 1; m <= high - 1; m++) {
    scale = 0;
    for (i = m; i <= high; i++) {
      scale = scale + Math.abs(H.get(i, m - 1));
    }
    if (scale !== 0) {
      h = 0;
      for (i = high; i >= m; i--) {
        ort[i] = H.get(i, m - 1) / scale;
        h += ort[i] * ort[i];
      }
      g = Math.sqrt(h);
      if (ort[m] > 0) {
        g = -g;
      }
      h = h - ort[m] * g;
      ort[m] = ort[m] - g;
      for (j = m; j < n; j++) {
        f = 0;
        for (i = high; i >= m; i--) {
          f += ort[i] * H.get(i, j);
        }
        f = f / h;
        for (i = m; i <= high; i++) {
          H.set(i, j, H.get(i, j) - f * ort[i]);
        }
      }
      for (i = 0; i <= high; i++) {
        f = 0;
        for (j = high; j >= m; j--) {
          f += ort[j] * H.get(i, j);
        }
        f = f / h;
        for (j = m; j <= high; j++) {
          H.set(i, j, H.get(i, j) - f * ort[j]);
        }
      }
      ort[m] = scale * ort[m];
      H.set(m, m - 1, scale * g);
    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      V.set(i, j, i === j ? 1 : 0);
    }
  }
  for (m = high - 1; m >= low + 1; m--) {
    if (H.get(m, m - 1) !== 0) {
      for (i = m + 1; i <= high; i++) {
        ort[i] = H.get(i, m - 1);
      }
      for (j = m; j <= high; j++) {
        g = 0;
        for (i = m; i <= high; i++) {
          g += ort[i] * V.get(i, j);
        }
        g = g / ort[m] / H.get(m, m - 1);
        for (i = m; i <= high; i++) {
          V.set(i, j, V.get(i, j) + g * ort[i]);
        }
      }
    }
  }
}
function hqr2(nn, e, d, V, H) {
  let n = nn - 1;
  let low = 0;
  let high = nn - 1;
  let eps = Number.EPSILON;
  let exshift = 0;
  let norm = 0;
  let p = 0;
  let q = 0;
  let r = 0;
  let s = 0;
  let z = 0;
  let iter = 0;
  let i, j, k, l, m, t, w, x, y;
  let ra, sa, vr, vi;
  let notlast, cdivres;
  for (i = 0; i < nn; i++) {
    if (i < low || i > high) {
      d[i] = H.get(i, i);
      e[i] = 0;
    }
    for (j = Math.max(i - 1, 0); j < nn; j++) {
      norm = norm + Math.abs(H.get(i, j));
    }
  }
  while (n >= low) {
    l = n;
    while (l > low) {
      s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));
      if (s === 0) {
        s = norm;
      }
      if (Math.abs(H.get(l, l - 1)) < eps * s) {
        break;
      }
      l--;
    }
    if (l === n) {
      H.set(n, n, H.get(n, n) + exshift);
      d[n] = H.get(n, n);
      e[n] = 0;
      n--;
      iter = 0;
    } else if (l === n - 1) {
      w = H.get(n, n - 1) * H.get(n - 1, n);
      p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;
      q = p * p + w;
      z = Math.sqrt(Math.abs(q));
      H.set(n, n, H.get(n, n) + exshift);
      H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);
      x = H.get(n, n);
      if (q >= 0) {
        z = p >= 0 ? p + z : p - z;
        d[n - 1] = x + z;
        d[n] = d[n - 1];
        if (z !== 0) {
          d[n] = x - w / z;
        }
        e[n - 1] = 0;
        e[n] = 0;
        x = H.get(n, n - 1);
        s = Math.abs(x) + Math.abs(z);
        p = x / s;
        q = z / s;
        r = Math.sqrt(p * p + q * q);
        p = p / r;
        q = q / r;
        for (j = n - 1; j < nn; j++) {
          z = H.get(n - 1, j);
          H.set(n - 1, j, q * z + p * H.get(n, j));
          H.set(n, j, q * H.get(n, j) - p * z);
        }
        for (i = 0; i <= n; i++) {
          z = H.get(i, n - 1);
          H.set(i, n - 1, q * z + p * H.get(i, n));
          H.set(i, n, q * H.get(i, n) - p * z);
        }
        for (i = low; i <= high; i++) {
          z = V.get(i, n - 1);
          V.set(i, n - 1, q * z + p * V.get(i, n));
          V.set(i, n, q * V.get(i, n) - p * z);
        }
      } else {
        d[n - 1] = x + p;
        d[n] = x + p;
        e[n - 1] = z;
        e[n] = -z;
      }
      n = n - 2;
      iter = 0;
    } else {
      x = H.get(n, n);
      y = 0;
      w = 0;
      if (l < n) {
        y = H.get(n - 1, n - 1);
        w = H.get(n, n - 1) * H.get(n - 1, n);
      }
      if (iter === 10) {
        exshift += x;
        for (i = low; i <= n; i++) {
          H.set(i, i, H.get(i, i) - x);
        }
        s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(n - 1, n - 2));
        // eslint-disable-next-line no-multi-assign
        x = y = 0.75 * s;
        w = -0.4375 * s * s;
      }
      if (iter === 30) {
        s = (y - x) / 2;
        s = s * s + w;
        if (s > 0) {
          s = Math.sqrt(s);
          if (y < x) {
            s = -s;
          }
          s = x - w / ((y - x) / 2 + s);
          for (i = low; i <= n; i++) {
            H.set(i, i, H.get(i, i) - s);
          }
          exshift += s;
          // eslint-disable-next-line no-multi-assign
          x = y = w = 0.964;
        }
      }
      iter = iter + 1;
      m = n - 2;
      while (m >= l) {
        z = H.get(m, m);
        r = x - z;
        s = y - z;
        p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);
        q = H.get(m + 1, m + 1) - z - r - s;
        r = H.get(m + 2, m + 1);
        s = Math.abs(p) + Math.abs(q) + Math.abs(r);
        p = p / s;
        q = q / s;
        r = r / s;
        if (m === l) {
          break;
        }
        if (Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H.get(m - 1, m - 1)) + Math.abs(z) + Math.abs(H.get(m + 1, m + 1))))) {
          break;
        }
        m--;
      }
      for (i = m + 2; i <= n; i++) {
        H.set(i, i - 2, 0);
        if (i > m + 2) {
          H.set(i, i - 3, 0);
        }
      }
      for (k = m; k <= n - 1; k++) {
        notlast = k !== n - 1;
        if (k !== m) {
          p = H.get(k, k - 1);
          q = H.get(k + 1, k - 1);
          r = notlast ? H.get(k + 2, k - 1) : 0;
          x = Math.abs(p) + Math.abs(q) + Math.abs(r);
          if (x !== 0) {
            p = p / x;
            q = q / x;
            r = r / x;
          }
        }
        if (x === 0) {
          break;
        }
        s = Math.sqrt(p * p + q * q + r * r);
        if (p < 0) {
          s = -s;
        }
        if (s !== 0) {
          if (k !== m) {
            H.set(k, k - 1, -s * x);
          } else if (l !== m) {
            H.set(k, k - 1, -H.get(k, k - 1));
          }
          p = p + s;
          x = p / s;
          y = q / s;
          z = r / s;
          q = q / p;
          r = r / p;
          for (j = k; j < nn; j++) {
            p = H.get(k, j) + q * H.get(k + 1, j);
            if (notlast) {
              p = p + r * H.get(k + 2, j);
              H.set(k + 2, j, H.get(k + 2, j) - p * z);
            }
            H.set(k, j, H.get(k, j) - p * x);
            H.set(k + 1, j, H.get(k + 1, j) - p * y);
          }
          for (i = 0; i <= Math.min(n, k + 3); i++) {
            p = x * H.get(i, k) + y * H.get(i, k + 1);
            if (notlast) {
              p = p + z * H.get(i, k + 2);
              H.set(i, k + 2, H.get(i, k + 2) - p * r);
            }
            H.set(i, k, H.get(i, k) - p);
            H.set(i, k + 1, H.get(i, k + 1) - p * q);
          }
          for (i = low; i <= high; i++) {
            p = x * V.get(i, k) + y * V.get(i, k + 1);
            if (notlast) {
              p = p + z * V.get(i, k + 2);
              V.set(i, k + 2, V.get(i, k + 2) - p * r);
            }
            V.set(i, k, V.get(i, k) - p);
            V.set(i, k + 1, V.get(i, k + 1) - p * q);
          }
        }
      }
    }
  }
  if (norm === 0) {
    return;
  }
  for (n = nn - 1; n >= 0; n--) {
    p = d[n];
    q = e[n];
    if (q === 0) {
      l = n;
      H.set(n, n, 1);
      for (i = n - 1; i >= 0; i--) {
        w = H.get(i, i) - p;
        r = 0;
        for (j = l; j <= n; j++) {
          r = r + H.get(i, j) * H.get(j, n);
        }
        if (e[i] < 0) {
          z = w;
          s = r;
        } else {
          l = i;
          if (e[i] === 0) {
            H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));
          } else {
            x = H.get(i, i + 1);
            y = H.get(i + 1, i);
            q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
            t = (x * s - z * r) / q;
            H.set(i, n, t);
            H.set(i + 1, n, Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z);
          }
          t = Math.abs(H.get(i, n));
          if (eps * t * t > 1) {
            for (j = i; j <= n; j++) {
              H.set(j, n, H.get(j, n) / t);
            }
          }
        }
      }
    } else if (q < 0) {
      l = n - 1;
      if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {
        H.set(n - 1, n - 1, q / H.get(n, n - 1));
        H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));
      } else {
        cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);
        H.set(n - 1, n - 1, cdivres[0]);
        H.set(n - 1, n, cdivres[1]);
      }
      H.set(n, n - 1, 0);
      H.set(n, n, 1);
      for (i = n - 2; i >= 0; i--) {
        ra = 0;
        sa = 0;
        for (j = l; j <= n; j++) {
          ra = ra + H.get(i, j) * H.get(j, n - 1);
          sa = sa + H.get(i, j) * H.get(j, n);
        }
        w = H.get(i, i) - p;
        if (e[i] < 0) {
          z = w;
          r = ra;
          s = sa;
        } else {
          l = i;
          if (e[i] === 0) {
            cdivres = cdiv(-ra, -sa, w, q);
            H.set(i, n - 1, cdivres[0]);
            H.set(i, n, cdivres[1]);
          } else {
            x = H.get(i, i + 1);
            y = H.get(i + 1, i);
            vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
            vi = (d[i] - p) * 2 * q;
            if (vr === 0 && vi === 0) {
              vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));
            }
            cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);
            H.set(i, n - 1, cdivres[0]);
            H.set(i, n, cdivres[1]);
            if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {
              H.set(i + 1, n - 1, (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x);
              H.set(i + 1, n, (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x);
            } else {
              cdivres = cdiv(-r - y * H.get(i, n - 1), -s - y * H.get(i, n), z, q);
              H.set(i + 1, n - 1, cdivres[0]);
              H.set(i + 1, n, cdivres[1]);
            }
          }
          t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));
          if (eps * t * t > 1) {
            for (j = i; j <= n; j++) {
              H.set(j, n - 1, H.get(j, n - 1) / t);
              H.set(j, n, H.get(j, n) / t);
            }
          }
        }
      }
    }
  }
  for (i = 0; i < nn; i++) {
    if (i < low || i > high) {
      for (j = i; j < nn; j++) {
        V.set(i, j, H.get(i, j));
      }
    }
  }
  for (j = nn - 1; j >= low; j--) {
    for (i = low; i <= high; i++) {
      z = 0;
      for (k = low; k <= Math.min(j, high); k++) {
        z = z + V.get(i, k) * H.get(k, j);
      }
      V.set(i, j, z);
    }
  }
}
function cdiv(xr, xi, yr, yi) {
  let r, d;
  if (Math.abs(yr) > Math.abs(yi)) {
    r = yi / yr;
    d = yr + r * yi;
    return [(xr + r * xi) / d, (xi - r * xr) / d];
  } else {
    r = yr / yi;
    d = yi + r * yr;
    return [(r * xr + xi) / d, (r * xi - xr) / d];
  }
}
class CholeskyDecomposition {
  constructor(value) {
    value = WrapperMatrix2D.checkMatrix(value);
    if (!value.isSymmetric()) {
      throw new Error('Matrix is not symmetric');
    }
    let a = value;
    let dimension = a.rows;
    let l = new Matrix$1(dimension, dimension);
    let positiveDefinite = true;
    let i, j, k;
    for (j = 0; j < dimension; j++) {
      let d = 0;
      for (k = 0; k < j; k++) {
        let s = 0;
        for (i = 0; i < k; i++) {
          s += l.get(k, i) * l.get(j, i);
        }
        s = (a.get(j, k) - s) / l.get(k, k);
        l.set(j, k, s);
        d = d + s * s;
      }
      d = a.get(j, j) - d;
      positiveDefinite &&= d > 0;
      l.set(j, j, Math.sqrt(Math.max(d, 0)));
      for (k = j + 1; k < dimension; k++) {
        l.set(j, k, 0);
      }
    }
    this.L = l;
    this.positiveDefinite = positiveDefinite;
  }
  isPositiveDefinite() {
    return this.positiveDefinite;
  }
  solve(value) {
    value = WrapperMatrix2D.checkMatrix(value);
    let l = this.L;
    let dimension = l.rows;
    if (value.rows !== dimension) {
      throw new Error('Matrix dimensions do not match');
    }
    if (this.isPositiveDefinite() === false) {
      throw new Error('Matrix is not positive definite');
    }
    let count = value.columns;
    let B = value.clone();
    let i, j, k;
    for (k = 0; k < dimension; k++) {
      for (j = 0; j < count; j++) {
        for (i = 0; i < k; i++) {
          B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));
        }
        B.set(k, j, B.get(k, j) / l.get(k, k));
      }
    }
    for (k = dimension - 1; k >= 0; k--) {
      for (j = 0; j < count; j++) {
        for (i = k + 1; i < dimension; i++) {
          B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));
        }
        B.set(k, j, B.get(k, j) / l.get(k, k));
      }
    }
    return B;
  }
  get lowerTriangularMatrix() {
    return this.L;
  }
}
class nipals {
  constructor(X, options = {}) {
    X = WrapperMatrix2D.checkMatrix(X);
    let {
      Y
    } = options;
    const {
      scaleScores = false,
      maxIterations = 1000,
      terminationCriteria = 1e-10
    } = options;
    let u;
    if (Y) {
      if (isAnyArray.isAnyArray(Y) && typeof Y[0] === 'number') {
        Y = Matrix$1.columnVector(Y);
      } else {
        Y = WrapperMatrix2D.checkMatrix(Y);
      }
      if (Y.rows !== X.rows) {
        throw new Error('Y should have the same number of rows as X');
      }
      u = Y.getColumnVector(0);
    } else {
      u = X.getColumnVector(0);
    }
    let diff = 1;
    let t, q, w, tOld;
    for (let counter = 0; counter < maxIterations && diff > terminationCriteria; counter++) {
      w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));
      w = w.div(w.norm());
      t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));
      if (counter > 0) {
        diff = t.clone().sub(tOld).pow(2).sum();
      }
      tOld = t.clone();
      if (Y) {
        q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
        q = q.div(q.norm());
        u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));
      } else {
        u = t;
      }
    }
    if (Y) {
      let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
      p = p.div(p.norm());
      let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));
      let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
      let yResidual = Y.clone().sub(t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()));
      this.t = t;
      this.p = p.transpose();
      this.w = w.transpose();
      this.q = q;
      this.u = u;
      this.s = t.transpose().mmul(t);
      this.xResidual = xResidual;
      this.yResidual = yResidual;
      this.betas = residual;
    } else {
      this.w = w.transpose();
      this.s = t.transpose().mmul(t).sqrt();
      if (scaleScores) {
        this.t = t.clone().div(this.s.get(0, 0));
      } else {
        this.t = t;
      }
      this.xResidual = X.sub(t.mmul(w.transpose()));
    }
  }
}
matrix.AbstractMatrix = AbstractMatrix;
matrix.CHO = CholeskyDecomposition;
matrix.CholeskyDecomposition = CholeskyDecomposition;
matrix.DistanceMatrix = DistanceMatrix;
matrix.EVD = EigenvalueDecomposition;
matrix.EigenvalueDecomposition = EigenvalueDecomposition;
matrix.LU = LuDecomposition;
matrix.LuDecomposition = LuDecomposition;
var Matrix_1 = matrix.Matrix = Matrix$1;
matrix.MatrixColumnSelectionView = MatrixColumnSelectionView;
matrix.MatrixColumnView = MatrixColumnView;
matrix.MatrixFlipColumnView = MatrixFlipColumnView;
matrix.MatrixFlipRowView = MatrixFlipRowView;
matrix.MatrixRowSelectionView = MatrixRowSelectionView;
matrix.MatrixRowView = MatrixRowView;
matrix.MatrixSelectionView = MatrixSelectionView;
matrix.MatrixSubView = MatrixSubView;
var MatrixTransposeView_1 = matrix.MatrixTransposeView = MatrixTransposeView$1;
matrix.NIPALS = nipals;
matrix.Nipals = nipals;
matrix.QR = QrDecomposition;
matrix.QrDecomposition = QrDecomposition;
matrix.SVD = SingularValueDecomposition;
matrix.SingularValueDecomposition = SingularValueDecomposition;
matrix.SymmetricMatrix = SymmetricMatrix;
matrix.WrapperMatrix1D = WrapperMatrix1D;
matrix.WrapperMatrix2D = WrapperMatrix2D;
matrix.correlation = correlation;
matrix.covariance = covariance;
var _default = matrix.default = Matrix$1;
matrix.determinant = determinant;
var inverse_1 = matrix.inverse = inverse$1;
matrix.linearDependencies = linearDependencies;
matrix.pseudoInverse = pseudoInverse;
var solve_1 = matrix.solve = solve$1;
matrix.wrap = wrap;

const Matrix = Matrix_1;
const MatrixTransposeView = MatrixTransposeView_1;
_default.Matrix ? _default.Matrix : Matrix_1;
const inverse = inverse_1;
const solve = solve_1;

/**
 * Computes the mean value of an array of values.
 * @param array - array of numbers
 * @param options - options
 */
function xMean(array, options = {}) {
  xCheck(array);
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(array, options);
  let sumValue = array[fromIndex];
  for (let i = fromIndex + 1; i <= toIndex; i++) {
    sumValue += array[i];
  }
  return sumValue / (toIndex - fromIndex + 1);
}

/**
 * Finds the variance of the data
 * @param values - the values of the array
 * @param options - options
 * @returns variance
 */
function xVariance(values, options = {}) {
  if (!isAnyArray$1(values)) {
    throw new TypeError('input must be an array');
  }
  const {
    unbiased = true,
    mean = xMean(values)
  } = options;
  let sqrError = 0;
  for (const value of values) {
    const x = value - mean;
    sqrError += x * x;
  }
  if (unbiased) {
    return sqrError / (values.length - 1);
  } else {
    return sqrError / values.length;
  }
}

/**
 * Finds the standard deviation for the data at hand
 * @param values - values in the data
 * @param options - options
 * @returns standard deviation
 */
function xStandardDeviation(values, options = {}) {
  return Math.sqrt(xVariance(values, options));
}

/**
 * This function divide the first array by the second array or a constant value to each element of the first array
 * @param array1 - first array
 * @param array2 - second array or number
 * @param options - options
 */
function xDivide(array1, array2, options = {}) {
  let isConstant = false;
  let constant = 0;
  if (isAnyArray$1(array2)) {
    if (array1.length !== array2.length) {
      throw new RangeError('size of array1 and array2 must be identical');
    }
  } else {
    isConstant = true;
    constant = array2;
  }
  const array3 = getOutputArray(options.output, array1.length);
  if (isConstant) {
    for (let i = 0; i < array1.length; i++) {
      array3[i] = array1[i] / constant;
    }
  } else {
    for (let i = 0; i < array1.length; i++) {
      array3[i] = array1[i] / array2[i];
    }
  }
  return array3;
}

/**
 * Returns a copy of the data as a Float64Array.
 * @param array - array of numbers
 */
function xEnsureFloat64(array) {
  xCheck(array);
  if (array instanceof Float64Array) {
    return array.slice(0);
  }
  return Float64Array.from(array);
}

function FFT(size) {
  this.size = size | 0;
  if (this.size <= 1 || (this.size & this.size - 1) !== 0) throw new Error('FFT size must be a power of two and bigger than 1');
  this._csize = size << 1;

  // NOTE: Use of `var` is intentional for old V8 versions
  var table = new Array(this.size * 2);
  for (var i = 0; i < table.length; i += 2) {
    const angle = Math.PI * i / this.size;
    table[i] = Math.cos(angle);
    table[i + 1] = -Math.sin(angle);
  }
  this.table = table;

  // Find size's power of two
  var power = 0;
  for (var t = 1; this.size > t; t <<= 1) power++;

  // Calculate initial step's width:
  //   * If we are full radix-4 - it is 2x smaller to give inital len=8
  //   * Otherwise it is the same as `power` to give len=4
  this._width = power % 2 === 0 ? power - 1 : power;

  // Pre-compute bit-reversal patterns
  this._bitrev = new Array(1 << this._width);
  for (var j = 0; j < this._bitrev.length; j++) {
    this._bitrev[j] = 0;
    for (var shift = 0; shift < this._width; shift += 2) {
      var revShift = this._width - shift - 2;
      this._bitrev[j] |= (j >>> shift & 3) << revShift;
    }
  }
  this._out = null;
  this._data = null;
  this._inv = 0;
}
FFT.prototype.fromComplexArray = function fromComplexArray(complex, storage) {
  var res = storage || new Array(complex.length >>> 1);
  for (var i = 0; i < complex.length; i += 2) res[i >>> 1] = complex[i];
  return res;
};
FFT.prototype.createComplexArray = function createComplexArray() {
  const res = new Array(this._csize);
  for (var i = 0; i < res.length; i++) res[i] = 0;
  return res;
};
FFT.prototype.toComplexArray = function toComplexArray(input, storage) {
  var res = storage || this.createComplexArray();
  for (var i = 0; i < res.length; i += 2) {
    res[i] = input[i >>> 1];
    res[i + 1] = 0;
  }
  return res;
};
FFT.prototype.completeSpectrum = function completeSpectrum(spectrum) {
  var size = this._csize;
  var half = size >>> 1;
  for (var i = 2; i < half; i += 2) {
    spectrum[size - i] = spectrum[i];
    spectrum[size - i + 1] = -spectrum[i + 1];
  }
};
FFT.prototype.transform = function transform(out, data) {
  if (out === data) throw new Error('Input and output buffers must be different');
  this._out = out;
  this._data = data;
  this._inv = 0;
  this._transform4();
  this._out = null;
  this._data = null;
};
FFT.prototype.realTransform = function realTransform(out, data) {
  if (out === data) throw new Error('Input and output buffers must be different');
  this._out = out;
  this._data = data;
  this._inv = 0;
  this._realTransform4();
  this._out = null;
  this._data = null;
};
FFT.prototype.inverseTransform = function inverseTransform(out, data) {
  if (out === data) throw new Error('Input and output buffers must be different');
  this._out = out;
  this._data = data;
  this._inv = 1;
  this._transform4();
  for (var i = 0; i < out.length; i++) out[i] /= this.size;
  this._out = null;
  this._data = null;
};

// radix-4 implementation
//
// NOTE: Uses of `var` are intentional for older V8 version that do not
// support both `let compound assignments` and `const phi`
FFT.prototype._transform4 = function _transform4() {
  var out = this._out;
  var size = this._csize;

  // Initial step (permute and transform)
  var width = this._width;
  var step = 1 << width;
  var len = size / step << 1;
  var outOff;
  var t;
  var bitrev = this._bitrev;
  if (len === 4) {
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleTransform2(outOff, off, step);
    }
  } else {
    // len === 8
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleTransform4(outOff, off, step);
    }
  }

  // Loop through steps in decreasing order
  var inv = this._inv ? -1 : 1;
  var table = this.table;
  for (step >>= 2; step >= 2; step >>= 2) {
    len = size / step << 1;
    var quarterLen = len >>> 2;

    // Loop through offsets in the data
    for (outOff = 0; outOff < size; outOff += len) {
      // Full case
      var limit = outOff + quarterLen;
      for (var i = outOff, k = 0; i < limit; i += 2, k += step) {
        const A = i;
        const B = A + quarterLen;
        const C = B + quarterLen;
        const D = C + quarterLen;

        // Original values
        const Ar = out[A];
        const Ai = out[A + 1];
        const Br = out[B];
        const Bi = out[B + 1];
        const Cr = out[C];
        const Ci = out[C + 1];
        const Dr = out[D];
        const Di = out[D + 1];

        // Middle values
        const MAr = Ar;
        const MAi = Ai;
        const tableBr = table[k];
        const tableBi = inv * table[k + 1];
        const MBr = Br * tableBr - Bi * tableBi;
        const MBi = Br * tableBi + Bi * tableBr;
        const tableCr = table[2 * k];
        const tableCi = inv * table[2 * k + 1];
        const MCr = Cr * tableCr - Ci * tableCi;
        const MCi = Cr * tableCi + Ci * tableCr;
        const tableDr = table[3 * k];
        const tableDi = inv * table[3 * k + 1];
        const MDr = Dr * tableDr - Di * tableDi;
        const MDi = Dr * tableDi + Di * tableDr;

        // Pre-Final values
        const T0r = MAr + MCr;
        const T0i = MAi + MCi;
        const T1r = MAr - MCr;
        const T1i = MAi - MCi;
        const T2r = MBr + MDr;
        const T2i = MBi + MDi;
        const T3r = inv * (MBr - MDr);
        const T3i = inv * (MBi - MDi);

        // Final values
        const FAr = T0r + T2r;
        const FAi = T0i + T2i;
        const FCr = T0r - T2r;
        const FCi = T0i - T2i;
        const FBr = T1r + T3i;
        const FBi = T1i - T3r;
        const FDr = T1r - T3i;
        const FDi = T1i + T3r;
        out[A] = FAr;
        out[A + 1] = FAi;
        out[B] = FBr;
        out[B + 1] = FBi;
        out[C] = FCr;
        out[C + 1] = FCi;
        out[D] = FDr;
        out[D + 1] = FDi;
      }
    }
  }
};

// radix-2 implementation
//
// NOTE: Only called for len=4
FFT.prototype._singleTransform2 = function _singleTransform2(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const evenR = data[off];
  const evenI = data[off + 1];
  const oddR = data[off + step];
  const oddI = data[off + step + 1];
  const leftR = evenR + oddR;
  const leftI = evenI + oddI;
  const rightR = evenR - oddR;
  const rightI = evenI - oddI;
  out[outOff] = leftR;
  out[outOff + 1] = leftI;
  out[outOff + 2] = rightR;
  out[outOff + 3] = rightI;
};

// radix-4
//
// NOTE: Only called for len=8
FFT.prototype._singleTransform4 = function _singleTransform4(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const inv = this._inv ? -1 : 1;
  const step2 = step * 2;
  const step3 = step * 3;

  // Original values
  const Ar = data[off];
  const Ai = data[off + 1];
  const Br = data[off + step];
  const Bi = data[off + step + 1];
  const Cr = data[off + step2];
  const Ci = data[off + step2 + 1];
  const Dr = data[off + step3];
  const Di = data[off + step3 + 1];

  // Pre-Final values
  const T0r = Ar + Cr;
  const T0i = Ai + Ci;
  const T1r = Ar - Cr;
  const T1i = Ai - Ci;
  const T2r = Br + Dr;
  const T2i = Bi + Di;
  const T3r = inv * (Br - Dr);
  const T3i = inv * (Bi - Di);

  // Final values
  const FAr = T0r + T2r;
  const FAi = T0i + T2i;
  const FBr = T1r + T3i;
  const FBi = T1i - T3r;
  const FCr = T0r - T2r;
  const FCi = T0i - T2i;
  const FDr = T1r - T3i;
  const FDi = T1i + T3r;
  out[outOff] = FAr;
  out[outOff + 1] = FAi;
  out[outOff + 2] = FBr;
  out[outOff + 3] = FBi;
  out[outOff + 4] = FCr;
  out[outOff + 5] = FCi;
  out[outOff + 6] = FDr;
  out[outOff + 7] = FDi;
};

// Real input radix-4 implementation
FFT.prototype._realTransform4 = function _realTransform4() {
  var out = this._out;
  var size = this._csize;

  // Initial step (permute and transform)
  var width = this._width;
  var step = 1 << width;
  var len = size / step << 1;
  var outOff;
  var t;
  var bitrev = this._bitrev;
  if (len === 4) {
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleRealTransform2(outOff, off >>> 1, step >>> 1);
    }
  } else {
    // len === 8
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleRealTransform4(outOff, off >>> 1, step >>> 1);
    }
  }

  // Loop through steps in decreasing order
  var inv = this._inv ? -1 : 1;
  var table = this.table;
  for (step >>= 2; step >= 2; step >>= 2) {
    len = size / step << 1;
    var halfLen = len >>> 1;
    var quarterLen = halfLen >>> 1;
    var hquarterLen = quarterLen >>> 1;

    // Loop through offsets in the data
    for (outOff = 0; outOff < size; outOff += len) {
      for (var i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {
        var A = outOff + i;
        var B = A + quarterLen;
        var C = B + quarterLen;
        var D = C + quarterLen;

        // Original values
        var Ar = out[A];
        var Ai = out[A + 1];
        var Br = out[B];
        var Bi = out[B + 1];
        var Cr = out[C];
        var Ci = out[C + 1];
        var Dr = out[D];
        var Di = out[D + 1];

        // Middle values
        var MAr = Ar;
        var MAi = Ai;
        var tableBr = table[k];
        var tableBi = inv * table[k + 1];
        var MBr = Br * tableBr - Bi * tableBi;
        var MBi = Br * tableBi + Bi * tableBr;
        var tableCr = table[2 * k];
        var tableCi = inv * table[2 * k + 1];
        var MCr = Cr * tableCr - Ci * tableCi;
        var MCi = Cr * tableCi + Ci * tableCr;
        var tableDr = table[3 * k];
        var tableDi = inv * table[3 * k + 1];
        var MDr = Dr * tableDr - Di * tableDi;
        var MDi = Dr * tableDi + Di * tableDr;

        // Pre-Final values
        var T0r = MAr + MCr;
        var T0i = MAi + MCi;
        var T1r = MAr - MCr;
        var T1i = MAi - MCi;
        var T2r = MBr + MDr;
        var T2i = MBi + MDi;
        var T3r = inv * (MBr - MDr);
        var T3i = inv * (MBi - MDi);

        // Final values
        var FAr = T0r + T2r;
        var FAi = T0i + T2i;
        var FBr = T1r + T3i;
        var FBi = T1i - T3r;
        out[A] = FAr;
        out[A + 1] = FAi;
        out[B] = FBr;
        out[B + 1] = FBi;

        // Output final middle point
        if (i === 0) {
          var FCr = T0r - T2r;
          var FCi = T0i - T2i;
          out[C] = FCr;
          out[C + 1] = FCi;
          continue;
        }

        // Do not overwrite ourselves
        if (i === hquarterLen) continue;

        // In the flipped case:
        // MAi = -MAi
        // MBr=-MBi, MBi=-MBr
        // MCr=-MCr
        // MDr=MDi, MDi=MDr
        var ST0r = T1r;
        var ST0i = -T1i;
        var ST1r = T0r;
        var ST1i = -T0i;
        var ST2r = -inv * T3i;
        var ST2i = -inv * T3r;
        var ST3r = -inv * T2i;
        var ST3i = -inv * T2r;
        var SFAr = ST0r + ST2r;
        var SFAi = ST0i + ST2i;
        var SFBr = ST1r + ST3i;
        var SFBi = ST1i - ST3r;
        var SA = outOff + quarterLen - i;
        var SB = outOff + halfLen - i;
        out[SA] = SFAr;
        out[SA + 1] = SFAi;
        out[SB] = SFBr;
        out[SB + 1] = SFBi;
      }
    }
  }
};

// radix-2 implementation
//
// NOTE: Only called for len=4
FFT.prototype._singleRealTransform2 = function _singleRealTransform2(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const evenR = data[off];
  const oddR = data[off + step];
  const leftR = evenR + oddR;
  const rightR = evenR - oddR;
  out[outOff] = leftR;
  out[outOff + 1] = 0;
  out[outOff + 2] = rightR;
  out[outOff + 3] = 0;
};

// radix-4
//
// NOTE: Only called for len=8
FFT.prototype._singleRealTransform4 = function _singleRealTransform4(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const inv = this._inv ? -1 : 1;
  const step2 = step * 2;
  const step3 = step * 3;

  // Original values
  const Ar = data[off];
  const Br = data[off + step];
  const Cr = data[off + step2];
  const Dr = data[off + step3];

  // Pre-Final values
  const T0r = Ar + Cr;
  const T1r = Ar - Cr;
  const T2r = Br + Dr;
  const T3r = inv * (Br - Dr);

  // Final values
  const FAr = T0r + T2r;
  const FBr = T1r;
  const FBi = -T3r;
  const FCr = T0r - T2r;
  const FDr = T1r;
  const FDi = T3r;
  out[outOff] = FAr;
  out[outOff + 1] = 0;
  out[outOff + 2] = FBr;
  out[outOff + 3] = FBi;
  out[outOff + 4] = FCr;
  out[outOff + 5] = 0;
  out[outOff + 6] = FDr;
  out[outOff + 7] = FDi;
};

/**
 * Create an array with numbers between "from" and "to" of length "length"
 * @param options - options
 * @returns - array of distributed numbers between "from" and "to"
 */
function createFromToArray(options = {}) {
  const {
    from = 0,
    to = 1,
    length = 1000,
    includeFrom = true,
    includeTo = true,
    distribution = 'uniform'
  } = options;
  const array = new Float64Array(length);
  let div = length;
  if (includeFrom && includeTo) {
    div = length - 1;
  } else if (!includeFrom && includeTo || includeFrom && !includeTo) {
    div = length;
  } else if (!includeFrom && !includeTo) {
    div = length + 1;
  }
  const delta = (to - from) / div;
  if (distribution === 'uniform') {
    if (includeFrom) {
      let index = 0;
      while (index < length) {
        array[index] = from + delta * index;
        index++;
      }
    } else {
      let index = 0;
      while (index < length) {
        array[index] = from + delta * (index + 1);
        index++;
      }
    }
  } else if (distribution === 'log') {
    const base = (to / from) ** (1 / div);
    const firstExponent = Math.log(from) / Math.log(base);
    if (includeFrom) {
      let index = 0;
      while (index < length) {
        array[index] = base ** (firstExponent + index);
        index++;
      }
    } else {
      let index = 0;
      while (index < length) {
        array[index] = base ** (firstExponent + index + 1);
        index++;
      }
    }
  } else {
    throw new Error('distribution must be uniform or log');
  }
  return array;
}

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
 * Stringify an object and convert all typed arrays to arrays
 * @param object
 * @param replacer
 * @param space
 * @returns
 */
function stringify(object, replacer, space) {
  const internalReplacer = (key, value) => {
    if (ArrayBuffer.isView(value)) {
      value = Array.from(value);
    }
    return value;
  };
  return JSON.stringify(object, internalReplacer, space);
}

/**
 * Computes the maximal value of an array of values
 * @param array - array of numbers
 * @param options - options
 */
function xMaxValue(array, options = {}) {
  xCheck(array);
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(array, options);
  let maxValue = array[fromIndex];
  for (let i = fromIndex + 1; i <= toIndex; i++) {
    if (array[i] > maxValue) {
      maxValue = array[i];
    }
  }
  return maxValue;
}

/**
 * Computes the minimal value of an array of values.
 * @param array - array of numbers
 * @param options - options
 */
function xMinValue(array, options = {}) {
  xCheck(array);
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(array, options);
  let minValue = array[fromIndex];
  for (let i = fromIndex + 1; i <= toIndex; i++) {
    if (array[i] < minValue) {
      minValue = array[i];
    }
  }
  return minValue;
}

/**
 * Check if the values are separated always by the same difference
 * @param array - Monotone growing array of number
 * @param options
 */
function xIsEquallySpaced(array, options = {}) {
  if (array.length < 3) return true;
  const {
    tolerance = 0.05
  } = options;
  let maxDx = 0;
  let minDx = Number.MAX_SAFE_INTEGER;
  for (let i = 0; i < array.length - 1; ++i) {
    const absoluteDifference = array[i + 1] - array[i];
    if (absoluteDifference < minDx) {
      minDx = absoluteDifference;
    }
    if (absoluteDifference > maxDx) {
      maxDx = absoluteDifference;
    }
  }
  return (maxDx - minDx) / maxDx < tolerance;
}

/**
 * Returns true if x is monotonic.
 * @param array - array of numbers.
 * @returns 1 if monotonic increasing, -1 if monotonic decreasing, 0 if not monotonic.
 */
function xIsMonotonic(array) {
  if (array.length <= 2) {
    return 1;
  }
  if (array[0] === array[1]) {
    // maybe a constant series
    for (let i = 1; i < array.length - 1; i++) {
      if (array[i] !== array[i + 1]) return 0;
    }
    return 1;
  }
  if (array[0] < array.at(-1)) {
    for (let i = 0; i < array.length - 1; i++) {
      if (array[i] >= array[i + 1]) return 0;
    }
    return 1;
  } else {
    for (let i = 0; i < array.length - 1; i++) {
      if (array[i] <= array[i + 1]) return 0;
    }
    return -1;
  }
}

/**
 * This function calculates the median absolute deviation (MAD).
 * https://en.wikipedia.org/wiki/Median_absolute_deviation
 * @param array
 */
function xMedianAbsoluteDeviation(array) {
  const median = xMedian(array);
  const averageDeviations = new Float64Array(array.length);
  for (let i = 0; i < array.length; i++) {
    averageDeviations[i] = Math.abs(array[i] - median);
  }
  return {
    median,
    mad: xMedian(averageDeviations)
  };
}

/**
 * Return min and max values of an array.
 * @param array - array of number
 * @returns - Object with 2 properties, min and max.
 */
function xMinMaxValues(array) {
  xCheck(array);
  let min = array[0];
  let max = array[0];
  for (const value of array) {
    if (value < min) min = value;
    if (value > max) max = value;
  }
  return {
    min,
    max
  };
}

/*
Adapted from: https://github.com/compute-io/erfcinv/blob/aa116e23883839359e310ad41a7c42f72815fc1e/lib/number.js

The MIT License (MIT)

Copyright (c) 2014-2015 The Compute.io Authors. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


Boost Software License - Version 1.0 - August 17th, 2003

Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following:

The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* eslint-disable no-loss-of-precision */
// Coefficients for erfcinv on [0, 0.5]:
const Y1 = 8.91314744949340820313e-2;
const P1 = [-0.005387729650712429, 8.22687874676915743155e-3, 2.19878681111168899165e-2, -0.03656379714117627, -0.012692614766297404, 3.34806625409744615033e-2, -0.008368748197417368, -5087819496582806e-19];
const Q1 = [8.86216390456424707504e-4, -0.0023339375937419, 7.95283687341571680018e-2, -0.05273963823400997, -0.7122890234154284, 6.62328840472002992063e-1, 1.56221558398423026363, -1.5657455823417585, -0.9700050433032906, 1];
// Coefficients for erfcinv for 0.5 > 1-x >= 0:
const Y2 = 2.249481201171875;
const P2 = [-3.6719225470772936, 2.11294655448340526258e1, 1.7445385985570866523e1, -44.6382324441787, -18.851064805871424, 1.76447298408374015486e1, 8.37050328343119927838, 1.05264680699391713268e-1, -0.20243350835593876];
const Q2 = [1.72114765761200282724, -22.643693341313973, 1.08268667355460159008e1, 4.85609213108739935468e1, -20.14326346804852, -28.66081804998, 3.9713437953343869095, 6.24264124854247537712, 1];
// Coefficients for erfcinv for sqrt( -log(1-x)):
const Y3 = 8.07220458984375e-1;
const P3 = [-681149956853777e-24, 2.85225331782217055858e-8, -6.794655751811263e-7, 2.14558995388805277169e-3, 2.90157910005329060432e-2, 1.42869534408157156766e-1, 3.37785538912035898924e-1, 3.87079738972604337464e-1, 1.17030156341995252019e-1, -0.16379404719331705, -0.1311027816799519];
const Q3 = [1.105924229346489121e-2, 1.52264338295331783612e-1, 8.48854343457902036425e-1, 2.59301921623620271374, 4.77846592945843778382, 5.38168345707006855425, 3.46625407242567245975, 1];
const Y4 = 9.3995571136474609375e-1;
const P4 = [2.66339227425782031962e-12, -2304047769118826e-25, 4.60469890584317994083e-6, 1.57544617424960554631e-4, 1.87123492819559223345e-3, 9.50804701325919603619e-3, 1.85573306514231072324e-2, -0.0022242652921344794, -0.0350353787183178];
const Q4 = [7.64675292302794483503e-5, 2.63861676657015992959e-3, 3.41589143670947727934e-2, 2.20091105764131249824e-1, 7.62059164553623404043e-1, 1.3653349817554063097, 1];
const Y5 = 9.8362827301025390625e-1;
const P5 = [9.9055709973310326855e-17, -2811287356288318e-29, 4.62596163522878599135e-9, 4.49696789927706453732e-7, 1.49624783758342370182e-5, 2.09386317487588078668e-4, 1.05628862152492910091e-3, -0.0011295143874558028, -0.016743100507663373];
const Q5 = [2.82243172016108031869e-7, 2.75335474764726041141e-5, 9.64011807005165528527e-4, 1.60746087093676504695e-2, 1.38151865749083321638e-1, 5.91429344886417493481e-1, 1];
/**
 * Polyval.
 * @param c - Array of Number.
 * @param x - Number.
 * @returns Number.
 */
function polyval(c, x) {
  let p = 0;
  for (const coef of c) {
    p = p * x + coef;
  }
  return p;
}
/**
 * Calculates a rational approximation.
 * @private
 * @param x - Number.
 * @param v - Number.
 * @param P - Array of polynomial coefficients.
 * @param Q - Array of polynomial coefficients.
 * @param Y - Number.
 * @returns Rational approximation.
 */
function calc(x, v, P, Q, Y) {
  const s = x - v;
  const r = polyval(P, s) / polyval(Q, s);
  return Y * x + r * x;
}
/**
 * Evaluates the complementary inverse error function for an input value.
 * @private
 * @param x - Input value.
 * @returns Evaluated complementary inverse error function.
 */
function erfcinv(x) {
  let sign = false;
  let val;
  let q;
  let g;
  let r;
  // [1] Special cases...
  // NaN:
  if (Number.isNaN(x)) {
    return Number.NaN;
  }
  // x not on the interval: [0,2]
  if (x < 0 || x > 2) {
    throw new RangeError(`erfcinv()::invalid input argument. Value must be on the interval [0,2]. Value: \`${x}\`.`);
  }
  if (x === 0) {
    return Number.POSITIVE_INFINITY;
  }
  if (x === 2) {
    return Number.NEGATIVE_INFINITY;
  }
  if (x === 1) {
    return 0;
  }
  // [2] Get the sign and make use of `erfc` reflection formula: `erfc(-z)=2 - erfc(z)`...
  if (x > 1) {
    q = 2 - x;
    x = 1 - q;
    sign = true;
  } else {
    q = x;
    x = 1 - x;
  }
  // [3] |x| <= 0.5
  if (x <= 0.5) {
    g = x * (x + 10);
    r = polyval(P1, x) / polyval(Q1, x);
    val = g * Y1 + g * r;
    return sign ? -val : val;
  }
  // [4] 1-|x| >= 0.25
  if (q >= 0.25) {
    g = Math.sqrt(-2 * Math.log(q));
    q = q - 0.25;
    r = polyval(P2, q) / polyval(Q2, q);
    val = g / (Y2 + r);
    return sign ? -val : val;
  }
  q = Math.sqrt(-Math.log(q));
  // [5] q < 3
  if (q < 3) {
    return calc(q, 1.125, P3, Q3, Y3);
  }
  // [6] q < 6
  if (q < 6) {
    return calc(q, 3, P4, Q4, Y4);
  }
  // Note that the smallest number in JavaScript is 5e-324. Math.sqrt( -Math.log( 5e-324 ) ) ~27.2844
  return calc(q, 6, P5, Q5, Y5);
  // Note that in the boost library, they are able to go to much smaller values, as 128 bit long doubles support ~1e-5000; something which JavaScript does not natively support.
}

/**
 * Applies a simple normalization inverse transformation to the input data.
 * @param data - The input array of numbers to be transformed.
 * @param options - Optional parameters for the transformation.
 * @returns A new Float64Array containing the transformed data.
 */
function simpleNormInv(data, options = {}) {
  const {
    magnitudeMode = false
  } = options;
  const result = new Float64Array(data.length);
  if (magnitudeMode) {
    for (let i = 0; i < result.length; i++) {
      result[i] = -Math.sqrt(-2 * Math.log(1 - data[i]));
    }
  } else {
    for (let i = 0; i < result.length; i++) {
      result[i] = -1 * Math.SQRT2 * erfcinv(2 * data[i]);
    }
  }
  return result;
}
/**
 * Convenience wrapper for single number processing by simpleNormInv function.
 * @param data - The number to be normalized.
 * @param options - The options for the normalization process.
 * @returns The normalized number.
 */
function simpleNormInvNumber(data, options = {}) {
  return simpleNormInv([data], options)[0];
}

/**
 * Determine noise level by san plot methodology (https://doi.org/10.1002/mrc.4882)
 * @param array - real or magnitude spectra data.
 * @param options - options
 * @returns noise level
 */
function xNoiseSanPlot(array, options = {}) {
  const {
    mask,
    cutOff,
    refine = true,
    magnitudeMode = false,
    scaleFactor = 1,
    factorStd = 5,
    fixOffset = true
  } = options;
  const input = prepareData(array, {
    scaleFactor,
    mask
  });
  if (fixOffset && !magnitudeMode) {
    const medianIndex = Math.floor(input.length / 2);
    const median = input.length % 2 === 0 ? 0.5 * (input[medianIndex - 1] + input[medianIndex]) : input[medianIndex];
    for (let i = 0; i < input.length; i++) {
      input[i] -= median;
    }
  }
  const firstNegativeValueIndex = input.at(-1) >= 0 ? input.length : input.findIndex(e => e < 0);
  let lastPositiveValueIndex = firstNegativeValueIndex - 1;
  for (let i = lastPositiveValueIndex; i >= 0; i--) {
    if (input[i] > 0) {
      lastPositiveValueIndex = i;
      break;
    }
  }
  const signPositive = input.slice(0, lastPositiveValueIndex + 1);
  const signNegative = input.slice(firstNegativeValueIndex);
  const cutOffDist = cutOff || determineCutOff(signPositive, {
    magnitudeMode
  });
  const pIndex = Math.floor(signPositive.length * cutOffDist);
  const initialNoiseLevelPositive = signPositive[pIndex];
  const skyPoint = signPositive[0];
  let initialNoiseLevelNegative;
  if (signNegative.length > 0) {
    const nIndex = Math.floor(signNegative.length * (1 - cutOffDist));
    initialNoiseLevelNegative = -1 * signNegative[nIndex];
  } else {
    initialNoiseLevelNegative = 0;
  }
  let noiseLevelPositive = initialNoiseLevelPositive;
  let noiseLevelNegative = initialNoiseLevelNegative;
  let cloneSignPositive = signPositive.slice();
  let cloneSignNegative = signNegative.slice();
  let cutOffSignalsIndexPlus = 0;
  let cutOffSignalsIndexNeg = 2;
  if (refine) {
    let cutOffSignals = noiseLevelPositive * factorStd;
    cutOffSignalsIndexPlus = signPositive.findIndex(e => e < cutOffSignals);
    if (cutOffSignalsIndexPlus > -1) {
      cloneSignPositive = signPositive.slice(cutOffSignalsIndexPlus);
      noiseLevelPositive = cloneSignPositive[Math.floor(cloneSignPositive.length * cutOffDist)];
    }
    cutOffSignals = noiseLevelNegative * factorStd;
    cutOffSignalsIndexNeg = signNegative.findIndex(e => e < cutOffSignals);
    if (cutOffSignalsIndexNeg > -1) {
      cloneSignNegative = signNegative.slice(cutOffSignalsIndexNeg);
      noiseLevelNegative = cloneSignPositive[Math.floor(cloneSignNegative.length * (1 - cutOffDist))];
    }
  }
  const correctionFactor = -simpleNormInvNumber(cutOffDist / 2, {
    magnitudeMode
  });
  let effectiveCutOffDist, refinedCorrectionFactor;
  if (refine && cutOffSignalsIndexPlus > -1) {
    effectiveCutOffDist = (cutOffDist * cloneSignPositive.length + cutOffSignalsIndexPlus) / (cloneSignPositive.length + cutOffSignalsIndexPlus);
    refinedCorrectionFactor = -1 * simpleNormInvNumber(effectiveCutOffDist / 2, {
      magnitudeMode
    });
    noiseLevelPositive /= refinedCorrectionFactor;
    if (cutOffSignalsIndexNeg > -1) {
      effectiveCutOffDist = (cutOffDist * cloneSignNegative.length + cutOffSignalsIndexNeg) / (cloneSignNegative.length + cutOffSignalsIndexNeg);
      refinedCorrectionFactor = -1 * simpleNormInvNumber(effectiveCutOffDist / 2, {
        magnitudeMode
      });
      if (noiseLevelNegative !== 0) {
        noiseLevelNegative /= refinedCorrectionFactor;
      }
    }
  } else {
    noiseLevelPositive /= correctionFactor;
    noiseLevelNegative /= correctionFactor;
  }
  return {
    positive: noiseLevelPositive,
    negative: noiseLevelNegative,
    snr: skyPoint / noiseLevelPositive,
    sanplot: generateSanPlot(input, {
      fromTo: {
        positive: {
          from: 0,
          to: lastPositiveValueIndex
        },
        negative: {
          from: firstNegativeValueIndex,
          to: input.length
        }
      }
    })
  };
}
/**
 * Determines the optimal cut-off point for a given array of positive numbers.
 * @param signPositive - An array of positive numbers.
 * @param options - Optional parameters to configure the cut-off determination.
 * @param options.magnitudeMode - If true, uses magnitude mode for normalization. Default is false.
 * @param options.considerList - An object specifying the range and step for consideration.
 * @param options.considerList.from - The starting point of the range. Default is 0.5.
 * @param options.considerList.step - The step size for the range. Default is 0.1.
 * @param options.considerList.to - The ending point of the range. Default is 0.9.
 * @returns The optimal cut-off point as a number.
 */
function determineCutOff(signPositive, options = {}) {
  const {
    magnitudeMode = false,
    considerList = {
      from: 0.5,
      step: 0.1,
      to: 0.9
    }
  } = options;
  //generate a list of values for
  const cutOff = [];
  const indexMax = signPositive.length - 1;
  for (let i = 0.01; i <= 0.99; i += 0.01) {
    const index = Math.round(indexMax * i);
    const value = -signPositive[index] / simpleNormInvNumber(i / 2, {
      magnitudeMode
    });
    cutOff.push([i, value]);
  }
  let minKi = Number.MAX_SAFE_INTEGER;
  const {
    from,
    to,
    step
  } = considerList;
  const delta = step / 2;
  let whereToCutStat = 0.5;
  for (let i = from; i <= to; i += step) {
    const floor = i - delta;
    const top = i + delta;
    const elementsOfCutOff = cutOff.filter(e => e[0] < top && e[0] > floor);
    let averageValue = 0;
    for (const element of elementsOfCutOff) {
      averageValue += Math.abs(element[1]);
    }
    let kiSqrt = 0;
    for (const element of elementsOfCutOff) {
      kiSqrt += (element[1] - averageValue) ** 2;
    }
    if (kiSqrt < minKi) {
      minKi = kiSqrt;
      whereToCutStat = i;
    }
  }
  return whereToCutStat;
}
/**
 * Generates a SAN plot from the given array based on the specified options.
 * @param array - The input array of numbers to be processed.
 * @param options - An optional object containing configuration options.
 * @param options.logBaseY - The logarithmic base for the Y-axis. Defaults to 2.
 * @param options.fromTo - An object specifying the range for each key. Each key maps to an object with `from` and `to` properties.
 * @returns An object where each key maps to a DataXY object containing the processed data.
 */
function generateSanPlot(array, options = {}) {
  const {
    fromTo,
    logBaseY = 2
  } = options;
  const sanplot = {};
  for (const key in fromTo) {
    const {
      from,
      to
    } = fromTo[key];
    sanplot[key] = from !== to ? scale(array.slice(from, to), {
      logBaseY
    }) : {
      x: [],
      y: []
    };
    if (key === 'negative') {
      sanplot[key].y.reverse();
    }
  }
  return sanplot;
}
/**
 * Scales the input array based on the provided options.
 * @param array - The input array to be scaled.
 * @param options - An optional object containing scaling options.
 * @param options.logBaseY - If provided, the array values will be scaled using the logarithm of this base.
 * @returns An object containing the scaled x and y arrays.
 */
function scale(array, options = {}) {
  const {
    log10,
    abs
  } = Math;
  const {
    logBaseY
  } = options;
  if (logBaseY) {
    array = array.slice(0);
    const logOfBase = log10(logBaseY);
    for (let i = 0; i < array.length; i++) {
      array[i] = log10(abs(array[i])) / logOfBase;
    }
  }
  const xAxis = createFromToArray({
    from: 0,
    to: array.length - 1,
    length: array.length
  });
  return {
    x: xAxis,
    y: array
  };
}
/**
 * Prepares and processes the input data array based on the provided options.
 * @param array - The input array of numbers to be processed.
 * @param options - An object containing the following properties:
 *   - scaleFactor: A number by which to scale each element of the array.
 *   - mask: An optional array of the same length as the input array, where
 *           elements corresponding to `true` values will be excluded from processing.
 * @param options.scaleFactor
 * @param options.mask
 * @returns A new Float64Array containing the processed data, scaled by the
 *          scaleFactor and sorted in descending order.
 */
function prepareData(array, options) {
  const {
    scaleFactor,
    mask
  } = options;
  const input = xEnsureFloat64(isAnyArray$1(mask) && mask.length === array.length ? array.filter((_e, i) => !mask[i]) : array);
  if (scaleFactor > 1) {
    for (let i = 0; i < input.length; i++) {
      input[i] *= scaleFactor;
    }
  }
  input.sort();
  input.reverse();
  return input;
}

/**
 * Determine noise level using MAD https://en.wikipedia.org/wiki/Median_absolute_deviation
 * Constant to convert mad to sd calculated using https://www.wolframalpha.com/input?i=sqrt%282%29+inverse+erf%280.5%29
 * This assumes a gaussian distribution of the noise
 * @param array
 * @returns noise level corresponding to one standard deviation
 */
function xNoiseStandardDeviation(array) {
  const {
    mad,
    median
  } = xMedianAbsoluteDeviation(array);
  return {
    sd: mad / 0.6744897501960817,
    mad,
    median
  };
}

/**
 * This function calculate the norm of a vector.
 * @example xNorm([3, 4]) -> 5
 * @param array - array
 * @returns - calculated norm
 */
function xNorm(array) {
  let result = 0;
  for (const element of array) {
    result += element ** 2;
  }
  return Math.sqrt(result);
}

/**
 * Calculate the sum of the values
 * @param array - Object that contains property x (an ordered increasing array) and y (an array).
 * @param options - Options.
 * @returns XSum value on the specified range.
 */
function xSum(array, options = {}) {
  xCheck(array);
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(array, options);
  let sumValue = array[fromIndex];
  for (let i = fromIndex + 1; i <= toIndex; i++) {
    sumValue += array[i];
  }
  return sumValue;
}

/**
 * Divides the data with either the sum, the absolute sum or the maximum of the data
 * @param input - Array containing values
 * @param options - options
 * @returns - normalized data
 */
function xNormed(input, options = {}) {
  const {
    algorithm = 'absolute',
    value = 1
  } = options;
  xCheck(input);
  const output = getOutputArray(options.output, input.length);
  if (input.length === 0) {
    throw new Error('input must not be empty');
  }
  switch (algorithm) {
    case 'absolute':
      {
        const absoluteSumValue = absoluteSum(input) / value;
        if (absoluteSumValue === 0) {
          throw new Error('trying to divide by 0');
        }
        for (let i = 0; i < input.length; i++) {
          output[i] = input[i] / absoluteSumValue;
        }
        return output;
      }
    case 'max':
      {
        const currentMaxValue = xMaxValue(input);
        if (currentMaxValue === 0) {
          throw new Error('trying to divide by 0');
        }
        const factor = value / currentMaxValue;
        for (let i = 0; i < input.length; i++) {
          output[i] = input[i] * factor;
        }
        return output;
      }
    case 'sum':
      {
        const sumFactor = xSum(input) / value;
        if (sumFactor === 0) {
          throw new Error('trying to divide by 0');
        }
        for (let i = 0; i < input.length; i++) {
          output[i] = input[i] / sumFactor;
        }
        return output;
      }
    default:
      throw new Error(`unknown algorithm: ${String(algorithm)}`);
  }
}
function absoluteSum(input) {
  let sumValue = 0;
  for (const value of input) {
    sumValue += Math.abs(value);
  }
  return sumValue;
}

/**
 * This function pads an array
 *s
 * @param array - the array that will be padded
 * @param options - options
 */
function xPadding(array, options = {}) {
  const {
    size = 0,
    value = 0,
    algorithm
  } = options;
  xCheck(array);
  if (!algorithm) {
    return xEnsureFloat64(array);
  }
  const result = new Float64Array(array.length + size * 2);
  for (let i = 0; i < array.length; i++) {
    result[i + size] = array[i];
  }
  const fromEnd = size + array.length;
  const toEnd = 2 * size + array.length;
  switch (algorithm) {
    case 'value':
      for (let i = 0; i < size; i++) {
        result[i] = value;
      }
      for (let i = fromEnd; i < toEnd; i++) {
        result[i] = value;
      }
      break;
    case 'duplicate':
      for (let i = 0; i < size; i++) {
        result[i] = array[0];
      }
      for (let i = fromEnd; i < toEnd; i++) {
        result[i] = array.at(-1);
      }
      break;
    case 'circular':
      for (let i = 0; i < size; i++) {
        result[i] = array[(array.length - size % array.length + i) % array.length];
      }
      for (let i = 0; i < size; i++) {
        result[i + fromEnd] = array[i % array.length];
      }
      break;
    default:
      throw new Error(`unknown algorithm ${String(algorithm)}`);
  }
  return result;
}

/**
 * Pareto scaling, which uses the square root of standard deviation as the scaling factor, circumvents the amplification of noise by retaining a small portion of magnitude information.
 * Noda, I. (2008). Scaling techniques to enhance two-dimensional correlation spectra. Journal of Molecular Structure, 883, 216-227.
 * DOI: 10.1016/j.molstruc.2007.12.026
 * @param array - array of number
 */
function xParetoNormalization(array) {
  xCheck(array);
  const result = new Float64Array(array.length);
  const sqrtSD = Math.sqrt(xStandardDeviation(array));
  for (let i = 0; i < array.length; i++) {
    result[i] = array[i] / sqrtSD;
  }
  return result;
}

/**
 * Function used to rescale data
 * @param input - input for the rescale
 * @param options - options
 * @returns rescaled data
 */
function xRescale(input, options = {}) {
  xCheck(input);
  const output = getOutputArray(options.output, input.length);
  const currentMin = xMinValue(input);
  const currentMax = xMaxValue(input);
  if (currentMin === currentMax) {
    throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');
  }
  const {
    min = 0,
    max = 1
  } = options;
  if (min >= max) {
    throw new RangeError('min option must be smaller than max option');
  }
  const factor = (max - min) / (currentMax - currentMin);
  for (let i = 0; i < input.length; i++) {
    output[i] = (input[i] - currentMin) * factor + min;
  }
  return output;
}

/**
 * This function calculates a rolling average
 * @param array - array
 * @param fct - callback function that from an array returns a value
 * @param options - options
 */
function xRolling(array, fct, options = {}) {
  xCheck(array);
  if (typeof fct !== 'function') {
    throw new TypeError('fct must be a function');
  }
  const {
    window = 5,
    padding = {}
  } = options;
  const {
    size = window - 1,
    algorithm,
    value
  } = padding;
  const padded = xPadding(array, {
    size,
    algorithm,
    value
  }); // ensure we get a copy and it is float64
  const newArray = [];
  for (let i = 0; i < padded.length - window + 1; i++) {
    // we will send a view to the original buffer
    newArray.push(fct(padded.subarray(i, i + window)));
  }
  return newArray;
}

/**
 * This function calculates a rolling average
 * @param array - array
 * @param options - option
 */
function xRollingAverage(array, options = {}) {
  return xRolling(array, xMean, options);
}

/**
 * This function calculates a rolling average
 * @param array - array
 * @param options - options
 */
function xRollingMedian(array, options = {}) {
  return xRolling(array, xMedian, options);
}

function matrixCheck(data) {
  if (data.length === 0 || data[0].length === 0) {
    throw new RangeError('matrix must contain data');
  }
  const firstLength = data[0].length;
  for (let i = 1; i < data.length; i++) {
    if (data[i].length !== firstLength) {
      throw new RangeError('all rows must has the same length');
    }
  }
}

/**
 * Get min and max Z.
 * @param matrix - matrix [rows][cols].
 */
function matrixMinMaxZ(matrix) {
  matrixCheck(matrix);
  const nbRows = matrix.length;
  const nbColumns = matrix[0].length;
  let min = matrix[0][0];
  let max = matrix[0][0];
  for (let column = 0; column < nbColumns; column++) {
    for (let row = 0; row < nbRows; row++) {
      if (matrix[row][column] < min) min = matrix[row][column];
      if (matrix[row][column] > max) max = matrix[row][column];
    }
  }
  return {
    min,
    max
  };
}

/**
 * Verify that `data` is an object of x,y arrays.
 * Throws an error if it's not.
 * @param data
 * @param options
 * @param options.minLength
 */
function xyCheck(data, options = {}) {
  const {
    minLength
  } = options;
  if (data === null || typeof data !== 'object' ||
  // @ts-expect-error Typechecking
  !isAnyArray$1(data.x) ||
  // @ts-expect-error Typechecking
  !isAnyArray$1(data.y)) {
    throw new Error('data must be an object of x and y arrays');
  }
  // @ts-expect-error Typechecking
  if (data.x.length !== data.y.length) {
    throw new Error('the x and y arrays must have the same length');
  }
  // @ts-expect-error Typechecking
  if (minLength && data.x.length < minLength) {
    throw new Error(`data.x must have a length of at least ${minLength}`);
  }
}

/**
 * Filters x,y values to allow strictly growing values in x-axis.
 * @param data - Object that contains property x (an ordered increasing array) and y (an array).
 */
function xyEnsureGrowingX(data) {
  xyCheck(data);
  if (xIsMonotonic(data.x) === 1) return data;
  const x = Array.from(data.x);
  const y = Array.from(data.y);
  let prevX = Number.NEGATIVE_INFINITY;
  let currentIndex = 0;
  for (let index = 0; index < x.length; index++) {
    if (prevX < x[index]) {
      if (currentIndex < index) {
        x[currentIndex] = x[index];
        y[currentIndex] = y[index];
      }
      currentIndex++;
      prevX = x[index];
    }
  }
  x.length = currentIndex;
  y.length = currentIndex;
  return {
    x,
    y
  };
}

/**
 * Normalize an array of zones:
 * - ensure than from < to
 * - merge overlapping zones
 * - deal with exclusions zones
 * - if no zones is specified add one between -Infinity and +Infinity
 * @param zones - array of zones
 * @param options - options
 * @returns array of zones
 */
function zonesNormalize(zones = [], options = {}) {
  const {
    exclusions = []
  } = options;
  let {
    from = Number.NEGATIVE_INFINITY,
    to = Number.POSITIVE_INFINITY
  } = options;
  if (from > to) [from, to] = [to, from];
  zones = zones.map(zone => zone.from > zone.to ? {
    from: zone.to,
    to: zone.from
  } : {
    ...zone
  });
  zones.sort((a, b) => {
    if (a.from !== b.from) return a.from - b.from;
    return a.to - b.to;
  });
  if (zones.length === 0) {
    zones.push({
      from,
      to
    });
  }
  for (const zone of zones) {
    if (from > zone.from) zone.from = from;
    if (to < zone.to) zone.to = to;
  }
  zones = zones.filter(zone => zone.from <= zone.to);
  if (zones.length === 0) return [];
  let currentZone = zones[0];
  const beforeExclusionsZones = [currentZone];
  for (let i = 1; i < zones.length; i++) {
    const zone = zones[i];
    if (zone.from <= currentZone.to) {
      if (currentZone.to < zone.to) {
        currentZone.to = zone.to;
      }
    } else {
      currentZone = zone;
      beforeExclusionsZones.push(currentZone);
    }
  }
  if (exclusions.length === 0) return beforeExclusionsZones;
  const normalizedExclusions = zonesNormalize(exclusions);
  let currentExclusionIndex = 0;
  const results = [];
  for (let zoneIndex = 0; zoneIndex < beforeExclusionsZones.length; zoneIndex++) {
    const zone = beforeExclusionsZones[zoneIndex];
    if (currentExclusionIndex === normalizedExclusions.length) {
      // we analysed all the exclusion zones
      results.push(zone);
      continue;
    }
    while (currentExclusionIndex < normalizedExclusions.length && normalizedExclusions[currentExclusionIndex].to <= zone.from) {
      currentExclusionIndex++;
    }
    if (currentExclusionIndex === normalizedExclusions.length) {
      // we analysed all the exclusion zones
      results.push(zone);
      continue;
    }
    if (zone.to < normalizedExclusions[currentExclusionIndex].from) {
      // no problems, not yet in exclusion
      results.push(zone);
      continue;
    }
    if (normalizedExclusions[currentExclusionIndex].to >= zone.to) {
      // could be totally excluded
      if (normalizedExclusions[currentExclusionIndex].from <= zone.from) {
        continue;
      }
      results.push({
        from: normalizedExclusions[currentExclusionIndex].to,
        to: zone.to
      });
    }
    // we cut in the middle, we need to create more zones, annoying !
    if (normalizedExclusions[currentExclusionIndex].from > zone.from) {
      results.push({
        from: zone.from,
        to: normalizedExclusions[currentExclusionIndex].from
      });
    }
    zone.from = normalizedExclusions[currentExclusionIndex].to;
    zoneIndex--;
  }
  return results;
}

/**
 * Add the number of points per zone to reach a specified total
 * @param zones - array of zones
 * @param numberOfPoints - total number of points to distribute between zones
 * @param options - options
 * @returns array of zones with points
 */
function zonesWithPoints(zones = [],
/**
 * total number of points to distribute between zones
 * @default 10
 */
numberOfPoints = 10, options = {}) {
  if (zones.length === 0) return [];
  const normalizedZones = zonesNormalize(zones, options);
  const zonesWithNumberOfPoints = [];
  const totalSize = normalizedZones.reduce((previous, current) => {
    return previous + (current.to - current.from);
  }, 0);
  const unitsPerPoint = totalSize / numberOfPoints;
  let currentTotal = 0;
  for (let i = 0; i < normalizedZones.length - 1; i++) {
    const tempZone = normalizedZones[i];
    const tempZoneNumberOfPoints = Math.min(Math.round((tempZone.to - tempZone.from) / unitsPerPoint), numberOfPoints - currentTotal);
    zonesWithNumberOfPoints.push({
      ...tempZone,
      numberOfPoints: tempZoneNumberOfPoints
    });
    currentTotal += tempZoneNumberOfPoints;
  }
  zonesWithNumberOfPoints.push({
    ...normalizedZones.at(-1),
    numberOfPoints: numberOfPoints - currentTotal
  });
  return zonesWithNumberOfPoints;
}

/**
 * Function that retrieves the getEquallySpacedData with the variant "slot".
 * @param x
 * @param y
 * @param from
 * @param to
 * @param numberOfPoints
 * @returns Array of y's equally spaced with the variant "slot"
 */
function equallySpacedSlot(/** x coordinates */
x, /** y coordinates */
y, /** from value */
from, /** to value */
to, /** number of points */
numberOfPoints) {
  const xLength = x.length;
  if (xLength < 2) {
    return Float64Array.from(x);
  }
  const step = (to - from) / (numberOfPoints > 1 ? numberOfPoints - 1 : 1);
  const halfStep = step / 2;
  const lastStep = x.at(-1) - x.at(-2);
  const start = from - halfStep;
  // Changed Array to Float64Array
  const output = new Float64Array(numberOfPoints);
  // Init main variables
  let min = start;
  let max = start + step;
  let previousX = -Number.MAX_VALUE;
  let previousY = 0;
  let nextX = x[0];
  let nextY = y[0];
  let frontOutsideSpectra = 0;
  let backOutsideSpectra = true;
  let currentValue = 0;
  // for slot algorithm
  let currentPoints = 0;
  let i = 1; // index of input
  let j = 0; // index of output
  main: while (true) {
    if (previousX >= nextX) throw new Error('x must be a growing series');
    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 integral value.
 */
function integral(/** first coordinate of point */
x0, /** second coordinate of point */
x1, /** slope of the line */
slope, /** intercept of the line on the y axis */
intercept) {
  return 0.5 * slope * x1 * x1 + intercept * x1 - (0.5 * slope * x0 * x0 + intercept * x0);
}

/**
 * Function that retrieves the getEquallySpacedData with the variant "smooth".
 * @param x
 * @param y
 * @param from
 * @param to
 * @param numberOfPoints
 * @returns - Array of y's equally spaced with the variant "smooth"
 */
function equallySpacedSmooth(/** x coordinates */
x, /** y coordinates */
y, /** from value */
from, /** to value */
to, /** number of points */
numberOfPoints) {
  const xLength = x.length;
  const step = (to - from) / (numberOfPoints > 1 ? numberOfPoints - 1 : 1);
  const halfStep = step / 2;
  // Changed Array to Float64Array
  const output = new Float64Array(numberOfPoints);
  const initialOriginalStep = x[1] - x[0];
  const lastOriginalStep = x[xLength - 1] - x[xLength - 2];
  // Init main variables
  let min = from - halfStep;
  let max = from + halfStep;
  let previousX = Number.MIN_SAFE_INTEGER;
  let previousY = 0;
  let nextX = x[0] - initialOriginalStep;
  let nextY = 0;
  let currentValue = 0;
  let slope = 0;
  let intercept = 0;
  let sumAtMin = 0;
  let sumAtMax = 0;
  let i = 0; // index of input
  let j = 0; // index of output
  let add = 0;
  main: while (true) {
    if (previousX >= nextX) throw new Error('x must be a growing series');
    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
      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 getSlope(x0, y0, x1, y1) {
  return (y1 - y0) / (x1 - x0);
}

/**
 * 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 an 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 an array.
 *
 * If exclusions zone are present, zones are ignored !
 * @param data - object containing 2 properties x and y
 * @param options - options
 * @returns new object with x / y array with the equally spaced data.
 */
function xyEquallySpaced(data, options = {}) {
  const {
    x,
    y
  } = data;
  const xLength = x.length;
  const {
    from = x[0],
    to = x[xLength - 1],
    variant = 'smooth',
    numberOfPoints = 100,
    exclusions = [],
    zones = [{
      from,
      to
    }]
  } = options;
  if (from > to) {
    throw new RangeError('from should be larger than to');
  }
  xyCheck(data);
  if (numberOfPoints < 2) {
    throw new RangeError("'numberOfPoints' option must be greater than 1");
  }
  const normalizedZones = zonesNormalize(zones, {
    from,
    to,
    exclusions
  });
  const zonesWithPointsRes = zonesWithPoints(normalizedZones, numberOfPoints, {
    from,
    to
  }).filter(zone => zone.numberOfPoints);
  let xResult = [];
  let yResult = [];
  for (const zone of zonesWithPointsRes) {
    if (!zone.numberOfPoints) {
      zone.numberOfPoints = 0;
    }
    const zoneResult = processZone(Array.from(x), Array.from(y), zone.from, zone.to, zone.numberOfPoints, variant);
    xResult = xResult.concat(zoneResult.x);
    yResult = yResult.concat(zoneResult.y);
  }
  return {
    x: xResult,
    y: yResult
  };
}
function processZone(x, y, from, to, numberOfPoints, variant) {
  if (numberOfPoints < 1) {
    throw new RangeError('the number of points must be at least 1');
  }
  const output = variant === 'slot' ? Array.from(equallySpacedSlot(x, y, from, to, numberOfPoints)) : Array.from(equallySpacedSmooth(x, y, from, to, numberOfPoints));
  return {
    x: Array.from(createFromToArray({
      from,
      to,
      length: numberOfPoints
    })),
    y: output
  };
}

/**
 * Filter an array x/y based on various criteria x points are expected to be sorted
 * @param data - object containing 2 properties x and y
 * @param options - options
 * @returns filtered array
 */
function xyFilterX(data, options = {}) {
  const {
    x,
    y
  } = data;
  if (x.length === 0) {
    return {
      x: Array.from(x),
      y: Array.from(y)
    };
  }
  const {
    from = x[0],
    to = x.at(-1),
    zones = [{
      from,
      to
    }],
    exclusions = []
  } = options;
  const normalizedZones = zonesNormalize(zones, {
    from,
    to,
    exclusions
  });
  let currentZoneIndex = 0;
  const newX = [];
  const newY = [];
  let position = 0;
  while (position < x.length) {
    if (x[position] <= normalizedZones[currentZoneIndex].to && x[position] >= normalizedZones[currentZoneIndex].from) {
      newX.push(x[position]);
      newY.push(y[position]);
    } else if (x[position] > normalizedZones[currentZoneIndex].to) {
      currentZoneIndex++;
      if (!normalizedZones[currentZoneIndex]) break;
    }
    position++;
  }
  return {
    x: newX,
    y: newY
  };
}

/**
 * Filter out all the points for which x <= 0. Useful to display log scale data
 * @param data - data
 * @returns - An object with the filtered data
 */
function xyFilterXPositive(data) {
  xyCheck(data);
  const {
    x,
    y
  } = data;
  const newX = [];
  const newY = [];
  if (x === undefined || y === undefined) {
    return {
      x: newX,
      y: newY
    };
  }
  for (let i = 0; i < x.length; i++) {
    if (x[i] > 0) {
      newX.push(x[i]);
      newY.push(y[i]);
    }
  }
  return {
    x: newX,
    y: newY
  };
}

/**
 * Order object of array, x has to be monotone. Ensure x is growing
 * @param data - Object of kind {x:[], y:[]}.
 */
function xyGrowingX(data) {
  const {
    x,
    y
  } = data;
  if (x.length !== y.length) {
    throw new TypeError('length of x and y must be identical');
  }
  if (x.length < 2 || x[0] < x.at(-1)) return data;
  return {
    x: x.toReversed(),
    y: y.toReversed()
  };
}

/**
 * Find the closest maximum going up hill
 * @param data - Object that contains property x (an ordered increasing array) and y (an array)
 * @param options - options
 * @returns - An object with the x/y value
 */
function xyMaxClosestYPoint(data, options = {}) {
  xyCheck(data);
  const {
    x,
    y
  } = data;
  const {
    target
  } = options;
  let {
    targetIndex
  } = options;
  if (targetIndex === undefined) {
    if (target !== undefined) {
      targetIndex = xFindClosestIndex(x, target);
    } else {
      targetIndex = 0;
    }
  }
  let previousIndex = Number.MIN_SAFE_INTEGER;
  let currentIndex = targetIndex;
  let xyMaxY = y[targetIndex];
  while (currentIndex !== previousIndex) {
    previousIndex = currentIndex;
    if (currentIndex > 0 && y[currentIndex - 1] > xyMaxY) {
      currentIndex--;
    } else if (currentIndex < x.length - 1 && y[currentIndex + 1] > xyMaxY) {
      currentIndex++;
    }
    xyMaxY = y[currentIndex];
  }
  return {
    x: x[currentIndex],
    y: y[currentIndex],
    index: currentIndex
  };
}

/**
 * Find the closest minimum going down hill
 * @param data - Object that contains property x (an ordered increasing array) and y (an array)
 * @param options - Options
 * @returns - An object with the x/y value
 */
function xyMinClosestYPoint(data, options = {}) {
  xyCheck(data);
  const {
    x,
    y
  } = data;
  const {
    target
  } = options;
  let {
    targetIndex
  } = options;
  if (targetIndex === undefined) {
    if (target !== undefined) {
      targetIndex = xFindClosestIndex(x, target);
    } else {
      targetIndex = 0;
    }
  }
  let previousIndex = Number.MIN_SAFE_INTEGER;
  let currentIndex = targetIndex;
  let minY = y[targetIndex];
  while (currentIndex !== previousIndex) {
    previousIndex = currentIndex;
    if (currentIndex > 0 && y[currentIndex - 1] < minY) {
      currentIndex--;
    } else if (currentIndex < x.length - 1 && y[currentIndex + 1] < minY) {
      currentIndex++;
    }
    minY = y[currentIndex];
  }
  return {
    x: x[currentIndex],
    y: y[currentIndex],
    index: currentIndex
  };
}

function addStyle(serie, spectrum, options = {}) {
  let {
    color = '#A9A9A9'
  } = options;
  const {
    opacity = 1,
    lineWidth = 1
  } = options;
  if (color.match(/#[\da-f]{6}$/i)) {
    color = (color + (opacity * 255 >> 0).toString(16)).toUpperCase();
  } else {
    color = color.replace(/rgb ?\((.*)\)/, `rgba($1,${opacity})`);
  }
  serie.style = [{
    name: 'unselected',
    style: {
      line: {
        color,
        width: lineWidth,
        dash: 1
      }
    }
  }, {
    name: 'selected',
    style: {
      line: {
        color,
        width: lineWidth + 2,
        dash: 1
      }
    }
  }];
  serie.name = spectrum.label || spectrum.id;
}

const COLORS = ['#FFB300', '#803E75', '#FF6800', '#A6BDD7', '#C10020', '#CEA262', '#817066', '#007D34', '#F6768E', '#00538A', '#FF7A5C', '#53377A', '#FF8E00', '#B32851', '#F4C800', '#7F180D', '#93AA00', '#593315', '#F13A13', '#232C16'];

/**
 * Generate a jsgraph chart format from an array of Analysis
 * @param analyses
 * @param options
 */
function getJSGraph(analyses, options = {}) {
  const {
    colors = COLORS,
    opacities = [1],
    linesWidth = [1],
    selector = {},
    normalization,
    xAxis = {},
    yAxis = {}
  } = options;
  const series = [];
  let xLabel = xAxis.label;
  let yLabel = yAxis.label;
  let xUnits = xAxis.units;
  let yUnits = yAxis.units;
  for (let i = 0; i < analyses.length; i++) {
    const analysis = analyses[i];
    const spectra = analysis.getNormalizedSpectra({
      selector,
      normalization
    });
    if (spectra.length === 0) continue;
    const firstSpectrum = spectra[0];
    // todo: if many spectra are available and not xUnits / yUnits are specified we should ensure that all the spectra are compatible
    if (!xLabel) xLabel = firstSpectrum.variables.x.label;
    if (!yLabel) yLabel = firstSpectrum.variables.y.label;
    if (!xUnits) xUnits = firstSpectrum.variables.x.units;
    if (!yUnits) yUnits = firstSpectrum.variables.y.units;
    for (const spectrum of spectra) {
      const serie = {};
      addStyle(serie, analysis, {
        color: colors[i % colors.length],
        opacity: opacities[i % opacities.length],
        lineWidth: linesWidth[i % linesWidth.length]
      });
      serie.data = {
        x: spectrum.variables.x.data,
        y: spectrum.variables.y.data
      };
      serie.id = spectrum.id;
      if (xAxis.logScale) {
        serie.data = xyFilterXPositive(serie.data);
      }
      series.push(serie);
    }
  }
  return {
    axes: {
      x: {
        label: xLabel,
        unit: xUnits,
        unitWrapperBefore: '(',
        unitWrapperAfter: ')',
        flipped: false,
        display: true,
        ...xAxis
      },
      y: {
        label: yLabel,
        unit: yUnits,
        unitWrapperBefore: '(',
        unitWrapperAfter: ')',
        flipped: false,
        display: true,
        ...yAxis
      }
    },
    series
  };
}

const defaultBoundary = {
  y: {
    min: '0px',
    max: '2000px'
  }
};
function getNormalizationAnnotations(filter = {}, boundary = defaultBoundary) {
  let {
    exclusions = []
  } = filter;
  let annotations = [];
  exclusions = exclusions.filter(exclusion => !exclusion.ignore);
  annotations = exclusions.map(exclusion => {
    const annotation = {
      type: 'rect',
      position: [{
        x: exclusion.from,
        y: boundary.y.min
      }, {
        x: exclusion.to,
        y: boundary.y.max
      }],
      strokeWidth: 0,
      fillColor: 'rgba(255,255,224,1)'
    };
    return annotation;
  });
  if (filter.from !== undefined) {
    annotations.push({
      type: 'rect',
      position: [{
        x: Number.MIN_SAFE_INTEGER,
        y: boundary.y.min
      }, {
        x: filter.from,
        y: boundary.y.max
      }],
      strokeWidth: 0,
      fillColor: 'rgba(255,255,224,1)'
    });
  }
  if (filter.to !== undefined) {
    annotations.push({
      type: 'rect',
      position: [{
        x: filter.to,
        y: boundary.y.min
      }, {
        x: Number.MAX_SAFE_INTEGER,
        y: boundary.y.max
      }],
      strokeWidth: 0,
      fillColor: 'rgba(255,255,224,1)'
    });
  }
  return annotations;
}

/**
 * Center the mean
 * @param data
 */
function centerMean(data) {
  const {
    y
  } = data;
  const mean = xMean(y);
  for (let i = 0; i < y.length; i++) {
    y[i] -= mean;
  }
  return {
    data
  };
}

/**
 * Center the median
 * @param data
 */
function centerMedian(data) {
  const {
    y
  } = data;
  const median = xMedian(y);
  for (let i = 0; i < y.length; i++) {
    y[i] -= median;
  }
  return {
    data
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function fromTo(data, options = {}) {
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(data.x, options);
  return {
    data: {
      x: data.x.subarray(fromIndex, toIndex + 1),
      y: data.y.subarray(fromIndex, toIndex + 1)
    }
  };
}

/**
 * Norm the Y values
 * @param data
 * @param options
 */
function normed(data, options = {}) {
  xNormed(data.y, {
    ...options,
    output: data.y
  });
  return {
    data
  };
}

/**
 * Center the mean
 * @param data
 */
function divideBySD(data) {
  const {
    y
  } = data;
  const sd = xStandardDeviation(y);
  for (let i = 0; i < y.length; i++) {
    y[i] /= sd;
  }
  return {
    data
  };
}

/**
 * Center the mean
 * @param data
 * @param options
 */
function rescale(data, options = {}) {
  xRescale(data.y, {
    ...options,
    output: data.y
  });
  return {
    data
  };
}

/**
 * Filter that allows to
 * @param data
 */
function paretoNormalization(data) {
  return {
    data: {
      x: data.x,
      y: xParetoNormalization(data.y)
    }
  };
}

// Based on https://github.com/scijs/cholesky-solve

/*
The MIT License (MIT)

Copyright (c) 2013 Eric Arnebäck

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

function ldlSymbolic(n /* A and L are n-by-n, where n >= 0 */, Ap /* input of size n + 1, not modified */, Ai /* input of size nz=Ap[n], not modified */, Lp /* output of size n + 1, not defined on input */, Parent /* output of size n, not defined on input */, Lnz /* output of size n, not defined on input */, Flag /* workspace of size n, not defn. on input or output */) {
  let i, k, p, kk, p2;
  for (k = 0; k < n; k++) {
    /* L(k,:) pattern: all nodes reachable in etree from nz in A(0:k-1,k) */
    Parent[k] = -1; /* parent of k is not yet known */
    Flag[k] = k; /* mark node k as visited */
    Lnz[k] = 0; /* count of nonzeros in column k of L */
    kk = k; /* kth original, or permuted, column */
    p2 = Ap[kk + 1];
    for (p = Ap[kk]; p < p2; p++) {
      /* A (i,k) is nonzero (original or permuted A) */
      i = Ai[p];
      if (i < k) {
        /* follow path from i to root of etree, stop at flagged node */
        for (; Flag[i] !== k; i = Parent[i]) {
          /* find parent of i if not yet determined */
          if (Parent[i] === -1) Parent[i] = k;
          Lnz[i]++; /* L (k,i) is nonzero */
          Flag[i] = k; /* mark i as visited */
        }
      }
    }
  }
  /* construct Lp index array from Lnz column counts */
  Lp[0] = 0;
  for (k = 0; k < n; k++) {
    Lp[k + 1] = Lp[k] + Lnz[k];
  }
}
function ldlNumeric(n /* A and L are n-by-n, where n >= 0 */, Ap /* input of size n+1, not modified */, Ai /* input of size nz=Ap[n], not modified */, Ax /* input of size nz=Ap[n], not modified */, Lp /* input of size n+1, not modified */, Parent /* input of size n, not modified */, Lnz /* output of size n, not defn. on input */, Li /* output of size lnz=Lp[n], not defined on input */, Lx /* output of size lnz=Lp[n], not defined on input */, D /* output of size n, not defined on input */, Y /* workspace of size n, not defn. on input or output */, Pattern /* workspace of size n, not defn. on input or output */, Flag /* workspace of size n, not defn. on input or output */) {
  let yi, lKi;
  let i, k, p, kk, p2, len, top;
  for (k = 0; k < n; k++) {
    /* compute nonzero Pattern of kth row of L, in topological order */
    Y[k] = 0.0; /* Y(0:k) is now all zero */
    top = n; /* stack for pattern is empty */
    Flag[k] = k; /* mark node k as visited */
    Lnz[k] = 0; /* count of nonzeros in column k of L */
    kk = k; /* kth original, or permuted, column */
    p2 = Ap[kk + 1];
    for (p = Ap[kk]; p < p2; p++) {
      i = Ai[p]; /* get A(i,k) */
      if (i <= k) {
        Y[i] += Ax[p]; /* scatter A(i,k) into Y (sum duplicates) */
        for (len = 0; Flag[i] !== k; i = Parent[i]) {
          Pattern[len++] = i; /* L(k,i) is nonzero */
          Flag[i] = k; /* mark i as visited */
        }
        while (len > 0) Pattern[--top] = Pattern[--len];
      }
    }
    /* compute numerical values kth row of L (a sparse triangular solve) */
    D[k] = Y[k]; /* get D(k,k) and clear Y(k) */
    Y[k] = 0.0;
    for (; top < n; top++) {
      i = Pattern[top]; /* Pattern[top:n-1] is pattern of L(:,k) */
      yi = Y[i]; /* get and clear Y(i) */
      Y[i] = 0.0;
      p2 = Lp[i] + Lnz[i];
      for (p = Lp[i]; p < p2; p++) {
        Y[Li[p]] -= Lx[p] * yi;
      }
      lKi = yi / D[i]; /* the nonzero entry L(k,i) */
      D[k] -= lKi * yi;
      Li[p] = k; /* store L(k,i) in column form of L */
      Lx[p] = lKi;
      Lnz[i]++; /* increment count of nonzeros in col i */
    }
    if (D[k] === 0.0) return k; /* failure, D(k,k) is zero */
  }
  return n; /* success, diagonal of D is all nonzero */
}
function ldlLsolve(n /* L is n-by-n, where n >= 0 */, X /* size n. right-hand-side on input, soln. on output */, Lp /* input of size n+1, not modified */, Li /* input of size lnz=Lp[n], not modified */, Lx /* input of size lnz=Lp[n], not modified */) {
  let j, p, p2;
  for (j = 0; j < n; j++) {
    p2 = Lp[j + 1];
    for (p = Lp[j]; p < p2; p++) {
      X[Li[p]] -= Lx[p] * X[j];
    }
  }
}
function ldlDsolve(n /* D is n-by-n, where n >= 0 */, X /* size n. right-hand-side on input, soln. on output */, D /* input of size n, not modified */) {
  let j;
  for (j = 0; j < n; j++) {
    X[j] /= D[j];
  }
}
function ldlLTsolve(n /* L is n-by-n, where n >= 0 */, X /* size n. right-hand-side on input, soln. on output */, Lp /* input of size n+1, not modified */, Li /* input of size lnz=Lp[n], not modified */, Lx /* input of size lnz=Lp[n], not modified */) {
  let j, p, p2;
  for (j = n - 1; j >= 0; j--) {
    p2 = Lp[j + 1];
    for (p = Lp[j]; p < p2; p++) {
      X[j] -= Lx[p] * X[Li[p]];
    }
  }
}
function ldlPerm(n /* size of X, B, and P */, X /* output of size n. */, B /* input of size n. */, P /* input permutation array of size n. */) {
  let j;
  for (j = 0; j < n; j++) {
    X[j] = B[P[j]];
  }
}
function ldlPermt(n /* size of X, B, and P */, X /* output of size n. */, B /* input of size n. */, P /* input permutation array of size n. */) {
  let j;
  for (j = 0; j < n; j++) {
    X[P[j]] = B[j];
  }
}
function prepare(M, n, P) {
  // if a permutation was specified, apply it.
  if (P) {
    let Pinv = new Array(n);
    for (let k = 0; k < n; k++) {
      Pinv[P[k]] = k;
    }
    let Mt = []; // scratch memory
    // Apply permutation. We make M into P*M*P^T
    for (let a = 0; a < M.length; ++a) {
      let ar = Pinv[M[a][0]];
      let ac = Pinv[M[a][1]];

      // we only store the upper-diagonal elements(since we assume matrix is symmetric, we only need to store these)
      // if permuted element is below diagonal, we simply transpose it.
      if (ac < ar) {
        let t = ac;
        ac = ar;
        ar = t;
      }
      Mt[a] = [];
      Mt[a][0] = ar;
      Mt[a][1] = ac;
      Mt[a][2] = M[a][2];
    }
    M = Mt; // copy scratch memory.
  } else {
    // if P argument is null, we just use an identity permutation.
    P = [];
    for (let i = 0; i < n; ++i) {
      P[i] = i;
    }
  }

  // The sparse matrix we are decomposing is A.
  // Now we shall create A from M.
  let Ap = new Array(n + 1);
  let Ai = new Array(M.length);
  let Ax = new Array(M.length);

  // count number of non-zero elements in columns.
  let LNZ = [];
  for (let i = 0; i < n; ++i) {
    LNZ[i] = 0;
  }
  for (let a = 0; a < M.length; ++a) {
    LNZ[M[a][1]]++;
  }
  Ap[0] = 0;
  for (let i = 0; i < n; ++i) {
    Ap[i + 1] = Ap[i] + LNZ[i];
  }
  let coloffset = [];
  for (let a = 0; a < n; ++a) {
    coloffset[a] = 0;
  }

  // go through all elements in M, and add them to sparse matrix A.
  for (let i = 0; i < M.length; ++i) {
    let e = M[i];
    let col = e[1];
    let adr = Ap[col] + coloffset[col];
    Ai[adr] = e[0];
    Ax[adr] = e[2];
    coloffset[col]++;
  }
  let D = new Array(n);
  let Y = new Array(n);
  let Lp = new Array(n + 1);
  let Parent = new Array(n);
  let Lnz = new Array(n);
  let Flag = new Array(n);
  let Pattern = new Array(n);
  let bp1 = new Array(n);
  let x = new Array(n);
  let d;
  ldlSymbolic(n, Ap, Ai, Lp, Parent, Lnz, Flag);
  let Lx = new Array(Lp[n]);
  let Li = new Array(Lp[n]);
  d = ldlNumeric(n, Ap, Ai, Ax, Lp, Parent, Lnz, Li, Lx, D, Y, Pattern, Flag);
  if (d === n) {
    return b => {
      ldlPerm(n, bp1, b, P);
      ldlLsolve(n, bp1, Lp, Li, Lx);
      ldlDsolve(n, bp1, D);
      ldlLTsolve(n, bp1, Lp, Li, Lx);
      ldlPermt(n, x, bp1, P);
      return x;
    };
  } else {
    return null;
  }
}

var cuthillMckee_1 = cuthillMckee$1;
function compareNum(a, b) {
  return a - b;
}
function cuthillMckee$1(list, n) {
  var adj = new Array(n);
  var visited = new Array(n);
  for (var i = 0; i < n; ++i) {
    adj[i] = [];
    visited[i] = false;
  }
  for (var i = 0; i < list.length; ++i) {
    var l = list[i];
    adj[l[0]].push(l[1]);
  }
  var toVisit = new Array(n);
  var eol = 0;
  var ptr = 0;
  for (var i = 0; i < n; ++i) {
    if (visited[i]) {
      continue;
    }
    toVisit[eol++] = i;
    visited[i] = true;
    while (ptr < eol) {
      var v = toVisit[ptr++];
      var nbhd = adj[v];
      nbhd.sort(compareNum);
      for (var j = 0; j < nbhd.length; ++j) {
        var u = nbhd[j];
        if (visited[u]) {
          continue;
        }
        visited[u] = true;
        toVisit[eol++] = u;
      }
    }
  }
  var result = new Array(n);
  for (var i = 0; i < n; ++i) {
    result[toVisit[i]] = i;
  }
  return result;
}
var cuthillMckee = /*@__PURE__*/getDefaultExportFromCjs(cuthillMckee_1);

const getClosestNumber = (array = [], goal = 0) => {
  const closest = array.reduce((prev, curr) => {
    return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
  });
  return closest;
};
const getCloseIndex = (array = [], goal = 0) => {
  const closest = getClosestNumber(array, goal);
  return array.indexOf(closest);
};
const updateSystem = (matrix, y, weights) => {
  let nbPoints = y.length;
  let l = nbPoints - 1;
  let newMatrix = new Array(matrix.length);
  let newVector = new Float64Array(nbPoints);
  for (let i = 0; i < l; i++) {
    let w = weights[i];
    let diag = i * 2;
    let next = diag + 1;
    newMatrix[diag] = matrix[diag].slice();
    newMatrix[next] = matrix[next].slice();
    if (w === 0) {
      newVector[i] = 0;
    } else {
      newVector[i] = y[i] * w;
      newMatrix[diag][2] += w;
    }
  }
  newVector[l] = y[l] * weights[l];
  newMatrix[l * 2] = matrix[l * 2].slice();
  newMatrix[l * 2][2] += weights[l];
  return [newMatrix, newVector];
};
const getDeltaMatrix = (nbPoints, lambda) => {
  let matrix = [];
  let last = nbPoints - 1;
  for (let i = 0; i < last; i++) {
    matrix.push([i, i, lambda * 2]);
    matrix.push([i + 1, i, -1 * lambda]);
  }
  matrix[0][2] = lambda;
  matrix.push([last, last, lambda]);
  return {
    lowerTriangularNonZeros: matrix,
    permutationEncodedArray: cuthillMckee(matrix, nbPoints)
  };
};

function getControlPoints(x, y, options = {}) {
  const {
    length
  } = x;
  let {
    controlPoints = Int8Array.from({
      length
    }).fill(0)
  } = options;
  const {
    zones = [],
    weights = Float64Array.from({
      length
    }).fill(1)
  } = options;
  if (x.length !== y.length) {
    throw new RangeError('Y should match the length with X');
  } else if (controlPoints.length !== x.length) {
    throw new RangeError('controlPoints should match the length with X');
  } else if (weights.length !== x.length) {
    throw new RangeError('weights should match the length with X');
  }
  zones.forEach(range => {
    let indexFrom = getCloseIndex(x, range.from);
    let indexTo = getCloseIndex(x, range.to);
    if (indexFrom > indexTo) [indexFrom, indexTo] = [indexTo, indexFrom];
    for (let i = indexFrom; i < indexTo; i++) {
      controlPoints[i] = 1;
    }
  });
  return {
    weights: 'controlPoints' in options || zones.length > 0 ? xMultiply(weights, controlPoints) : weights,
    controlPoints
  };
}

/**
 * Fit the baseline drift by iteratively changing weights of sum square error between the fitted baseline and original signals,
 * for further information about the parameters you can get the [paper of airPLS](https://github.com/zmzhang/airPLS/blob/main/airPLS_manuscript.pdf)
 * @param {Array<number>} x - x axis data useful when control points or zones are submitted
 * @param {Array<number>} y - Original data
 * @param {object} [options={}] - Options object
 * @param {number} [options.maxIterations = 100] - Maximal number of iterations if the method does not reach the stop criterion
 * @param {number} [options.tolerance = 0.001] - Factor of the sum of absolute value of original data, to compute stop criterion
 * @param {Array<number>} [options.weights = [1,1,...]] - Initial weights vector, default each point has the same weight
 * @param {number} [options.lambda = 100] - Factor of weights matrix in -> [I + lambda D'D]z = x
 * @param {Array<number>} [options.controlPoints = []] - Array of 0|1 to force the baseline cross those points.
 * @param {Array<number>} [options.zones = []] - Array of x axis values (as from - to), to force that baseline cross those zones.
 * @returns {{corrected: Array<number>, error: number, iteration: number, baseline: Array<number>}}
 */

function airPLS(x, y, options = {}) {
  const {
    weights,
    controlPoints
  } = getControlPoints(x, y, options);
  let {
    maxIterations = 100,
    lambda = 10,
    tolerance = 0.001
  } = options;
  let baseline, iteration;
  let sumNegDifferences = Number.MAX_SAFE_INTEGER;
  const corrected = Float64Array.from(y);
  let stopCriterion = getStopCriterion(y, tolerance);
  const {
    length
  } = y;
  let {
    lowerTriangularNonZeros,
    permutationEncodedArray
  } = getDeltaMatrix(length, lambda);
  let threshold = 1;
  const l = length - 1;
  let prevNegSum = Number.MAX_SAFE_INTEGER;
  for (iteration = 0; iteration < maxIterations && Math.abs(sumNegDifferences) > stopCriterion; iteration++) {
    let [leftHandSide, rightHandSide] = updateSystem(lowerTriangularNonZeros, y, weights);
    let cho = prepare(leftHandSide, length, permutationEncodedArray);
    baseline = cho(rightHandSide);
    sumNegDifferences = applyCorrection(y, baseline, corrected);
    if (iteration === 1) {
      const {
        positive
      } = xNoiseSanPlot(corrected);
      threshold = positive;
    } else {
      const absChange = Math.abs(prevNegSum / sumNegDifferences);
      if (absChange < 1.01 && absChange > 0.99) {
        break;
      }
    }
    prevNegSum = sumNegDifferences + 0;
    for (let i = 1; i < l; i++) {
      const diff = corrected[i];
      if (controlPoints[i] < 1 && Math.abs(diff) > threshold) {
        weights[i] = 0;
      } else {
        const factor = diff > 0 ? -1 : 1;
        weights[i] = Math.exp(factor * (iteration * diff) / Math.abs(sumNegDifferences));
      }
    }
    weights[0] = 1;
    weights[l] = 1;
  }
  return {
    corrected,
    baseline,
    iteration,
    error: sumNegDifferences
  };
  function applyCorrection(y, baseline, corrected) {
    let sumNegDifferences = 0;
    for (let i = 0; i < y.length; i++) {
      let diff = y[i] - baseline[i];
      if (diff < 0) sumNegDifferences += diff;
      corrected[i] = diff;
    }
    return sumNegDifferences;
  }
}
function getStopCriterion(y, tolerance) {
  let sum = xAbsoluteSum(y);
  return tolerance * sum;
}

function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function (obj) {
      return typeof obj;
    };
  } else {
    _typeof = function (obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }
  return _typeof(obj);
}

/**
 * Fill an array with sequential numbers
 * @param {Array<number>} [input] - optional destination array (if not provided a new array will be created)
 * @param {object} [options={}]
 * @param {number} [options.from=0] - first value in the array
 * @param {number} [options.to=10] - last value in the array
 * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step)
 * @param {number} [options.step] - if not provided calculated from size
 * @return {Array<number>}
 */

function sequentialFill() {
  var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (_typeof(input) === 'object' && !isAnyArray$1(input)) {
    options = input;
    input = [];
  }
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  var _options = options,
    _options$from = _options.from,
    from = _options$from === void 0 ? 0 : _options$from,
    _options$to = _options.to,
    to = _options$to === void 0 ? 10 : _options$to,
    _options$size = _options.size,
    size = _options$size === void 0 ? input.length : _options$size,
    step = _options.step;
  if (size !== 0 && step) {
    throw new Error('step is defined by the array size');
  }
  if (!size) {
    if (step) {
      size = Math.floor((to - from) / step) + 1;
    } else {
      size = to - from + 1;
    }
  }
  if (!step && size) {
    step = (to - from) / (size - 1);
  }
  if (Array.isArray(input)) {
    // only works with normal array
    input.length = 0;
    for (var i = 0; i < size; i++) {
      input.push(from);
      from += step;
    }
  } else {
    if (input.length !== size) {
      throw new Error('sequentialFill typed array must have the correct length');
    }
    for (var _i = 0; _i < size; _i++) {
      input[_i] = from;
      from += step;
    }
  }
  return input;
}

/**
 * Adaptive iteratively reweighted penalized least squares [1]
 *
 * This function calls ml-airpls
 *
 * References:
 * [1] Zhang, Z.-M.; Chen, S.; Liang, Y.-Z.
 * Baseline Correction Using Adaptive Iteratively Reweighted Penalized Least Squares.
 * Analyst 2010, 135 (5), 1138–1146. https://doi.org/10.1039/B922045C.
 * @export
 * @param {Array<number>} ys
 * @param {object} [options] - Options object
 * @param {Array<number>} [options.x] Optional, Independent axis variable. If not specified, we use a linear grid
 * @param {object} [options.regression] - Options for the regression
 * @param {number} [options.regression.maxIterations = 100] - Maximum number of allowed iterations
 * @param {function} [options.regression.§Regression = PolynomialRegression] - Regression class with a predict method
 * @param {*} [options.regression.regressionOptions] - Options for regressionFunction
 * @param {number} [options.regression.tolerance = 0.001] - Convergence error tolerance
 * @returns {BaselineOutput}
 */
function airPLSBaseline$1(ys, options = {}) {
  const numberPoints = ys.length;
  let {
    x,
    regressionOptions
  } = options;
  if (!x) {
    x = sequentialFill({
      from: 0,
      to: numberPoints - 1,
      size: numberPoints
    });
  }
  let output = airPLS(x, ys, regressionOptions);
  return {
    baseline: output.baseline,
    correctedSpectrum: output.corrected
  };
}

/**
 * Check that x and y are arrays with the same length.
 * @param x - first array
 * @param y - second array
 * @throws if x or y are not the same length, or if they are not arrays
 */
function checkArrayLength(x, y) {
  if (!isAnyArray$1(x) || !isAnyArray$1(y)) {
    throw new TypeError('x and y must be arrays');
  }
  if (x.length !== y.length) {
    throw new RangeError('x and y arrays must have the same length');
  }
}

class BaseRegression {
  constructor() {
    if (new.target === BaseRegression) {
      throw new Error('BaseRegression must be subclassed');
    }
  }
  predict(x) {
    if (typeof x === 'number') {
      return this._predict(x);
    } else if (isAnyArray$1(x)) {
      const y = [];
      for (const xVal of x) {
        y.push(this._predict(xVal));
      }
      return y;
    } else {
      throw new TypeError('x must be a number or array');
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _predict(x) {
    throw new Error('_predict must be implemented');
  }
  train() {
    // Do nothing for this package
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  toString(precision) {
    return '';
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  toLaTeX(precision) {
    return '';
  }
  /**
   * Return the correlation coefficient of determination (r) and chi-square.
   * @param x - explanatory variable
   * @param y - response variable
   * @return - Object with further statistics.
   */
  score(x, y) {
    checkArrayLength(x, y);
    const n = x.length;
    const y2 = new Array(n);
    for (let i = 0; i < n; i++) {
      y2[i] = this._predict(x[i]);
    }
    let xSum = 0;
    let ySum = 0;
    let chi2 = 0;
    let rmsd = 0;
    let xSquared = 0;
    let ySquared = 0;
    let xY = 0;
    for (let i = 0; i < n; i++) {
      xSum += y2[i];
      ySum += y[i];
      xSquared += y2[i] * y2[i];
      ySquared += y[i] * y[i];
      xY += y2[i] * y[i];
      if (y[i] !== 0) {
        chi2 += (y[i] - y2[i]) * (y[i] - y2[i]) / y[i];
      }
      rmsd += (y[i] - y2[i]) * (y[i] - y2[i]);
    }
    const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));
    return {
      r,
      r2: r * r,
      chi2,
      rmsd: Math.sqrt(rmsd / n)
    };
  }
}

/**
 * Cast `number` to string. Optionally `digits` specifies significant figures.
 * @param number
 * @param figures
 * @returns - A string representation of `number`.
 */
function maybeToPrecision(number, figures) {
  if (number < 0) {
    number = 0 - number;
    if (typeof figures === 'number') {
      return `- ${number.toPrecision(figures)}`;
    } else {
      return `- ${number.toString()}`;
    }
  } else if (typeof figures === 'number') {
    return number.toPrecision(figures);
  } else {
    return number.toString();
  }
}

class PolynomialRegression extends BaseRegression {
  /**
   * @param x - independent or explanatory variable
   * @param y - dependent or response variable
   * @param degree - degree of the polynomial regression, or array of powers to be used. When degree is an array, intercept at zero is forced to false/ignored.
   * @example `new PolynomialRegression(x, y, 2)`, in this case, you can pass the option `interceptAtZero`, if you need it.
   * @param options
   * @example `new PolynomialRegression(x, y, [1, 3, 5])`
   * Each of the degrees corresponds to a column, so if you have them switched, just do:
   * @example `new PolynomialRegression(x, y, [3, 1, 5])`
   * @param options.interceptAtZero - force the polynomial regression so that f(0) = 0
   */
  constructor(x, y, degree, options = {}) {
    super();
    // @ts-expect-error internal use only
    if (x === true) {
      // @ts-expect-error internal use only
      this.degree = y.degree;
      // @ts-expect-error internal use only
      this.powers = y.powers;
      // @ts-expect-error internal use only
      this.coefficients = y.coefficients;
    } else {
      checkArrayLength(x, y);
      const result = regress(x, y, degree, options);
      this.degree = result.degree;
      this.powers = result.powers;
      this.coefficients = result.coefficients;
    }
  }
  _predict(x) {
    let y = 0;
    for (let k = 0; k < this.powers.length; k++) {
      y += this.coefficients[k] * x ** this.powers[k];
    }
    return y;
  }
  toJSON() {
    return {
      name: 'polynomialRegression',
      degree: this.degree,
      powers: this.powers,
      coefficients: this.coefficients
    };
  }
  toString(precision) {
    return this._toFormula(precision, false);
  }
  toLaTeX(precision) {
    return this._toFormula(precision, true);
  }
  _toFormula(precision, isLaTeX) {
    let sup = '^';
    let closeSup = '';
    let times = ' * ';
    if (isLaTeX) {
      sup = '^{';
      closeSup = '}';
      times = '';
    }
    let fn = '';
    let str = '';
    for (let k = 0; k < this.coefficients.length; k++) {
      str = '';
      if (this.coefficients[k] !== 0) {
        if (this.powers[k] === 0) {
          str = maybeToPrecision(this.coefficients[k], precision);
        } else if (this.powers[k] === 1) {
          str = `${maybeToPrecision(this.coefficients[k], precision) + times}x`;
        } else {
          str = `${maybeToPrecision(this.coefficients[k], precision) + times}x${sup}${this.powers[k]}${closeSup}`;
        }
        if (this.coefficients[k] > 0 && k !== this.coefficients.length - 1) {
          str = ` + ${str}`;
        } else if (k !== this.coefficients.length - 1) {
          str = ` ${str}`;
        }
      }
      fn = str + fn;
    }
    if (fn.startsWith('+')) {
      fn = fn.slice(1);
    }
    return `f(x) = ${fn}`;
  }
  static load(json) {
    if (json.name !== 'polynomialRegression') {
      throw new TypeError('not a polynomial regression model');
    }
    // @ts-expect-error internal use only
    return new PolynomialRegression(true, json);
  }
}
/**
 * Perform a polynomial regression on the given data set.
 * This is an internal function.
 * @param x - independent or explanatory variable
 * @param y - dependent or response variable
 * @param degree - degree of the polynomial regression
 * @param options.interceptAtZero - force the polynomial regression so that $f(0) = 0$
 * @param options
 */
function regress(x, y, degree, options = {}) {
  const n = x.length;
  let {
    interceptAtZero = false
  } = options;
  let powers = [];
  if (Array.isArray(degree)) {
    powers = degree;
    interceptAtZero = false; //must be false in this case
  } else if (typeof degree === 'number') {
    if (interceptAtZero) {
      powers = new Array(degree);
      for (let k = 0; k < degree; k++) {
        powers[k] = k + 1;
      }
    } else {
      powers = new Array(degree + 1);
      for (let k = 0; k <= degree; k++) {
        powers[k] = k;
      }
    }
  }
  const nCoefficients = powers.length; //1 per power, in any case.
  const F = new Matrix(n, nCoefficients);
  const Y = new Matrix([y]);
  for (let k = 0; k < nCoefficients; k++) {
    for (let i = 0; i < n; i++) {
      if (powers[k] === 0) {
        F.set(i, k, 1);
      } else {
        F.set(i, k, x[i] ** powers[k]);
      }
    }
  }
  const FT = new MatrixTransposeView(F);
  const A = FT.mmul(F);
  const B = FT.mmul(new MatrixTransposeView(Y));
  return {
    coefficients: solve(A, B).to1DArray(),
    degree: Math.max(...powers),
    powers
  };
}

/**
 * Iterative regression-based baseline correction
 * @param {Array<number>} x - Independent axis variable
 * @param {Array<number>} y - Dependent axis variable
 * @param {object} [options] - Options object
 * @param {number} [options.maxIterations = 100] - Maximum number of allowed iterations
 * @param {function} [options.Regression = PolynomialRegression] - Regression class with a predict method
 * @param {*} [options.regressionOptions] - Options for regressionFunction
 * @param {number} [options.tolerance = 0.001] - Convergence error tolerance
 * @return {{corrected: Array<number>, delta: number, iteration: number, baseline: Array<number>}}
 */
function baselineCorrectionRegression(x, y, options = {}) {
  let {
    maxIterations = 100,
    Regression = PolynomialRegression,
    regressionOptions,
    tolerance = 0.001
  } = options;
  if (!regressionOptions && Regression === PolynomialRegression) {
    regressionOptions = 3;
  }
  let baseline = y.slice();
  let fitting = y.slice();
  let oldFitting = y;
  let iteration = 0;
  let delta;
  let regression;
  while (iteration < maxIterations) {
    // Calculate the fitting result
    regression = new Regression(x, baseline, regressionOptions);
    delta = 0;
    for (let i = 0; i < baseline.length; i++) {
      fitting[i] = regression.predict(x[i]);
      if (baseline[i] > fitting[i]) {
        baseline[i] = fitting[i];
      }
      delta += Math.abs((fitting[i] - oldFitting[i]) / oldFitting[i]);
    }

    // Stop criterion
    if (delta < tolerance) {
      break;
    } else {
      oldFitting = fitting.slice();
      iteration++;
    }
  }

  // removes baseline
  let corrected = new Array(baseline.length);
  for (let j = 0; j < baseline.length; j++) {
    corrected[j] = y[j] - baseline[j];
  }
  return {
    corrected,
    delta,
    iteration,
    baseline,
    regression
  };
}

/**
 * Iterative polynomial fitting [1]
 *
 * Implementation based on ml-baseline-correction-regression
 *
 * References:
 * [1] Gan, F.; Ruan, G.; Mo, J.
 * Baseline Correction by Improved Iterative Polynomial Fitting with Automatic Threshold.
 *  Chemometrics and Intelligent Laboratory Systems 2006, 82 (1), 59–65.
 * https://doi.org/10.1016/j.chemolab.2005.08.009.
 * @export
 * @param {Array<number>} ys
 * @param {object} [options] - Options object
 * @param {Array<number>} [options.x] Optional, Independent axis variable. If not specified, we use a linear grid
 * @param {Object} [options.regression]
 * @param {number} [options.regression.maxIterations = 100] - Maximum number of allowed iterations
 * @param {Object} [options.regression]
 * @param {function} [options.regression.Regression = PolynomialRegression] - Regression class with a predict method
 * @param {Object} [options.regression.regressionOptions] - Options for regressionFunction
 * @param {number} [options.regression.tolerance = 0.001] - Convergence error tolerance
 * @returns {BaselineOutput}
 */
function iterativePolynomialBaseline$1(ys, options = {}) {
  const numberPoints = ys.length;
  let {
    x,
    regressionOptions
  } = options;
  if (!x) {
    x = sequentialFill({
      from: 0,
      to: numberPoints - 1,
      size: numberPoints
    });
  }
  let output = baselineCorrectionRegression(x, ys, regressionOptions);
  return {
    baseline: output.baseline,
    correctedSpectrum: output.corrected
  };
}

/**

 *
 * @export
 * @param {Array<number>} ys
 * @param {Object} [options={}]
 * @param {number} [options.window] rolling window size, defaults to 10% of the length of the spectrum
 * @param {string} [options.padding.size=window-1] none, value, circular, duplicate
 * @param {string} [options.padding.algorithm='duplicate'] none, value, circular, duplicate
 * @param {number} [options.padding.value=0] value to use for padding (if algorithm='value')
 * @returns {BaselineOutput}
 */
function rollingAverageBaseline$1(ys, options = {}) {
  let window = Math.max(Math.round(ys.length * 0.1), 2);
  let defaults = {
    window,
    padding: {
      size: window - 1,
      algorithm: 'duplicate',
      value: 0
    }
  };
  let actualOptions = {
    ...defaults,
    ...options
  };
  let baseline = xRollingAverage(ys, actualOptions);
  let corrected = new Float64Array(ys.length);
  for (let i = 0; i < corrected.length; i++) {
    corrected[i] = ys[i] - baseline[i];
  }
  return {
    baseline,
    correctedSpectrum: corrected
  };
}

function rollingBall(spectrum, options = {}) {
  if (!isAnyArray$1(spectrum)) {
    throw new Error('Spectrum must be an array');
  }
  if (spectrum.length === 0) {
    throw new TypeError('Spectrum must not be empty');
  }
  const numberPoints = spectrum.length;
  const maxima = new Float64Array(numberPoints);
  const minima = new Float64Array(numberPoints);
  const baseline = new Float64Array(numberPoints);
  // windowM 4 percent of spectrum length
  // windowS 8 percent of spectrum length
  const {
    windowM = Math.round(numberPoints * 0.04),
    windowS = Math.round(numberPoints * 0.08)
  } = options;
  // fi(1) in original paper
  for (let i = 0; i < spectrum.length; i++) {
    const windowLeft = Math.max(0, i - windowM);
    const windowRight = Math.min(i + windowM + 1, spectrum.length);
    minima[i] = xMinValue(spectrum, {
      fromIndex: windowLeft,
      toIndex: windowRight
    });
  }
  // fi in original paper
  for (let i = 0; i < minima.length; i++) {
    const windowLeft = Math.max(0, i - windowM);
    const windowRight = Math.min(i + windowM + 1, minima.length);
    maxima[i] = xMaxValue(minima, {
      fromIndex: windowLeft,
      toIndex: windowRight
    });
  }
  for (let i = 0; i < minima.length; i++) {
    const windowLeft = Math.max(0, i - windowS);
    const windowRight = Math.min(i + windowS + 1, maxima.length);
    baseline[i] = xMean(maxima.subarray(windowLeft, windowRight));
  }
  return baseline;
}

/**
 * Rolling ball baseline correction algorithm.
 * From the abstract of (1):
 * "This algorithm behaves equivalently to traditional polynomial backgrounds in simple spectra,
 * [...] and is considerably more robust for multiple overlapping peaks, rapidly varying background [...]
 *
 * The baseline is the trace one gets by rolling a ball below a spectrum. Algorithm has three steps:
 * Finding the minima in each window, find maxima among minima and then smooth over them by averaging.
 *
 * Algorithm described in (1), but in the implementation here the window width does not change.
 *
 * Reference:
 * (1) Kneen, M. A.; Annegarn, H. J.
 *     Algorithm for Fitting XRF, SEM and PIXE X-Ray Spectra Backgrounds.
 *     Nuclear Instruments and Methods in Physics Research Section B: Beam Interactions with Materials and Atoms 1996, 109–110, 209–213.
 *     https://doi.org/10.1016/0168-583X(95)00908-6.
 * (2) Kristian Hovde Liland, Bjørn-Helge Mevik, Roberto Canteri: baseline.
 *     https://cran.r-project.org/web/packages/baseline/index.html
 *
 * @export
 * @param {Array<number>} ys
 * @param {Object} [options={}]
 * @param {Number} [options.windowM] - width of local window for minimization/maximization, defaults to 4% of the spectrum length
 * @param {Number} [options.windowS] - width of local window for smoothing, defaults to 8% of the specturm length
 * @returns {BaselineOutput}
 */
function rollingBallBaseline$1(ys, options = {}) {
  const baseline = rollingBall(ys, options);
  let corrected = new Float64Array(ys.length);
  for (let i = 0; i < corrected.length; i++) {
    corrected[i] = ys[i] - baseline[i];
  }
  return {
    baseline,
    correctedSpectrum: corrected
  };
}

/**

 *
 * @export
 * @param {Array<number>} ys
 * @param {Object} [options={}]
 * @param {number} [options.window] rolling window size, defaults to 10% of the length of the spectrum
 * @param {string} [options.padding.size=window-1] none, value, circular, duplicate
 * @param {string} [options.padding.algorithm='duplicate'] none, value, circular, duplicate
 * @param {number} [options.padding.value=0] value to use for padding (if algorithm='value')
 * @returns {BaselineOutput}
 */
function rollingMedianBaseline$1(ys, options = {}) {
  let window = Math.max(Math.round(ys.length * 0.1), 2);
  let defaults = {
    window,
    padding: {
      size: window - 1,
      algorithm: 'duplicate',
      value: 0
    }
  };
  let actualOptions = {
    ...defaults,
    ...options
  };
  let baseline = xRollingMedian(ys, actualOptions);
  let corrected = new Float64Array(ys.length);
  for (let i = 0; i < corrected.length; i++) {
    corrected[i] = ys[i] - baseline[i];
  }
  return {
    baseline,
    correctedSpectrum: corrected
  };
}

//@ts-expect-error no type definition for baselines
/**
 * @param data
 */
function airPLSBaseline(data) {
  data.y = airPLSBaseline$1(data.y).correctedSpectrum;
  return {
    data
  };
}

//@ts-expect-error no type definition for baselines
/**
 * @param data
 */
function iterativePolynomialBaseline(data) {
  data.y = iterativePolynomialBaseline$1(data.y).correctedSpectrum;
  return {
    data
  };
}

//@ts-expect-error no type definition for baselines
/**
 * @param data
 */
function rollingAverageBaseline(data) {
  data.y = rollingAverageBaseline$1(data.y).correctedSpectrum;
  return {
    data
  };
}

//@ts-expect-error no type definition for baselines
/**
 * @param data
 */
function rollingBallBaseline(data) {
  data.y = rollingBallBaseline$1(data.y).correctedSpectrum;
  return {
    data
  };
}

//@ts-expect-error no type definition for baselines
/**
 * @param data
 */
function rollingMedianBaseline(data) {
  data.y = rollingMedianBaseline$1(data.y).correctedSpectrum;
  return {
    data
  };
}

/**
 * Apply Savitzky Golay algorithm
 * @param [ys] Array of y values
 * @param [xs] Array of X or deltaX
 * @return  Array containing the new ys (same length)
 */
function sgg(ys, xs, options = {}) {
  const {
    windowSize = 9,
    derivative = 0,
    polynomial = 3
  } = options;
  if (windowSize % 2 === 0 || windowSize < 5 || !Number.isInteger(windowSize)) {
    throw new RangeError('Invalid window size (should be odd and at least 5 integer number)');
  }
  if (!isAnyArray$1(ys)) {
    throw new TypeError('Y values must be an array');
  }
  if (typeof xs === 'undefined') {
    throw new TypeError('X must be defined');
  }
  if (windowSize > ys.length) {
    throw new RangeError(`Window size is higher than the data length ${windowSize}>${ys.length}`);
  }
  if (derivative < 0 || !Number.isInteger(derivative)) {
    throw new RangeError('Derivative should be a positive integer');
  }
  if (polynomial < 1 || !Number.isInteger(polynomial)) {
    throw new RangeError('Polynomial should be a positive integer');
  }
  if (polynomial >= 6) {
    // eslint-disable-next-line no-console
    console.warn('You should not use polynomial grade higher than 5 if you are' + ' not sure that your data arises from such a model. Possible polynomial oscillation problems');
  }
  const half = Math.floor(windowSize / 2);
  const np = ys.length;
  const ans = new Float64Array(np);
  const weights = fullWeights(windowSize, polynomial, derivative);
  let hs = 0;
  let constantH = true;
  if (isAnyArray$1(xs)) {
    constantH = false;
  } else {
    hs = xs ** derivative;
  }
  //For the borders
  for (let i = 0; i < half; i++) {
    const wg1 = weights[half - i - 1];
    const wg2 = weights[half + i + 1];
    let d1 = 0;
    let d2 = 0;
    for (let l = 0; l < windowSize; l++) {
      d1 += wg1[l] * ys[l];
      d2 += wg2[l] * ys[np - windowSize + l];
    }
    if (constantH) {
      ans[half - i - 1] = d1 / hs;
      ans[np - half + i] = d2 / hs;
    } else {
      hs = getHs(xs, half - i - 1, half, derivative);
      ans[half - i - 1] = d1 / hs;
      hs = getHs(xs, np - half + i, half, derivative);
      ans[np - half + i] = d2 / hs;
    }
  }
  //For the internal points
  const wg = weights[half];
  for (let i = windowSize; i <= np; i++) {
    let d = 0;
    for (let l = 0; l < windowSize; l++) d += wg[l] * ys[l + i - windowSize];
    if (!constantH) {
      hs = getHs(xs, i - half - 1, half, derivative);
    }
    ans[i - half - 1] = d / hs;
  }
  return ans;
}
function getHs(h, center, half, derivative) {
  let hs = 0;
  let count = 0;
  for (let i = center - half; i < center + half; i++) {
    if (i >= 0 && i < h.length - 1) {
      hs += h[i + 1] - h[i];
      count++;
    }
  }
  return (hs / count) ** derivative;
}
function gramPoly(i, m, k, s) {
  let Grampoly = 0;
  if (k > 0) {
    Grampoly = (4 * k - 2) / (k * (2 * m - k + 1)) * (i * gramPoly(i, m, k - 1, s) + s * gramPoly(i, m, k - 1, s - 1)) - (k - 1) * (2 * m + k) / (k * (2 * m - k + 1)) * gramPoly(i, m, k - 2, s);
  } else if (k === 0 && s === 0) {
    Grampoly = 1;
  } else {
    Grampoly = 0;
  }
  return Grampoly;
}
function genFact(a, b) {
  let gf = 1;
  if (a >= b) {
    for (let j = a - b + 1; j <= a; j++) {
      gf *= j;
    }
  }
  return gf;
}
function weight(i, t, m, n, s) {
  let sum = 0;
  for (let k = 0; k <= n; k++) {
    sum += (2 * k + 1) * (genFact(2 * m, k) / genFact(2 * m + k + 1, k + 1)) * gramPoly(i, m, k, 0) * gramPoly(t, m, k, s);
  }
  return sum;
}
/**
 * @private
 * @param m  Number of points
 * @param n  Polynomial grade
 * @param s  Derivative
 */
function fullWeights(m, n, s) {
  const weights = new Array(m);
  const np = Math.floor(m / 2);
  for (let t = -np; t <= np; t++) {
    weights[t + np] = new Float64Array(m);
    for (let j = -np; j <= np; j++) {
      weights[t + np][j + np] = weight(j, t, np, n, s);
    }
  }
  return weights;
}

/**
 * Calculate the first derivative using Savitzky–Golay filter.
 * @param data
 * @param options
 */
function firstDerivative$1(data, options = {}) {
  const {
    x,
    y
  } = data;
  return {
    data: {
      x,
      y: sgg(y, x, {
        ...options,
        derivative: 1
      })
    }
  };
}

/**
 * Calculate the second derivative using Savitzky–Golay filter.
 * @param data
 * @param options
 */
function secondDerivative$1(data, options = {}) {
  const {
    x,
    y
  } = data;
  return {
    data: {
      x,
      y: sgg(y, x, {
        ...options,
        derivative: 2
      })
    }
  };
}

/**
 * Calculate the third derivative using Savitzky–Golay filter.
 * @param data
 * @param options
 */
function thirdDerivative(data, options = {}) {
  const {
    x,
    y
  } = data;
  return {
    data: {
      x,
      y: sgg(y, x, {
        ...options,
        derivative: 3
      })
    }
  };
}

/**
 * Apply the Savitzky Golay Generalized Filter
 * @param data
 * @param options
 */
function savitzkyGolay(data, options = {}) {
  const {
    x,
    y
  } = data;
  return {
    data: {
      x,
      y: sgg(y, x, options)
    }
  };
}

/**
 * Ensure X values are strictly monotonic increasing
 * http://www-groups.mcs.st-andrews.ac.uk/~john/analysis/Lectures/L8.html
 * @param data
 */
function ensureGrowing(data) {
  return {
    data: xyEnsureGrowingX(data)
  };
}

/**
 * Ensure X values are strictly monotonic increasing
 * http://www-groups.mcs.st-andrews.ac.uk/~john/analysis/Lectures/L8.html
 * @param data
 */
function reverseIfNeeded(data) {
  return {
    data: xyGrowingX(data)
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function equallySpaced(data, options = {}) {
  return {
    data: xyEquallySpaced(data, options)
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function filterX(data, options = {}) {
  return {
    data: xyFilterX(data, options)
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function setMaxX(data, options = {}) {
  const {
    max = 1
  } = options;
  const existingMax = xMaxValue(data.x);
  if (existingMax === max) {
    return {
      data
    };
  }
  return {
    data: {
      x: xAdd(data.x, max - existingMax),
      y: data.y
    }
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function setMinX(data, options = {}) {
  const {
    min = 0
  } = options;
  const existingMin = xMinValue(data.x);
  if (existingMin === min) {
    return {
      data
    };
  }
  return {
    data: {
      x: xAdd(data.x, min - existingMin),
      y: data.y
    }
  };
}

function getMinMaxIntervalsDy(y, x, dY, dX) {
  let lastMax = null;
  let lastMin = null;
  const intervalL = [];
  const intervalR = [];
  for (let i = 1; i < y.length - 1; ++i) {
    if (dY[i] < dY[i - 1] && dY[i] <= dY[i + 1] || dY[i] <= dY[i - 1] && dY[i] < dY[i + 1]) {
      lastMin = {
        x: x[i],
        index: i
      };
      if (dX > 0 && lastMax !== null) {
        intervalL.push(lastMax);
        intervalR.push(lastMin);
      }
    }
    // Maximum in first derivative
    if (dY[i] >= dY[i - 1] && dY[i] > dY[i + 1] || dY[i] > dY[i - 1] && dY[i] >= dY[i + 1]) {
      lastMax = {
        x: x[i],
        index: i
      };
      if (dX < 0 && lastMin !== null) {
        intervalL.push(lastMax);
        intervalR.push(lastMin);
      }
    }
  }
  return {
    intervalL,
    intervalR
  };
}

function tryMatchOneIntervalWithMinData(options) {
  const {
    x,
    lastK,
    minData,
    yThreshold,
    intervalWidth,
    intervalCenter,
    yData
  } = options;
  let minDistance = Number.POSITIVE_INFINITY;
  let possible = -1;
  let newLastIndex = lastK;
  for (let k = newLastIndex + 1; k < minData.length; k++) {
    const centerIndex = minData[k];
    if (yData[centerIndex] <= yThreshold) {
      continue;
    }
    const deltaX = x[centerIndex];
    const currentDistance = Math.abs(deltaX - intervalCenter);
    if (currentDistance < intervalWidth) {
      if (currentDistance < minDistance) {
        possible = k;
      }
      newLastIndex = k;
    }
    if (currentDistance >= minDistance) break;
    minDistance = currentDistance;
  }
  return {
    lastIndex: newLastIndex,
    possible
  };
}

function autoAlgorithm(input) {
  const {
    x,
    y,
    yData,
    dY,
    ddY,
    dX,
    yThreshold
  } = input;
  const minddY = [];
  const crossDy = [];
  const {
    intervalL,
    intervalR
  } = getMinMaxIntervalsDy(y, x, dY, dX);
  for (let i = 1; i < y.length - 1; ++i) {
    if (dY[i] < 0 && dY[i + 1] > 0 || dY[i] > 0 && dY[i + 1] < 0) {
      // push the index of the element closer to zero
      crossDy.push(Math.abs(dY[i]) < Math.abs(dY[i + 1]) ? i : i + 1);
    }
    // Handle exact zero
    if (dY[i] === 0 && dY[i] < Math.abs(dY[i + 1]) && dY[i] < Math.abs(dY[i - 1])) {
      crossDy.push(i);
    }
    // Minimum in second derivative
    if (ddY[i] < ddY[i - 1] && ddY[i] < ddY[i + 1]) {
      minddY.push(i);
    }
  }
  const peaks = [];
  let [lastK, lastJ] = [-1, -1];
  for (let i = 0; i < intervalL.length; i++) {
    const intervalWidth = (intervalR[i].x - intervalL[i].x) / 2;
    const intervalCenter = (intervalR[i].x + intervalL[i].x) / 2;
    let yIndex = -1;
    let match = tryMatchOneIntervalWithMinData({
      x,
      yData,
      lastK,
      yThreshold,
      intervalWidth,
      intervalCenter,
      minData: crossDy
    });
    lastK = match.lastIndex;
    if (match.possible !== -1) {
      yIndex = crossDy[match.possible];
    } else {
      match = tryMatchOneIntervalWithMinData({
        x,
        yData,
        yThreshold,
        lastK: lastJ,
        intervalWidth,
        intervalCenter,
        minData: minddY
      });
      if (match.possible !== -1) {
        yIndex = minddY[match.possible];
      }
      lastJ = match.lastIndex;
    }
    if (yIndex !== -1) {
      const width = Math.abs(intervalR[i].x - intervalL[i].x);
      peaks.push({
        id: crypto.randomUUID(),
        x: x[yIndex],
        y: y[yIndex],
        width,
        index: yIndex,
        ddY: ddY[yIndex],
        inflectionPoints: {
          from: intervalL[i],
          to: intervalR[i]
        }
      });
    }
  }
  return peaks;
}

function getPeakFromIntervals(options) {
  let lastK = -1;
  const peaks = [];
  const {
    x,
    ddY,
    yData,
    yThreshold,
    intervalR,
    intervalL,
    minData
  } = options;
  for (let i = 0; i < intervalL.length; i++) {
    const intervalWidth = (intervalR[i].x - intervalL[i].x) / 2;
    const intervalCenter = (intervalR[i].x + intervalL[i].x) / 2;
    const {
      possible = -1,
      lastIndex
    } = tryMatchOneIntervalWithMinData({
      x,
      lastK,
      minData,
      yThreshold,
      intervalWidth,
      intervalCenter,
      yData
    });
    if (possible !== -1) {
      const centerIndex = minData[possible];
      const width = Math.abs(intervalR[i].x - intervalL[i].x);
      peaks.push({
        id: crypto.randomUUID(),
        x: x[centerIndex],
        y: yData[centerIndex],
        width,
        index: centerIndex,
        ddY: ddY[centerIndex],
        inflectionPoints: {
          from: intervalL[i],
          to: intervalR[i]
        }
      });
    }
    lastK = lastIndex;
  }
  return peaks;
}

/**
 * Finds the indices where the first derivative crosses zero (sign change),
 * which are potential peak positions. This function does not detect zero-crossings
 * in regions with consecutive zero values in the derivative (flat regions).
 *
 * @param input - Object containing the y values and their first derivative (dY).
 * @returns Array of indices where the first derivative crosses zero (excluding consecutive zeros).
 */
function xGetCrossZeroPoints(input) {
  const {
    y,
    dY
  } = input;
  const crossDy = [];
  for (let i = 1; i < y.length - 1; ++i) {
    if (isLessAndGreaterThanZero(dY[i], dY[i + 1])) {
      // push the index of the element closer to zero
      crossDy.push(Math.abs(dY[i]) < Math.abs(dY[i + 1]) ? i : i + 1);
    } else if (
    // Handle exact zero
    dY[i] === 0 && isLessAndGreaterThanZero(dY[i - 1], dY[i + 1])) {
      crossDy.push(i);
    }
  }
  return crossDy;
}
function isLessAndGreaterThanZero(back, next) {
  return back < 0 && next > 0 || back > 0 && next < 0;
}

function firstDerivative(input) {
  const {
    y,
    x,
    dY,
    dX,
    yData,
    yThreshold,
    ddY
  } = input;
  const crossDy = xGetCrossZeroPoints(input);
  const {
    intervalL,
    intervalR
  } = getMinMaxIntervalsDy(y, x, dY, dX);
  return getPeakFromIntervals({
    minData: crossDy,
    intervalL,
    intervalR,
    x,
    yData,
    yThreshold,
    ddY
  });
}

function secondDerivative(input) {
  const {
    x,
    y,
    yData,
    dY,
    ddY,
    dX,
    yThreshold
  } = input;
  const minddY = [];
  const {
    intervalL,
    intervalR
  } = getMinMaxIntervalsDy(y, x, dY, dX);
  // By the intermediate value theorem We cannot find 2 consecutive maximum or minimum
  for (let i = 1; i < y.length - 1; ++i) {
    // Minimum in second derivative
    if (ddY[i] < ddY[i - 1] && ddY[i] < ddY[i + 1]) {
      minddY.push(i);
    }
  }
  return getPeakFromIntervals({
    minData: minddY,
    intervalL,
    intervalR,
    x,
    yData,
    yThreshold,
    ddY
  });
}

/**
 * Correction of the x and y coordinates using a quadratic optimizations with the peak and its 3 closest neighbors to determine the true x,y values of the peak.
 * This process is done in place and is very fast.
 * @param data
 * @param peaks
 */
function optimizeTop(data, peaks) {
  const {
    x,
    y
  } = data;
  for (const peak of peaks) {
    let currentIndex = peak.index;
    // The detected peak could be moved 1 or 2 units to left or right.
    if (y[currentIndex - 1] >= y[currentIndex - 2] && y[currentIndex - 1] >= y[currentIndex]) {
      currentIndex--;
    } else if (y[currentIndex + 1] >= y[currentIndex] && y[currentIndex + 1] >= y[currentIndex + 2]) {
      currentIndex++;
    } else if (y[currentIndex - 2] >= y[currentIndex - 3] && y[currentIndex - 2] >= y[currentIndex - 1]) {
      currentIndex -= 2;
    } else if (y[currentIndex + 2] >= y[currentIndex + 1] && y[currentIndex + 2] >= y[currentIndex + 3]) {
      currentIndex += 2;
    }
    // interpolation to a sin() function
    if (y[currentIndex - 1] > 0 && y[currentIndex + 1] > 0 && y[currentIndex] >= y[currentIndex - 1] && y[currentIndex] >= y[currentIndex + 1] && (y[currentIndex] !== y[currentIndex - 1] || y[currentIndex] !== y[currentIndex + 1])) {
      const alpha = 20 * Math.log10(y[currentIndex - 1]);
      const beta = 20 * Math.log10(y[currentIndex]);
      const gamma = 20 * Math.log10(y[currentIndex + 1]);
      const p = 0.5 * (alpha - gamma) / (alpha - 2 * beta + gamma);
      const xCurrent = x[currentIndex];
      const xPrevious = x[currentIndex - 1];
      peak.x = xCurrent + (xCurrent - xPrevious) * p;
      peak.y = y[currentIndex] - 0.25 * (y[currentIndex - 1] - y[currentIndex + 1]) * p;
    }
  }
}

/**
 * Global spectra deconvolution
 * @param  data - Object data with x and y arrays. Values in x has to be growing
 * @param options
 * @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.
 */
function gsd(data, options = {}) {
  let {
    noiseLevel
  } = options;
  const {
    sgOptions = {
      windowSize: 9,
      polynomial: 3
    },
    smoothY = false,
    maxCriteria = true,
    minMaxRatio = 0.00025,
    realTopDetection = false,
    peakDetectionAlgorithm = 'second'
  } = options;
  const {
    x
  } = data;
  let {
    y
  } = data;
  if (xIsMonotonic(x) !== 1) {
    throw new Error('GSD only accepts monotone increasing x values');
  }
  //rescale;
  y = y.slice();
  // If the max difference between delta x is less than 5%, then,
  // we can assume it to be equally spaced variable
  const isEquallySpaced = xIsEquallySpaced(x);
  if (noiseLevel === undefined) {
    if (isEquallySpaced) {
      const noiseInfo = xNoiseStandardDeviation(y);
      if (maxCriteria) {
        noiseLevel = noiseInfo.median + 1.5 * noiseInfo.sd;
      } else {
        noiseLevel = -noiseInfo.median + 1.5 * noiseInfo.sd;
      }
    } else {
      noiseLevel = 0;
    }
  } else if (!maxCriteria) {
    noiseLevel *= -1;
  }
  if (!maxCriteria) {
    for (let i = 0; i < y.length; i++) {
      y[i] *= -1;
    }
  }
  if (noiseLevel !== undefined) {
    for (let i = 0; i < y.length; i++) {
      if (y[i] < noiseLevel) {
        y[i] = noiseLevel;
      }
    }
  }
  const xValue = isEquallySpaced ? x[1] - x[0] : x;
  const yData = smoothY ? sgg(y, xValue, {
    ...sgOptions,
    derivative: 0
  }) : y;
  const {
    min: minY,
    max: maxY
  } = xMinMaxValues(yData);
  if (minY > maxY || minY === maxY) return [];
  const dY = sgg(y, xValue, {
    ...sgOptions,
    derivative: 1
  });
  const ddY = sgg(y, xValue, {
    ...sgOptions,
    derivative: 2
  });
  const yThreshold = Math.max(noiseLevel, minY + (maxY - minY) * minMaxRatio);
  const dX = x[1] - x[0];
  const peakData = {
    x,
    y,
    yData,
    dY,
    ddY,
    dX,
    yThreshold
  };
  let peaks = [];
  if (peakDetectionAlgorithm === 'first') {
    peaks = firstDerivative(peakData);
  } else if (peakDetectionAlgorithm === 'second') {
    peaks = secondDerivative(peakData);
  } else {
    peaks = autoAlgorithm(peakData);
  }
  if (realTopDetection) {
    optimizeTop({
      x,
      y: yData
    }, peaks);
  }
  peaks.forEach(peak => {
    if (!maxCriteria) {
      peak.y *= -1;
      peak.ddY = peak.ddY * -1;
    }
  });
  peaks.sort((a, b) => {
    return a.x - b.x;
  });
  return peaks;
}

const GAUSSIAN_EXP_FACTOR = -4 * Math.LN2;
const ROOT_PI_OVER_LN2 = Math.sqrt(Math.PI / Math.LN2);
const ROOT_THREE = Math.sqrt(3);
const ROOT_2LN2 = Math.sqrt(2 * Math.LN2);
const ROOT_2LN2_MINUS_ONE = Math.sqrt(2 * Math.LN2) - 1;

// https://en.wikipedia.org/wiki/Error_function#Inverse_functions
// This code yields to a good approximation
// If needed a better implementation using polynomial can be found on https://en.wikipedia.org/wiki/Error_function#Inverse_functions
function erfinv(x) {
  let a = 0.147;
  if (x === 0) return 0;
  let ln1MinusXSqrd = Math.log(1 - x * x);
  let lnEtcBy2Plus2 = ln1MinusXSqrd / 2 + 2 / (Math.PI * a);
  let firstSqrt = Math.sqrt(lnEtcBy2Plus2 ** 2 - ln1MinusXSqrd / a);
  let secondSqrt = Math.sqrt(firstSqrt - lnEtcBy2Plus2);
  return secondSqrt * (x > 0 ? 1 : -1);
}

class Gaussian {
  constructor(options = {}) {
    const {
      fwhm = 500,
      sd
    } = options;
    this.fwhm = sd ? gaussianWidthToFWHM(2 * sd) : fwhm;
  }
  fwhmToWidth(fwhm = this.fwhm) {
    return gaussianFwhmToWidth(fwhm);
  }
  widthToFWHM(width) {
    return gaussianWidthToFWHM(width);
  }
  fct(x) {
    return gaussianFct(x, this.fwhm);
  }
  getArea(height = calculateGaussianHeight({
    fwhm: this.fwhm
  })) {
    return getGaussianArea({
      fwhm: this.fwhm,
      height
    });
  }
  getFactor(area) {
    return getGaussianFactor(area);
  }
  getData(options = {}) {
    return getGaussianData(this, options);
  }
  calculateHeight(area = 1) {
    return calculateGaussianHeight({
      fwhm: this.fwhm,
      area
    });
  }
  getParameters() {
    return ['fwhm'];
  }
}
function calculateGaussianHeight(options) {
  let {
    fwhm = 500,
    area = 1,
    sd
  } = options;
  if (sd) fwhm = gaussianWidthToFWHM(2 * sd);
  return 2 * area / ROOT_PI_OVER_LN2 / fwhm;
}
/**
 * Calculate the height of the gaussian function of a specific width (fwhm) at a speicifc
 * x position (the gaussian is centered on x=0)
 * @param x
 * @param fwhm
 * @returns y
 */
function gaussianFct(x, fwhm) {
  return Math.exp(GAUSSIAN_EXP_FACTOR * Math.pow(x / fwhm, 2));
}
function gaussianWidthToFWHM(width) {
  return width * ROOT_2LN2;
}
function gaussianFwhmToWidth(fwhm) {
  return fwhm / ROOT_2LN2;
}
function getGaussianArea(options) {
  let {
    fwhm = 500,
    sd,
    height = 1
  } = options;
  if (sd) fwhm = gaussianWidthToFWHM(2 * sd);
  return height * ROOT_PI_OVER_LN2 * fwhm / 2;
}
function getGaussianFactor(area = 0.9999) {
  return Math.sqrt(2) * erfinv(area);
}
function getGaussianData(shape = {}, options = {}) {
  let {
    fwhm = 500,
    sd
  } = shape;
  if (sd) fwhm = gaussianWidthToFWHM(2 * sd);
  let {
    length,
    factor = getGaussianFactor(),
    height = calculateGaussianHeight({
      fwhm
    })
  } = options;
  if (!length) {
    length = Math.min(Math.ceil(fwhm * factor), Math.pow(2, 25) - 1);
    if (length % 2 === 0) length++;
  }
  const center = (length - 1) / 2;
  const data = new Float64Array(length);
  for (let i = 0; i <= center; i++) {
    data[i] = gaussianFct(i - center, fwhm) * height;
    data[length - 1 - i] = data[i];
  }
  return data;
}

class Lorentzian {
  constructor(options = {}) {
    const {
      fwhm = 500
    } = options;
    this.fwhm = fwhm;
  }
  fwhmToWidth(fwhm = this.fwhm) {
    return lorentzianFwhmToWidth(fwhm);
  }
  widthToFWHM(width) {
    return lorentzianWidthToFWHM(width);
  }
  fct(x) {
    return lorentzianFct(x, this.fwhm);
  }
  getArea(height = 1) {
    return getLorentzianArea({
      fwhm: this.fwhm,
      height
    });
  }
  getFactor(area) {
    return getLorentzianFactor(area);
  }
  getData(options = {}) {
    return getLorentzianData(this, options);
  }
  calculateHeight(area = 1) {
    return calculateLorentzianHeight({
      fwhm: this.fwhm,
      area
    });
  }
  getParameters() {
    return ['fwhm'];
  }
}
const calculateLorentzianHeight = ({
  fwhm = 1,
  area = 1
}) => {
  return 2 * area / Math.PI / fwhm;
};
const getLorentzianArea = options => {
  const {
    fwhm = 500,
    height = 1
  } = options;
  return height * Math.PI * fwhm / 2;
};
const lorentzianFct = (x, fwhm) => {
  return fwhm ** 2 / (4 * x ** 2 + fwhm ** 2);
};
const lorentzianWidthToFWHM = width => {
  return width * ROOT_THREE;
};
const lorentzianFwhmToWidth = fwhm => {
  return fwhm / ROOT_THREE;
};
const getLorentzianFactor = (area = 0.9999) => {
  if (area >= 1) {
    throw new Error('area should be (0 - 1)');
  }
  const halfResidual = (1 - area) * 0.5;
  const quantileFunction = p => Math.tan(Math.PI * (p - 0.5));
  return (quantileFunction(1 - halfResidual) - quantileFunction(halfResidual)) / 2;
};
const getLorentzianData = (shape = {}, options = {}) => {
  let {
    fwhm = 500
  } = shape;
  let {
    length,
    factor = getLorentzianFactor(),
    height = calculateLorentzianHeight({
      fwhm,
      area: 1
    })
  } = options;
  if (!length) {
    length = Math.min(Math.ceil(fwhm * factor), Math.pow(2, 25) - 1);
    if (length % 2 === 0) length++;
  }
  const center = (length - 1) / 2;
  const data = new Float64Array(length);
  for (let i = 0; i <= center; i++) {
    data[i] = lorentzianFct(i - center, fwhm) * height;
    data[length - 1 - i] = data[i];
  }
  return data;
};

class LorentzianDispersive {
  constructor(options = {}) {
    const {
      fwhm = 500
    } = options;
    this.fwhm = fwhm;
  }
  fwhmToWidth(fwhm = this.fwhm) {
    return lorentzianFwhmToWidth(fwhm);
  }
  widthToFWHM(width) {
    return lorentzianWidthToFWHM(width);
  }
  fct(x) {
    return lorentzianDispersiveFct(x, this.fwhm);
  }
  //eslint-disable-next-line
  getArea(_height) {
    return 0;
  }
  getFactor(area) {
    return getLorentzianFactor(area);
  }
  getData(options = {}) {
    return getLorentzianDispersiveData(this, options);
  }
  calculateHeight(area = 1) {
    return calculateLorentzianHeight({
      fwhm: this.fwhm,
      area
    });
  }
  getParameters() {
    return ['fwhm'];
  }
}
const lorentzianDispersiveFct = (x, fwhm) => {
  return 2 * fwhm * x / (4 * x ** 2 + fwhm ** 2);
};
const getLorentzianDispersiveData = (shape = {}, options = {}) => {
  let {
    fwhm = 500
  } = shape;
  let {
    length,
    factor = getLorentzianFactor(),
    height = calculateLorentzianHeight({
      fwhm,
      area: 1
    })
  } = options;
  if (!length) {
    length = Math.min(Math.ceil(fwhm * factor), Math.pow(2, 25) - 1);
    if (length % 2 === 0) length++;
  }
  const center = (length - 1) / 2;
  const data = new Float64Array(length);
  for (let i = 0; i <= center; i++) {
    data[i] = lorentzianDispersiveFct(i - center, fwhm) * height;
    data[length - 1 - i] = -data[i];
  }
  return data;
};

class PseudoVoigt {
  constructor(options = {}) {
    const {
      fwhm = 500,
      mu = 0.5
    } = options;
    this.mu = mu;
    this.fwhm = fwhm;
  }
  fwhmToWidth(fwhm = this.fwhm, mu = this.mu) {
    return pseudoVoigtFwhmToWidth(fwhm, mu);
  }
  widthToFWHM(width, mu = this.mu) {
    return pseudoVoigtWidthToFWHM(width, mu);
  }
  fct(x) {
    return pseudoVoigtFct(x, this.fwhm, this.mu);
  }
  getArea(height = 1) {
    return getPseudoVoigtArea({
      fwhm: this.fwhm,
      height,
      mu: this.mu
    });
  }
  getFactor(area) {
    return getPseudoVoigtFactor(area);
  }
  getData(options = {}) {
    const {
      length,
      factor,
      height = calculatePseudoVoigtHeight({
        fwhm: this.fwhm,
        mu: this.mu,
        area: 1
      })
    } = options;
    return getPseudoVoigtData(this, {
      factor,
      length,
      height
    });
  }
  calculateHeight(area = 1) {
    return calculatePseudoVoigtHeight({
      fwhm: this.fwhm,
      mu: this.mu,
      area
    });
  }
  getParameters() {
    return ['fwhm', 'mu'];
  }
}
const calculatePseudoVoigtHeight = (options = {}) => {
  let {
    fwhm = 1,
    mu = 0.5,
    area = 1
  } = options;
  return 2 * area / (fwhm * (mu * ROOT_PI_OVER_LN2 + (1 - mu) * Math.PI));
};
const pseudoVoigtFct = (x, fwhm, mu) => {
  return (1 - mu) * lorentzianFct(x, fwhm) + mu * gaussianFct(x, fwhm);
};
const pseudoVoigtWidthToFWHM = (width, mu = 0.5) => {
  return width * (mu * ROOT_2LN2_MINUS_ONE + 1);
};
const pseudoVoigtFwhmToWidth = (fwhm, mu = 0.5) => {
  return fwhm / (mu * ROOT_2LN2_MINUS_ONE + 1);
};
const getPseudoVoigtArea = options => {
  const {
    fwhm = 500,
    height = 1,
    mu = 0.5
  } = options;
  return fwhm * height * (mu * ROOT_PI_OVER_LN2 + (1 - mu) * Math.PI) / 2;
};
const getPseudoVoigtFactor = (area = 0.9999, mu = 0.5) => {
  return mu < 1 ? getLorentzianFactor(area) : getGaussianFactor(area);
};
const getPseudoVoigtData = (shape = {}, options = {}) => {
  let {
    fwhm = 500,
    mu = 0.5
  } = shape;
  let {
    length,
    factor = getPseudoVoigtFactor(0.999, mu),
    height = calculatePseudoVoigtHeight({
      fwhm,
      mu,
      area: 1
    })
  } = options;
  if (!height) {
    height = 1 / (mu / Math.sqrt(-GAUSSIAN_EXP_FACTOR / Math.PI) * fwhm + (1 - mu) * fwhm * Math.PI / 2);
  }
  if (!length) {
    length = Math.min(Math.ceil(fwhm * factor), Math.pow(2, 25) - 1);
    if (length % 2 === 0) length++;
  }
  const center = (length - 1) / 2;
  const data = new Float64Array(length);
  for (let i = 0; i <= center; i++) {
    data[i] = pseudoVoigtFct(i - center, fwhm, mu) * height;
    data[length - 1 - i] = data[i];
  }
  return data;
};

/**
 * This shape is a linear combination of rational function (n|n+2), for n = 0 (lorentzian function) and n = 2
 * the parameter that combines those two functions is `gamma` and it is called the kurtosis parameter, it is an
 * implementation of generalized lorentzian shape published by Stanislav Sykora in the SMASH 2010. DOI:10.3247/SL3nmr10.006
 * @link http://www.ebyte.it/stan/Talk_ML_UserMeeting_SMASH_2010_GeneralizedLorentzian.html
 */
class GeneralizedLorentzian {
  constructor(options = {}) {
    const {
      fwhm = 500,
      gamma = 0.5
    } = options;
    this.fwhm = fwhm;
    this.gamma = gamma;
  }
  fwhmToWidth(fwhm = this.fwhm) {
    return generalizedLorentzianFwhmToWidth(fwhm);
  }
  widthToFWHM(width) {
    return generalizedLorentzianWidthToFWHM(width);
  }
  fct(x) {
    return generalizedLorentzianFct(x, this.fwhm, this.gamma);
  }
  getArea(height = 1) {
    return getGeneralizedLorentzianArea({
      fwhm: this.fwhm,
      height,
      gamma: this.gamma
    });
  }
  getFactor(area) {
    return getGeneralizedLorentzianFactor(area);
  }
  getData(options = {}) {
    return getGeneralizedLorentzianData(this, options);
  }
  calculateHeight(area = 1) {
    const {
      gamma,
      fwhm
    } = this;
    return calculateGeneralizedLorentzianHeight({
      fwhm,
      area,
      gamma
    });
  }
  getParameters() {
    return ['fwhm', 'gamma'];
  }
}
const calculateGeneralizedLorentzianHeight = ({
  fwhm = 1,
  gamma = 1,
  area = 1
}) => {
  return area / fwhm / (3.14159 - 0.420894 * gamma) * 2;
};
/**
 * expression of integral generated by Mathematica of the function
 */
const getGeneralizedLorentzianArea = options => {
  const {
    fwhm = 500,
    height = 1,
    gamma = 1
  } = options;
  return height * fwhm * (3.14159 - 0.420894 * gamma) / 2;
};
const generalizedLorentzianFct = (x, fwhm, gamma) => {
  const u = (2 * x / fwhm) ** 2;
  return (1 - gamma) / (1 + u) + gamma * (1 + u / 2) / (1 + u + u ** 2);
};
const generalizedLorentzianWidthToFWHM = width => {
  return width * ROOT_THREE;
};
const generalizedLorentzianFwhmToWidth = fwhm => {
  return fwhm / ROOT_THREE;
};
const getGeneralizedLorentzianFactor = (area = 0.9999) => {
  if (area >= 1) {
    throw new Error('area should be (0 - 1)');
  }
  const halfResidual = (1 - area) * 0.5;
  const quantileFunction = p => Math.tan(Math.PI * (p - 0.5));
  return (quantileFunction(1 - halfResidual) - quantileFunction(halfResidual)) / 2;
};
const getGeneralizedLorentzianData = (shape = {}, options = {}) => {
  let {
    fwhm = 500,
    gamma = 1
  } = shape;
  let {
    length,
    factor = getGeneralizedLorentzianFactor(),
    height = calculateGeneralizedLorentzianHeight({
      fwhm,
      area: 1,
      gamma
    })
  } = options;
  if (!length) {
    length = Math.min(Math.ceil(fwhm * factor), Math.pow(2, 25) - 1);
    if (length % 2 === 0) length++;
  }
  const center = (length - 1) / 2;
  const data = new Float64Array(length);
  for (let i = 0; i <= center; i++) {
    data[i] = generalizedLorentzianFct(i - center, fwhm, gamma) * height;
    data[length - 1 - i] = data[i];
  }
  return data;
};

/**
 * Generate a instance of a specific kind of shape.
 */
function getShape1D(shape) {
  const {
    kind
  } = shape;
  switch (kind) {
    case 'gaussian':
      return new Gaussian(shape);
    case 'lorentzian':
      return new Lorentzian(shape);
    case 'pseudoVoigt':
      return new PseudoVoigt(shape);
    case 'lorentzianDispersive':
      return new LorentzianDispersive(shape);
    case 'generalizedLorentzian':
      return new GeneralizedLorentzian(shape);
    default:
      {
        throw Error(`Unknown distribution ${kind}`);
      }
  }
}

/**
 * This function returns the sumOfShapes function
 * This function gives sumOfShapes access to the peak list and the associated data
 * @param internalPeaks
 */
function getSumOfShapes(internalPeaks) {
  return function sumOfShapes(parameters) {
    return x => {
      let totalY = 0;
      for (const peak of internalPeaks) {
        const peakX = parameters[peak.fromIndex];
        const y = parameters[peak.fromIndex + 1];
        for (let i = 2; i < parameters.length; i++) {
          const shapeFctKey = peak.parameters[i];
          peak.shapeFct[shapeFctKey] = parameters[peak.fromIndex + i];
        }
        totalY += y * peak.shapeFct.fct(x - peakX);
      }
      return totalY;
    };
  };
}

/**
 * Asserts that value is truthy.
 *
 * @param value - Value to check.
 * @param message - Optional error message to throw.
 */
function assert(value, message) {
  if (!value) {
    throw new Error(message ? message : 'unreachable');
  }
}

const DefaultParameters = {
  x: {
    init: peak => peak.x,
    min: (peak, peakShape) => peak.x - peakShape.fwhm * 2,
    max: (peak, peakShape) => peak.x + peakShape.fwhm * 2,
    gradientDifference: (peak, peakShape) => peakShape.fwhm * 2e-3
  },
  y: {
    init: peak => peak.y,
    min: peak => peak.y < 0 ? -1.1 : 0,
    max: peak => peak.y < 0 ? 0 : 1.1,
    gradientDifference: () => 1e-3
  },
  fwhm: {
    init: (peak, peakShape) => peakShape.fwhm,
    min: (peak, peakShape) => peakShape.fwhm * 0.25,
    max: (peak, peakShape) => peakShape.fwhm * 4,
    gradientDifference: (peak, peakShape) => peakShape.fwhm * 2e-3
  },
  mu: {
    init: (peak, peakShape) => peakShape.mu,
    min: () => 0,
    max: () => 1,
    gradientDifference: () => 0.01
  },
  gamma: {
    init: (peak, peakShape) => peakShape.gamma || 0.5,
    min: () => -1,
    max: () => 2,
    gradientDifference: () => 0.01
  }
};

const properties = ['init', 'min', 'max', 'gradientDifference'];
/**
 * Return an array of internalPeaks that contains the exact init, min, max values based on the options
 * @param peaks
 * @param minMaxY
 * @param options
 * @returns
 */
function getInternalPeaks(peaks, minMaxY, options = {}) {
  let index = 0;
  const internalPeaks = [];
  const {
    baseline: shiftValue = minMaxY.min
  } = options;
  const normalizedPeaks = peaks.map(peak => {
    return {
      ...peak,
      y: (peak.y - shiftValue) / minMaxY.range
    };
  });
  for (const peak of normalizedPeaks) {
    const {
      id,
      shape = options.shape ? options.shape : {
        kind: 'gaussian'
      }
    } = peak;
    const shapeFct = getShape1D(shape);
    const parameters = ['x', 'y', ...shapeFct.getParameters()];
    const propertiesValues = {
      min: [],
      max: [],
      init: [],
      gradientDifference: []
    };
    for (const parameter of parameters) {
      for (const property of properties) {
        // check if the property is specified in the peak
        let propertyValue = peak?.parameters?.[parameter]?.[property];
        if (propertyValue) {
          propertyValue = getNormalizedValue(propertyValue, parameter, property, minMaxY, options.baseline);
          propertiesValues[property].push(propertyValue);
          continue;
        }
        // check if there are some global option, it could be a number or a callback
        let generalParameterValue = options?.parameters?.[parameter]?.[property];
        if (generalParameterValue) {
          if (typeof generalParameterValue === 'number') {
            generalParameterValue = getNormalizedValue(generalParameterValue, parameter, property, minMaxY, options.baseline);
            propertiesValues[property].push(generalParameterValue);
            continue;
          } else {
            let value = generalParameterValue(peak);
            value = getNormalizedValue(value, parameter, property, minMaxY, options.baseline);
            propertiesValues[property].push(value);
            continue;
          }
        }
        // we just need to take the default parameters
        assert(DefaultParameters[parameter], `No default parameter for ${parameter}`);
        const defaultParameterValues = DefaultParameters[parameter][property];
        //@ts-expect-error should never happen
        propertiesValues[property].push(defaultParameterValues(peak, shapeFct));
      }
    }
    const fromIndex = index;
    const toIndex = fromIndex + parameters.length - 1;
    index += toIndex - fromIndex + 1;
    internalPeaks.push({
      id,
      shape,
      shapeFct,
      parameters,
      propertiesValues,
      fromIndex,
      toIndex
    });
  }
  return internalPeaks;
}
function getNormalizedValue(value, parameter, property, minMaxY, baseline) {
  if (parameter === 'y') {
    if (property === 'gradientDifference') {
      return value;
    } else {
      return baseline !== undefined ? (value - baseline) / minMaxY.range : (value - minMaxY.min) / minMaxY.range;
    }
  }
  return value;
}

function checkOptions(data, options) {
  const {
    timeout,
    initialValues,
    weights = 1,
    damping = 1e-2,
    dampingStepUp = 11,
    dampingStepDown = 9,
    maxIterations = 100,
    errorTolerance = 1e-7,
    centralDifference = false,
    gradientDifference = 10e-2,
    improvementThreshold = 1e-3
  } = options;
  let {
    minValues,
    maxValues
  } = options;
  if (damping <= 0) {
    throw new Error('The damping option must be a positive number');
  } else if (!data.x || !data.y) {
    throw new Error('The data parameter must have x and y elements');
  } else if (!isAnyArray$1(data.x) || data.x.length < 2 || !isAnyArray$1(data.y) || data.y.length < 2) {
    throw new Error('The data parameter elements must be an array with more than 2 points');
  } else if (data.x.length !== data.y.length) {
    throw new Error('The data parameter elements must have the same size');
  }
  if (!(initialValues && initialValues.length > 0)) {
    throw new Error('The initialValues option is mandatory and must be an array');
  }
  const parameters = Array.from(initialValues);
  const parLen = parameters.length;
  maxValues = maxValues || new Array(parLen).fill(Number.MAX_SAFE_INTEGER);
  minValues = minValues || new Array(parLen).fill(Number.MIN_SAFE_INTEGER);
  if (maxValues.length !== minValues.length) {
    throw new Error('minValues and maxValues must be the same size');
  }
  const gradientDifferenceArray = getGradientDifferenceArray(gradientDifference, parameters);
  const filler = getFiller(weights, data.x.length);
  const checkTimeout = getCheckTimeout(timeout);
  const weightSquare = Array.from({
    length: data.x.length
  }, (_, i) => filler(i));
  return {
    checkTimeout,
    minValues,
    maxValues,
    parameters,
    weightSquare,
    damping,
    dampingStepUp,
    dampingStepDown,
    maxIterations,
    errorTolerance,
    centralDifference,
    gradientDifference: gradientDifferenceArray,
    improvementThreshold
  };
}
function getGradientDifferenceArray(gradientDifference, parameters) {
  if (typeof gradientDifference === 'number') {
    return new Array(parameters.length).fill(gradientDifference);
  } else if (isAnyArray$1(gradientDifference)) {
    const parLen = parameters.length;
    if (gradientDifference.length !== parLen) {
      return new Array(parLen).fill(gradientDifference[0]);
    }
    return Array.from(gradientDifference);
  }
  throw new Error('gradientDifference should be a number or array with length equal to the number of parameters');
}
function getFiller(weights, dataLength) {
  if (typeof weights === 'number') {
    const value = 1 / weights ** 2;
    return () => value;
  } else if (isAnyArray$1(weights)) {
    if (weights.length < dataLength) {
      const value = 1 / weights[0] ** 2;
      return () => value;
    }
    return i => 1 / weights[i] ** 2;
  }
  throw new Error('weights should be a number or array with length equal to the number of data points');
}
function getCheckTimeout(timeout) {
  if (timeout !== undefined) {
    if (typeof timeout !== 'number') {
      throw new Error('timeout should be a number');
    }
    const endTime = Date.now() + timeout * 1000;
    return () => Date.now() > endTime;
  } else {
    return () => false;
  }
}

/**
 * the sum of the weighted squares of the errors (or weighted residuals) between the data.y
 * and the curve-fit function.
 *
 * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param parameters - Array of current parameter values
 * @param parameterizedFunction - The parameters and returns a function with the independent variable as a parameter
 * @param weightSquare - Square of weights (must be same length as data.x)
 */
function errorCalculation(data, parameters, parameterizedFunction, weightSquare) {
  let error = 0;
  const func = parameterizedFunction(parameters);
  for (let i = 0; i < data.x.length; i++) {
    error += (data.y[i] - func(data.x[i])) ** 2 / weightSquare[i];
  }
  return error;
}

/**
 * Difference of the matrix function over the parameters
 * @param data Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param evaluatedData - Array of previous evaluated function values
 * @param params - Array of previous parameter values
 * @param gradientDifference - The step size to approximate the jacobian matrix
 * @param centralDifference - If true the jacobian matrix is approximated by central differences otherwise by forward differences
 * @param paramFunction - The parameters and returns a function with the independent variable as a parameter
 */
function gradientFunction(data, evaluatedData, params, gradientDifference, paramFunction, centralDifference) {
  const nbParams = params.length;
  const nbPoints = data.x.length;
  const ans = Matrix.zeros(nbParams, nbPoints);
  let rowIndex = 0;
  for (let param = 0; param < nbParams; param++) {
    if (gradientDifference[param] === 0) continue;
    let delta = gradientDifference[param];
    let auxParams = params.slice();
    auxParams[param] += delta;
    const funcParam = paramFunction(auxParams);
    if (!centralDifference) {
      for (let point = 0; point < nbPoints; point++) {
        ans.set(rowIndex, point, (evaluatedData[point] - funcParam(data.x[point])) / delta);
      }
    } else {
      auxParams = params.slice();
      auxParams[param] -= delta;
      delta *= 2;
      const funcParam2 = paramFunction(auxParams);
      for (let point = 0; point < nbPoints; point++) {
        ans.set(rowIndex, point, (funcParam2(data.x[point]) - funcParam(data.x[point])) / delta);
      }
    }
    rowIndex++;
  }
  return ans;
}

/**
 * Matrix function over the samples
 *
 * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param evaluatedData - Array of previous evaluated function values
 */
function matrixFunction(data, evaluatedData) {
  const m = data.x.length;
  const ans = new Matrix(m, 1);
  for (let point = 0; point < m; point++) {
    ans.set(point, 0, data.y[point] - evaluatedData[point]);
  }
  return ans;
}
/**
 * Iteration for Levenberg-Marquardt
 *
 * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param params - Array of previous parameter values
 * @param damping - Levenberg-Marquardt parameter
 * @param gradientDifference - The step size to approximate the jacobian matrix
 * @param centralDifference - If true the jacobian matrix is approximated by central differences otherwise by forward differences
 * @param parameterizedFunction - The parameters and returns a function with the independent variable as a parameter
 * @param weights - scale the gradient and residual error by weights
 */
function step(data, params, damping, gradientDifference, parameterizedFunction, centralDifference, weights) {
  const identity = Matrix.eye(params.length, params.length, damping);
  const func = parameterizedFunction(params);
  const evaluatedData = new Float64Array(data.x.length);
  for (let i = 0; i < data.x.length; i++) {
    evaluatedData[i] = func(data.x[i]);
  }
  const gradientFunc = gradientFunction(data, evaluatedData, params, gradientDifference, parameterizedFunction, centralDifference);
  const residualError = matrixFunction(data, evaluatedData);
  const inverseMatrix = inverse(identity.add(gradientFunc.mmul(gradientFunc.transpose().scale('row', {
    scale: weights
  }))));
  const jacobianWeightResidualError = gradientFunc.mmul(residualError.scale('row', {
    scale: weights
  }));
  const perturbations = inverseMatrix.mmul(jacobianWeightResidualError);
  return {
    perturbations,
    jacobianWeightResidualError
  };
}

/**
 * Curve fitting algorithm
 * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]
 * @param parameterizedFunction - Takes an array of parameters and returns a function with the independent variable as its sole argument
 * @param options - Options object
 */
function levenbergMarquardt(data, parameterizedFunction, options) {
  const checkedOptions = checkOptions(data, options);
  const {
    checkTimeout,
    minValues,
    maxValues,
    parameters,
    weightSquare,
    dampingStepUp,
    dampingStepDown,
    maxIterations,
    errorTolerance,
    centralDifference,
    gradientDifference,
    improvementThreshold
  } = checkedOptions;
  let damping = checkedOptions.damping;
  let error = errorCalculation(data, parameters, parameterizedFunction, weightSquare);
  let optimalError = error;
  let optimalParameters = parameters.slice();
  let converged = error <= errorTolerance;
  let iteration = 0;
  for (; iteration < maxIterations && !converged; iteration++) {
    const previousError = error;
    const {
      perturbations,
      jacobianWeightResidualError
    } = step(data, parameters, damping, gradientDifference, parameterizedFunction, centralDifference, weightSquare);
    for (let k = 0; k < parameters.length; k++) {
      parameters[k] = Math.min(Math.max(minValues[k], parameters[k] - perturbations.get(k, 0)), maxValues[k]);
    }
    error = errorCalculation(data, parameters, parameterizedFunction, weightSquare);
    if (isNaN(error)) break;
    if (error < optimalError - errorTolerance) {
      optimalError = error;
      optimalParameters = parameters.slice();
    }
    const improvementMetric = (previousError - error) / perturbations.transpose().mmul(perturbations.mul(damping).add(jacobianWeightResidualError)).get(0, 0);
    if (improvementMetric > improvementThreshold) {
      damping = Math.max(damping / dampingStepDown, 1e-7);
    } else {
      damping = Math.min(damping * dampingStepUp, 1e7);
    }
    if (checkTimeout()) {
      throw new Error(`The execution time is over to ${options.timeout} seconds`);
    }
    converged = error <= errorTolerance;
  }
  return {
    parameterValues: optimalParameters,
    parameterError: optimalError,
    iterations: iteration
  };
}

/**
 * Preparata, F. P., & Shamos, M. I. (2012). Computational geometry: an introduction. Springer Science & Business Media.
 * @param {Array} x - The array with x coordinates of the points.
 * @param {Array} y - The array with y coordinates of the points.
 * @return {Array} The indices of the points of anticlockwise lower convex hull
 * @private
 */
function antiLowerConvexHull(x, y) {
  if (x.length !== y.length) {
    throw new RangeError('X and Y vectors has different dimensions');
  }
  const nbPoints = x.length - 1;
  if (nbPoints === 0) return [0];
  if (nbPoints === 1) return [0, 1];
  let currentPoint = 0;
  let result = new Array(x.length).fill(true);
  while (true) {
    const a = currentPoint;
    const b = moveOn(currentPoint, nbPoints, result);
    const c = moveOn(moveOn(currentPoint, nbPoints, result), nbPoints, result);
    const det = x[c] * (y[a] - y[b]) + x[a] * (y[b] - y[c]) + x[b] * (y[c] - y[a]);
    const leftTurn = det >= 0;
    if (leftTurn) {
      currentPoint = b;
    } else {
      result[b] = false;
      currentPoint = moveBack(currentPoint, nbPoints, result);
    }
    if (c === nbPoints) break;
  }
  return result.map((item, index) => item === false ? false : index).filter(item => item !== false);
}

/**
 * @param {number} currentPoint - The index of the current point to make the move
 * @param {number} nbPoints - The total number of points in the array
 * @param {Array} vector - The array with the points
 * @return {number} the index of the point after the move
 * @private
 */

function moveBack(currentPoint, nbPoints, vector) {
  let counter = currentPoint - 1;
  while (vector[counter] === false) counter--;
  return currentPoint === 0 ? nbPoints : counter;
}
function moveOn(currentPoint, nbPoints, vector) {
  let counter = currentPoint + 1;
  while (vector[counter] === false) counter++;
  return currentPoint === nbPoints ? 0 : counter;
}

/**
 * Performs a global optimization of required parameters
 * It will return an object containing:
 * - `minFunctionValue`: The minimum value found for the objetive function
 * - `optima`: Array of Array of values for all the variables where the function reach its minimum value
 * - `iterations`: Number of iterations performed in the process
 * - `finalState`: Internal state allowing to continue optimization (initialState)
 * @param {function} objectiveFunction Function to evaluate. It should accept an array of variables
 * @param {Array} lowerBoundaries Array containing for each variable the lower boundary
 * @param {Array} upperBoundaries Array containing for each variable the higher boundary
 * @param {Object} [options={}]
 * @param {number} [options.iterations] - Number of iterations.
 * @param {number} [options.epsilon] - Tolerance to choose best current value.
 * @param {number} [options.tolerance] - Minimum tollerance of the function.
 * @param {number} [options.tolerance2] - Minimum tollerance of the function.
 * @param {Object} [options.initialState={}}] - finalState of previous optimization.
 * @return {Object} {finalState, iterations, minFunctionValue}
 * */

function direct(objectiveFunction, lowerBoundaries, upperBoundaries, options = {}) {
  const {
    iterations = 50,
    epsilon = 1e-4,
    tolerance = 1e-16,
    tolerance2 = 1e-12,
    initialState = {}
  } = options;
  if (objectiveFunction === undefined || lowerBoundaries === undefined || upperBoundaries === undefined) {
    throw new RangeError('There is something undefined');
  }
  lowerBoundaries = new Float64Array(lowerBoundaries);
  upperBoundaries = new Float64Array(upperBoundaries);
  if (lowerBoundaries.length !== upperBoundaries.length) {
    throw new Error('Lower bounds and Upper bounds for x are not of the same length');
  }

  //-------------------------------------------------------------------------
  //                        STEP 1. Initialization
  //-------------------------------------------------------------------------
  let n = lowerBoundaries.length;
  let diffBorders = upperBoundaries.map((x, i) => x - lowerBoundaries[i]);
  let {
    numberOfRectangles = 0,
    totalIterations = 0,
    unitaryCoordinates = [new Float64Array(n).fill(0.5)],
    middlePoint = new Float64Array(n).map((value, index) => {
      return lowerBoundaries[index] + unitaryCoordinates[0][index] * diffBorders[index];
    }),
    bestCurrentValue = objectiveFunction(middlePoint),
    fCalls = 1,
    smallerDistance = 0,
    edgeSizes = [new Float64Array(n).fill(0.5)],
    diagonalDistances = [Math.sqrt(n * 0.5 ** 2)],
    functionValues = [bestCurrentValue],
    differentDistances = diagonalDistances,
    smallerValuesByDistance = [bestCurrentValue],
    choiceLimit = undefined
  } = initialState;
  if (initialState.originalCoordinates && initialState.originalCoordinates.length > 0) {
    bestCurrentValue = xMinValue(functionValues);
    choiceLimit = epsilon * Math.abs(bestCurrentValue) > 1e-8 ? epsilon * Math.abs(bestCurrentValue) : 1e-8;
    smallerDistance = getMinIndex(functionValues, diagonalDistances, choiceLimit, bestCurrentValue);
    unitaryCoordinates = initialState.originalCoordinates.slice();
    for (let j = 0; j < unitaryCoordinates.length; j++) {
      for (let i = 0; i < lowerBoundaries.length; i++) {
        unitaryCoordinates[j][i] = (unitaryCoordinates[j][i] - lowerBoundaries[i]) / diffBorders[i];
      }
    }
  }
  let iteration = 0;
  //-------------------------------------------------------------------------
  //                          Iteration loop
  //-------------------------------------------------------------------------

  while (iteration < iterations) {
    //----------------------------------------------------------------------
    //  STEP 2. Identify the set S of all potentially optimal rectangles
    //----------------------------------------------------------------------

    let S1 = [];
    let idx = differentDistances.findIndex(
    // eslint-disable-next-line no-loop-func
    e => e === diagonalDistances[smallerDistance]);
    let counter = 0;
    for (let i = idx; i < differentDistances.length; i++) {
      for (let f = 0; f < functionValues.length; f++) {
        if (functionValues[f] === smallerValuesByDistance[i] & diagonalDistances[f] === differentDistances[i]) {
          S1[counter++] = f;
        }
      }
    }
    let optimumValuesIndex, S3;
    if (differentDistances.length - idx > 1) {
      let a1 = diagonalDistances[smallerDistance];
      let b1 = functionValues[smallerDistance];
      let a2 = differentDistances[differentDistances.length - 1];
      let b2 = smallerValuesByDistance[differentDistances.length - 1];
      let slope = (b2 - b1) / (a2 - a1);
      let constant = b1 - slope * a1;
      let S2 = new Uint32Array(counter);
      counter = 0;
      for (let i = 0; i < S2.length; i++) {
        let j = S1[i];
        if (functionValues[j] <= slope * diagonalDistances[j] + constant + tolerance2) {
          S2[counter++] = j;
        }
      }
      let xHull = [];
      let yHull = [];
      for (let i = 0; i < counter; i++) {
        xHull.push(diagonalDistances[S2[i]]);
        yHull.push(functionValues[S2[i]]);
      }
      let lowerIndexHull = antiLowerConvexHull(xHull, yHull);
      S3 = [];
      for (let i = 0; i < lowerIndexHull.length; i++) {
        S3.push(S2[lowerIndexHull[i]]);
      }
    } else {
      S3 = S1.slice(0, counter);
    }
    optimumValuesIndex = S3;
    //--------------------------------------------------------------
    // STEPS 3,5: Select any rectangle j in S
    //--------------------------------------------------------------
    for (let k = 0; k < optimumValuesIndex.length; k++) {
      let j = optimumValuesIndex[k];
      let largerSide = xMaxValue(edgeSizes[j]);
      let largeSidesIndex = new Uint32Array(edgeSizes[j].length);
      counter = 0;
      for (let i = 0; i < edgeSizes[j].length; i++) {
        if (Math.abs(edgeSizes[j][i] - largerSide) < tolerance) {
          largeSidesIndex[counter++] = i;
        }
      }
      let delta = 2 * largerSide / 3;
      let bestFunctionValues = [];
      for (let r = 0; r < counter; r++) {
        let i = largeSidesIndex[r];
        let firstMiddleCenter = unitaryCoordinates[j].slice();
        let secondMiddleCenter = unitaryCoordinates[j].slice();
        firstMiddleCenter[i] += delta;
        secondMiddleCenter[i] -= delta;
        let firstMiddleValue = new Float64Array(firstMiddleCenter.length);
        let secondMiddleValue = new Float64Array(secondMiddleCenter.length);
        for (let i = 0; i < firstMiddleCenter.length; i++) {
          firstMiddleValue[i] = lowerBoundaries[i] + firstMiddleCenter[i] * diffBorders[i];
          secondMiddleValue[i] = lowerBoundaries[i] + secondMiddleCenter[i] * diffBorders[i];
        }
        let firstMinValue = objectiveFunction(firstMiddleValue);
        let secondMinValue = objectiveFunction(secondMiddleValue);
        fCalls += 2;
        bestFunctionValues.push({
          minValue: Math.min(firstMinValue, secondMinValue),
          index: r
        });
        // [Math.min(firstMinValue, secondMinValue), r];
        unitaryCoordinates.push(firstMiddleCenter, secondMiddleCenter);
        functionValues.push(firstMinValue, secondMinValue);
      }
      let b = bestFunctionValues.sort((a, b) => a.minValue - b.minValue);
      for (let r = 0; r < counter; r++) {
        let u = largeSidesIndex[b[r].index];
        let ix1 = numberOfRectangles + 2 * (b[r].index + 1) - 1;
        let ix2 = numberOfRectangles + 2 * (b[r].index + 1);
        edgeSizes[j][u] = delta / 2;
        edgeSizes[ix1] = edgeSizes[j].slice();
        edgeSizes[ix2] = edgeSizes[j].slice();
        diagonalDistances[j] = xNorm(edgeSizes[j]);
        diagonalDistances[ix1] = diagonalDistances[j];
        diagonalDistances[ix2] = diagonalDistances[j];
      }
      numberOfRectangles += 2 * counter;
    }

    //--------------------------------------------------------------
    //                  Update
    //--------------------------------------------------------------

    bestCurrentValue = xMinValue(functionValues);
    choiceLimit = epsilon * Math.abs(bestCurrentValue) > 1e-8 ? epsilon * Math.abs(bestCurrentValue) : 1e-8;
    smallerDistance = getMinIndex(functionValues, diagonalDistances, choiceLimit, bestCurrentValue);
    differentDistances = Array.from(new Set(diagonalDistances));
    differentDistances = differentDistances.sort((a, b) => a - b);
    smallerValuesByDistance = [];
    for (let i = 0; i < differentDistances.length; i++) {
      let minIndex;
      let minValue = Number.POSITIVE_INFINITY;
      for (let k = 0; k < diagonalDistances.length; k++) {
        if (diagonalDistances[k] === differentDistances[i]) {
          if (functionValues[k] < minValue) {
            minValue = functionValues[k];
            minIndex = k;
          }
        }
      }
      smallerValuesByDistance.push(functionValues[minIndex]);
    }
    for (let j = 0; j < functionValues.length; j++) {
      if (functionValues[j] === bestCurrentValue) {
        let temp = [];
        for (let i = 0; i < lowerBoundaries.length; i++) {
          temp.push(lowerBoundaries[i] + unitaryCoordinates[j][i] * diffBorders[i]);
        }
      }
    }
    iteration += 1;
  }
  //--------------------------------------------------------------
  //                  Saving results
  //--------------------------------------------------------------

  let result = {};
  result.minFunctionValue = bestCurrentValue;
  result.iterations = iteration;
  let originalCoordinates = [];
  for (let j = 0; j < numberOfRectangles + 1; j++) {
    let pair = [];
    for (let i = 0; i < lowerBoundaries.length; i++) {
      pair.push(lowerBoundaries[i] + unitaryCoordinates[j][i] * diffBorders[i]);
    }
    originalCoordinates.push(pair);
  }
  result.finalState = {
    numberOfRectangles,
    totalIterations: totalIterations += iterations,
    originalCoordinates,
    middlePoint,
    fCalls,
    smallerDistance,
    edgeSizes,
    diagonalDistances,
    functionValues,
    differentDistances,
    smallerValuesByDistance,
    choiceLimit
  };
  let minimizer = [];
  for (let i = 0; i < functionValues.length; i++) {
    if (functionValues[i] === bestCurrentValue) {
      minimizer.push(originalCoordinates[i]);
    }
  }
  result.optima = minimizer;
  return result;
}
function getMinIndex(functionValues, diagonalDistances, choiceLimit, bestCurrentValue) {
  let item = [];
  for (let i = 0; i < functionValues.length; i++) {
    item[i] = Math.abs(functionValues[i] - (bestCurrentValue + choiceLimit)) / diagonalDistances[i];
  }
  const min = xMinValue(item);
  let result = item.findIndex(x => x === min);
  return result;
}

function directOptimization(data, sumOfShapes, options) {
  const {
    minValues,
    maxValues,
    maxIterations,
    epsilon,
    tolerance,
    tolerance2,
    initialState
  } = options;
  const objectiveFunction = getObjectiveFunction(data, sumOfShapes);
  const result = direct(objectiveFunction,
  // direct internally converts ArrayLike to Float64Array,
  // so we can safely cast minValues and maxValues to number[]
  minValues, maxValues, {
    iterations: maxIterations,
    epsilon,
    tolerance,
    tolerance2,
    initialState
  });
  const {
    optima
  } = result;
  return {
    parameterError: result.minFunctionValue,
    iterations: result.iterations,
    parameterValues: optima[0]
  };
}
function getObjectiveFunction(data, sumOfShapes) {
  const {
    x,
    y
  } = data;
  const nbPoints = x.length;
  return parameters => {
    const fct = sumOfShapes(parameters);
    let error = 0;
    for (let i = 0; i < nbPoints; i++) {
      error += (y[i] - fct(x[i])) ** 2;
    }
    return error;
  };
}

/** Algorithm to select the method.
 * @param optimizationOptions - Optimization options
 * @returns - The algorithm and optimization options
 */
function selectMethod(optimizationOptions = {}) {
  const {
    kind = 'lm',
    options
  } = optimizationOptions;
  switch (kind) {
    case 'lm':
    case 'levenbergMarquardt':
      return {
        algorithm: levenbergMarquardt,
        optimizationOptions: {
          damping: 1.5,
          maxIterations: 100,
          errorTolerance: 1e-8,
          ...options
        }
      };
    case 'direct':
      {
        return {
          algorithm: directOptimization,
          optimizationOptions: {
            iterations: 20,
            epsilon: 1e-4,
            tolerance: 1e-16,
            tolerance2: 1e-12,
            initialState: {},
            ...options
          }
        };
      }
    default:
      throw new Error(`Unknown fitting algorithm`);
  }
}

/**
 * Fits a set of points to the sum of a set of bell functions.
 *
 * @param data - An object containing the x and y data to be fitted.
 * @param peaks - A list of initial parameters to be optimized. e.g. coming from a peak picking [{x, y, width}].
 * @param options - Options for optimize
 * @returns - An object with fitting error and the list of optimized parameters { parameters: [ {x, y, width} ], error } if the kind of shape is pseudoVoigt mu parameter is optimized.
 */
function optimize(data, peaks, options = {}) {
  // rescale data
  const temp = xMinMaxValues(data.y);
  const minMaxY = {
    ...temp,
    range: temp.max - temp.min
  };
  const internalPeaks = getInternalPeaks(peaks, minMaxY, options);
  // need to rescale what is related to Y
  const {
    baseline: shiftValue = minMaxY.min
  } = options;
  const normalizedY = new Float64Array(data.y.length);
  for (let i = 0; i < data.y.length; i++) {
    normalizedY[i] = (data.y[i] - shiftValue) / minMaxY.range;
  }
  const nbParams = internalPeaks[internalPeaks.length - 1].toIndex + 1;
  const minValues = new Float64Array(nbParams);
  const maxValues = new Float64Array(nbParams);
  const initialValues = new Float64Array(nbParams);
  const gradientDifferences = new Float64Array(nbParams);
  let index = 0;
  for (const peak of internalPeaks) {
    for (let i = 0; i < peak.parameters.length; i++) {
      minValues[index] = peak.propertiesValues.min[i];
      maxValues[index] = peak.propertiesValues.max[i];
      initialValues[index] = peak.propertiesValues.init[i];
      gradientDifferences[index] = peak.propertiesValues.gradientDifference[i];
      index++;
    }
  }
  const {
    algorithm,
    optimizationOptions
  } = selectMethod(options.optimization);
  const sumOfShapes = getSumOfShapes(internalPeaks);
  const fitted = algorithm({
    x: data.x,
    y: normalizedY
  }, sumOfShapes, {
    minValues,
    maxValues,
    initialValues,
    gradientDifference: gradientDifferences,
    ...optimizationOptions
  });
  const fittedValues = fitted.parameterValues;
  const newPeaks = [];
  for (const peak of internalPeaks) {
    const {
      id,
      shape,
      parameters,
      fromIndex
    } = peak;
    let newPeak = {
      x: 0,
      y: 0,
      shape
    };
    if (id) {
      newPeak = {
        ...newPeak,
        id
      };
    }
    newPeak.x = fittedValues[fromIndex];
    newPeak.y = fittedValues[fromIndex + 1] * minMaxY.range + shiftValue;
    for (let i = 2; i < parameters.length; i++) {
      //@ts-expect-error should be fixed once
      newPeak.shape[parameters[i]] = fittedValues[fromIndex + i];
    }
    newPeaks.push(newPeak);
  }
  return {
    error: fitted.parameterError,
    iterations: fitted.iterations,
    peaks: newPeaks
  };
}

/**
 * Filter that allows to calibrateX the x axis based on the presence of peaks
 * @param data
 * @param options
 */
function calibrateX(data, options = {}) {
  const {
    targetX = 0,
    nbPeaks = 1,
    from = data.x[0],
    to = data.x.at(-1),
    gsd: gsdOptions = {
      minMaxRatio: 0.1,
      realTopDetection: true,
      smoothY: true,
      sgOptions: {
        windowSize: 7,
        polynomial: 3
      }
    }
  } = options;
  const fromIndex = xFindClosestIndex(data.x, from);
  const toIndex = xFindClosestIndex(data.x, to);
  let peaks = gsd({
    x: data.x.subarray(fromIndex, toIndex),
    y: data.y.subarray(fromIndex, toIndex)
  }, gsdOptions);
  peaks.sort((a, b) => b.y - a.y);
  peaks = peaks.slice(0, nbPeaks);
  if (peaks.length < nbPeaks) return {
    data
  };
  const middle = xMean(peaks.map(peak => peak.x));
  return {
    data: {
      x: xAdd(data.x, targetX - middle),
      y: data.y
    }
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function xFunction(data, options = {}) {
  return {
    data: {
      x: xApplyFunctionStr(data.x, {
        variableLabel: 'x',
        fctString: options.function
      }),
      y: data.y
    }
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function yFunction(data, options = {}) {
  return {
    data: {
      x: data.x,
      y: xApplyFunctionStr(data.y, {
        variableLabel: 'y',
        fctString: options.function
      })
    }
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function setMaxY(data, options = {}) {
  const {
    max = 1
  } = options;
  const existingMax = xMaxValue(data.y);
  if (existingMax === max) {
    return {
      data
    };
  }
  return {
    data: {
      x: data.x,
      y: xAdd(data.y, max - existingMax)
    }
  };
}

/**
 * Filter that allows to
 * @param data
 * @param options
 */
function setMinY(data, options = {}) {
  const {
    min = 0
  } = options;
  const existingMin = xMinValue(data.y);
  if (existingMin === min) {
    return {
      data
    };
  }
  return {
    data: {
      x: data.x,
      y: xAdd(data.y, min - existingMin)
    }
  };
}

var Filters = /*#__PURE__*/Object.freeze({
    __proto__: null,
    airPLSBaseline: airPLSBaseline,
    calibrateX: calibrateX,
    centerMean: centerMean,
    centerMedian: centerMedian,
    divideBySD: divideBySD,
    ensureGrowing: ensureGrowing,
    equallySpaced: equallySpaced,
    filterX: filterX,
    firstDerivative: firstDerivative$1,
    fromTo: fromTo,
    iterativePolynomialBaseline: iterativePolynomialBaseline,
    normed: normed,
    paretoNormalization: paretoNormalization,
    rescale: rescale,
    reverseIfNeeded: reverseIfNeeded,
    rollingAverageBaseline: rollingAverageBaseline,
    rollingBallBaseline: rollingBallBaseline,
    rollingMedianBaseline: rollingMedianBaseline,
    savitzkyGolay: savitzkyGolay,
    secondDerivative: secondDerivative$1,
    setMaxX: setMaxX,
    setMaxY: setMaxY,
    setMinX: setMinX,
    setMinY: setMinY,
    thirdDerivative: thirdDerivative,
    xFunction: xFunction,
    yFunction: yFunction
});

/**
 * Apply filters on {x:[], y:[]}
 * @param data
 * @param filters
 * @returns
 */
function filterXY(data, filters) {
  let result = {
    data: xyGrowingX({
      x: xEnsureFloat64(data.x),
      y: xEnsureFloat64(data.y)
    })
  };
  const logs = [];
  for (const filter of filters) {
    const start = Date.now();
    if (!filter.name) {
      // we ignore empty filter names
      continue;
    }
    const filterFct = Filters[filter.name];
    if (!filterFct) {
      throw new Error(`Unknown filter: ${filter.name}`);
    }
    // @ts-expect-error some method have options and some other ones don't have any options
    result = filterFct(result.data, filter.options);
    result.data = xyGrowingX(result.data);
    logs.push({
      name: filter.name,
      time: Date.now() - start
    });
  }
  return {
    logs,
    data: result.data
  };
}

function getNormalizedSpectrum(spectrum, options = {}) {
  const data = {
    x: spectrum.variables.x.data,
    y: spectrum.variables.y.data
  };
  const newSpectrum = {
    variables: {
      x: {
        data: spectrum.variables.x.data,
        units: spectrum.variables.x.units,
        label: spectrum.variables.x.label
      },
      y: {
        data: spectrum.variables.y.data,
        units: spectrum.variables.y.units,
        label: spectrum.variables.y.label
      }
    }
  };
  if (spectrum.title) newSpectrum.title = spectrum.title;
  if (spectrum.dataType) newSpectrum.dataType = spectrum.dataType;
  if (spectrum.meta) newSpectrum.meta = spectrum.meta;
  if (spectrum.id) newSpectrum.id = spectrum.id;
  const {
    from = spectrum.variables.x.min,
    to = spectrum.variables.x.max,
    numberOfPoints,
    applyRangeSelectionFirst = false,
    exclusions = [],
    zones = []
  } = options;
  let {
    filters = []
  } = options;
  filters = structuredClone(filters);
  if (numberOfPoints) {
    if (applyRangeSelectionFirst) {
      filters.unshift({
        name: 'equallySpaced',
        options: {
          from,
          to,
          exclusions,
          zones,
          numberOfPoints
        }
      });
    } else {
      filters.push({
        name: 'equallySpaced',
        options: {
          from,
          to,
          exclusions,
          zones,
          numberOfPoints
        }
      });
    }
  } else if (applyRangeSelectionFirst) {
    filters.unshift({
      name: 'filterX',
      options: {
        from,
        to,
        exclusions,
        zones
      }
    });
  } else {
    filters.push({
      name: 'filterX',
      options: {
        from,
        to,
        exclusions,
        zones
      }
    });
  }
  const {
    x,
    y
  } = filterXY(data, filters).data;
  // filters change the y axis, we get rid of the units
  // TODO we should deal correctly with this problem
  if (filters.length > 1) {
    newSpectrum.variables.y.units = '';
    newSpectrum.variables.y.label = newSpectrum.variables.y.label?.replace(/\s*\[.*]/, '');
  }
  newSpectrum.variables.x.data = x;
  newSpectrum.variables.x.min = xMinValue(x);
  newSpectrum.variables.x.max = xMaxValue(x);
  newSpectrum.variables.x.isMonotonic = xIsMonotonic(x);
  newSpectrum.variables.y.data = y;
  newSpectrum.variables.y.min = xMinValue(y);
  newSpectrum.variables.y.max = xMaxValue(y);
  newSpectrum.variables.y.isMonotonic = xIsMonotonic(y);
  return newSpectrum;
}

var quantities$1 = {exports: {}};

/*
The MIT License (MIT)
Copyright © 2006-2007 Kevin C. Olbrich
Copyright © 2010-2016 LIM SAS (http://lim.eu) - Julien Sanchez

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var quantities = quantities$1.exports;
(function (module, exports$1) {
  (function (global, factory) {
    module.exports = factory() ;
  })(quantities, function () {

    /**
     * Tests if a value is a string
     *
     * @param {*} value - Value to test
     *
     * @returns {boolean} true if value is a string, false otherwise
     */
    function isString(value) {
      return typeof value === "string" || value instanceof String;
    }

    /*
     * Prefer stricter Number.isFinite if currently supported.
     * To be dropped when ES6 is finalized. Obsolete browsers will
     * have to use ES6 polyfills.
     */
    var isFiniteImpl = Number.isFinite || window.isFinite;
    /**
     * Tests if a value is a number
     *
     * @param {*} value - Value to test
     *
     * @returns {boolean} true if value is a number, false otherwise
     */
    function isNumber(value) {
      // Number.isFinite allows not to consider NaN or '1' as numbers
      return isFiniteImpl(value);
    }

    /*
     * Identity function
     */
    function identity(value) {
      return value;
    }

    /**
     * Returns unique strings from list
     *
     * @param {string[]} strings - array of strings
     *
     *
     * @returns {string[]} a new array of strings without duplicates
     */
    function uniq(strings) {
      var seen = {};
      return strings.filter(function (item) {
        return seen.hasOwnProperty(item) ? false : seen[item] = true;
      });
    }
    function compareArray(array1, array2) {
      if (array2.length !== array1.length) {
        return false;
      }
      for (var i = 0; i < array1.length; i++) {
        if (array2[i].compareArray) {
          if (!array2[i].compareArray(array1[i])) {
            return false;
          }
        }
        if (array2[i] !== array1[i]) {
          return false;
        }
      }
      return true;
    }
    function assign(target, properties) {
      Object.keys(properties).forEach(function (key) {
        target[key] = properties[key];
      });
    }

    /**
     * Safely multiplies numbers while avoiding floating errors
     * like 0.1 * 0.1 => 0.010000000000000002
     *
     * @param {...number} numbers - numbers to multiply
     *
     * @returns {number} result
     */
    function mulSafe() {
      var result = 1,
        decimals = 0;
      for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        decimals = decimals + getFractional(arg);
        result *= arg;
      }
      return decimals !== 0 ? round(result, decimals) : result;
    }

    /**
     * Safely divides two numbers while avoiding floating errors
     * like 0.3 / 0.05 => 5.999999999999999
     *
     * @returns {number} result
     * @param {number} num Numerator
     * @param {number} den Denominator
     */
    function divSafe(num, den) {
      if (den === 0) {
        throw new Error("Divide by zero");
      }
      var factor = Math.pow(10, getFractional(den));
      var invDen = factor / (factor * den);
      return mulSafe(num, invDen);
    }

    /**
     * Rounds value at the specified number of decimals
     *
     * @param {number} val - value to round
     * @param {number} decimals - number of decimals
     *
     * @returns {number} rounded number
     */
    function round(val, decimals) {
      return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals);
    }
    function getFractional(num) {
      // Check for NaNs or Infinities
      if (!isFinite(num)) {
        return 0;
      }

      // Faster than parsing strings
      // http://jsperf.com/count-decimals/2
      var count = 0;
      while (num % 1 !== 0) {
        num *= 10;
        count++;
      }
      return count;
    }

    /**
     * Custom error type definition
     * @constructor
     */
    function QtyError() {
      var err;
      if (!this) {
        // Allows to instantiate QtyError without new()
        err = Object.create(QtyError.prototype);
        QtyError.apply(err, arguments);
        return err;
      }
      err = Error.apply(this, arguments);
      this.name = "QtyError";
      this.message = err.message;
      this.stack = err.stack;
    }
    QtyError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: QtyError
      }
    });

    /*
     * Throws incompatible units error
     * @param {string} left - units
     * @param {string} right - units incompatible with first argument
     * @throws "Incompatible units" error
     */
    function throwIncompatibleUnits(left, right) {
      throw new QtyError("Incompatible units: " + left + " and " + right);
    }
    var UNITS = {
      /* prefixes */
      "<googol>": [["googol"], 1e100, "prefix"],
      "<kibi>": [["Ki", "Kibi", "kibi"], Math.pow(2, 10), "prefix"],
      "<mebi>": [["Mi", "Mebi", "mebi"], Math.pow(2, 20), "prefix"],
      "<gibi>": [["Gi", "Gibi", "gibi"], Math.pow(2, 30), "prefix"],
      "<tebi>": [["Ti", "Tebi", "tebi"], Math.pow(2, 40), "prefix"],
      "<pebi>": [["Pi", "Pebi", "pebi"], Math.pow(2, 50), "prefix"],
      "<exi>": [["Ei", "Exi", "exi"], Math.pow(2, 60), "prefix"],
      "<zebi>": [["Zi", "Zebi", "zebi"], Math.pow(2, 70), "prefix"],
      "<yebi>": [["Yi", "Yebi", "yebi"], Math.pow(2, 80), "prefix"],
      "<yotta>": [["Y", "Yotta", "yotta"], 1e24, "prefix"],
      "<zetta>": [["Z", "Zetta", "zetta"], 1e21, "prefix"],
      "<exa>": [["E", "Exa", "exa"], 1e18, "prefix"],
      "<peta>": [["P", "Peta", "peta"], 1e15, "prefix"],
      "<tera>": [["T", "Tera", "tera"], 1e12, "prefix"],
      "<giga>": [["G", "Giga", "giga"], 1e9, "prefix"],
      "<mega>": [["M", "Mega", "mega"], 1e6, "prefix"],
      "<kilo>": [["k", "kilo"], 1e3, "prefix"],
      "<hecto>": [["h", "Hecto", "hecto"], 1e2, "prefix"],
      "<deca>": [["da", "Deca", "deca", "deka"], 1e1, "prefix"],
      "<deci>": [["d", "Deci", "deci"], 1e-1, "prefix"],
      "<centi>": [["c", "Centi", "centi"], 1e-2, "prefix"],
      "<milli>": [["m", "Milli", "milli"], 1e-3, "prefix"],
      "<micro>": [["u", "\u03BC" /*µ as greek letter*/, "\u00B5" /*µ as micro sign*/, "Micro", "mc", "micro"], 1e-6, "prefix"],
      "<nano>": [["n", "Nano", "nano"], 1e-9, "prefix"],
      "<pico>": [["p", "Pico", "pico"], 1e-12, "prefix"],
      "<femto>": [["f", "Femto", "femto"], 1e-15, "prefix"],
      "<atto>": [["a", "Atto", "atto"], 1e-18, "prefix"],
      "<zepto>": [["z", "Zepto", "zepto"], 1e-21, "prefix"],
      "<yocto>": [["y", "Yocto", "yocto"], 1e-24, "prefix"],
      "<1>": [["1", "<1>"], 1, ""],
      /* length units */
      "<meter>": [["m", "meter", "meters", "metre", "metres"], 1.0, "length", ["<meter>"]],
      "<inch>": [["in", "inch", "inches", "\""], 0.0254, "length", ["<meter>"]],
      "<foot>": [["ft", "foot", "feet", "'"], 0.3048, "length", ["<meter>"]],
      "<yard>": [["yd", "yard", "yards"], 0.9144, "length", ["<meter>"]],
      "<mile>": [["mi", "mile", "miles"], 1609.344, "length", ["<meter>"]],
      "<naut-mile>": [["nmi", "naut-mile"], 1852, "length", ["<meter>"]],
      "<league>": [["league", "leagues"], 4828, "length", ["<meter>"]],
      "<furlong>": [["furlong", "furlongs"], 201.2, "length", ["<meter>"]],
      "<rod>": [["rd", "rod", "rods"], 5.029, "length", ["<meter>"]],
      "<mil>": [["mil", "mils"], 0.0000254, "length", ["<meter>"]],
      "<angstrom>": [["ang", "angstrom", "angstroms"], 1e-10, "length", ["<meter>"]],
      "<fathom>": [["fathom", "fathoms"], 1.829, "length", ["<meter>"]],
      "<pica>": [["pica", "picas"], 0.00423333333, "length", ["<meter>"]],
      "<point>": [["pt", "point", "points"], 0.000352777778, "length", ["<meter>"]],
      "<redshift>": [["z", "red-shift", "redshift"], 1.302773e26, "length", ["<meter>"]],
      "<AU>": [["AU", "astronomical-unit"], 149597900000, "length", ["<meter>"]],
      "<light-second>": [["ls", "light-second"], 299792500, "length", ["<meter>"]],
      "<light-minute>": [["lmin", "light-minute"], 17987550000, "length", ["<meter>"]],
      "<light-year>": [["ly", "light-year"], 9460528000000000, "length", ["<meter>"]],
      "<parsec>": [["pc", "parsec", "parsecs"], 30856780000000000, "length", ["<meter>"]],
      "<datamile>": [["DM", "datamile"], 1828.8, "length", ["<meter>"]],
      /* mass */
      "<kilogram>": [["kg", "kilogram", "kilograms"], 1.0, "mass", ["<kilogram>"]],
      "<AMU>": [["u", "AMU", "amu"], 1.660538921e-27, "mass", ["<kilogram>"]],
      "<dalton>": [["Da", "Dalton", "Daltons", "dalton", "daltons"], 1.660538921e-27, "mass", ["<kilogram>"]],
      "<slug>": [["slug", "slugs"], 14.5939029, "mass", ["<kilogram>"]],
      "<short-ton>": [["tn", "ton", "short-ton"], 907.18474, "mass", ["<kilogram>"]],
      "<metric-ton>": [["t", "tonne", "metric-ton"], 1000, "mass", ["<kilogram>"]],
      "<carat>": [["ct", "carat", "carats"], 0.0002, "mass", ["<kilogram>"]],
      "<pound>": [["lbs", "lb", "pound", "pounds", "#"], 0.45359237, "mass", ["<kilogram>"]],
      "<ounce>": [["oz", "ounce", "ounces"], 0.0283495231, "mass", ["<kilogram>"]],
      "<gram>": [["g", "gram", "grams", "gramme", "grammes"], 1e-3, "mass", ["<kilogram>"]],
      "<grain>": [["grain", "grains", "gr"], 6.479891e-5, "mass", ["<kilogram>"]],
      "<dram>": [["dram", "drams", "dr"], 0.0017718452, "mass", ["<kilogram>"]],
      "<stone>": [["stone", "stones", "st"], 6.35029318, "mass", ["<kilogram>"]],
      /* area */
      "<hectare>": [["hectare"], 10000, "area", ["<meter>", "<meter>"]],
      "<acre>": [["acre", "acres"], 4046.85642, "area", ["<meter>", "<meter>"]],
      "<sqft>": [["sqft"], 1, "area", ["<foot>", "<foot>"]],
      /* volume */
      "<liter>": [["l", "L", "liter", "liters", "litre", "litres"], 0.001, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<gallon>": [["gal", "gallon", "gallons"], 0.0037854118, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<gallon-imp>": [["galimp", "gallon-imp", "gallons-imp"], 0.0045460900, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<quart>": [["qt", "quart", "quarts"], 0.00094635295, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<pint>": [["pt", "pint", "pints"], 0.000473176475, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<pint-imp>": [["ptimp", "pint-imp", "pints-imp"], 5.6826125e-4, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<cup>": [["cu", "cup", "cups"], 0.000236588238, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<fluid-ounce>": [["floz", "fluid-ounce", "fluid-ounces"], 2.95735297e-5, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<fluid-ounce-imp>": [["flozimp", "floz-imp", "fluid-ounce-imp", "fluid-ounces-imp"], 2.84130625e-5, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<tablespoon>": [["tb", "tbsp", "tbs", "tablespoon", "tablespoons"], 1.47867648e-5, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<teaspoon>": [["tsp", "teaspoon", "teaspoons"], 4.92892161e-6, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<bushel>": [["bu", "bsh", "bushel", "bushels"], 0.035239072, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<oilbarrel>": [["bbl", "oilbarrel", "oilbarrels", "oil-barrel", "oil-barrels"], 0.158987294928, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<beerbarrel>": [["bl", "bl-us", "beerbarrel", "beerbarrels", "beer-barrel", "beer-barrels"], 0.1173477658, "volume", ["<meter>", "<meter>", "<meter>"]],
      "<beerbarrel-imp>": [["blimp", "bl-imp", "beerbarrel-imp", "beerbarrels-imp", "beer-barrel-imp", "beer-barrels-imp"], 0.16365924, "volume", ["<meter>", "<meter>", "<meter>"]],
      /* speed */
      "<kph>": [["kph"], 0.277777778, "speed", ["<meter>"], ["<second>"]],
      "<mph>": [["mph"], 0.44704, "speed", ["<meter>"], ["<second>"]],
      "<knot>": [["kt", "kn", "kts", "knot", "knots"], 0.514444444, "speed", ["<meter>"], ["<second>"]],
      "<fps>": [["fps"], 0.3048, "speed", ["<meter>"], ["<second>"]],
      /* acceleration */
      "<gee>": [["gee"], 9.80665, "acceleration", ["<meter>"], ["<second>", "<second>"]],
      "<Gal>": [["Gal"], 1e-2, "acceleration", ["<meter>"], ["<second>", "<second>"]],
      /* temperature_difference */
      "<kelvin>": [["degK", "kelvin"], 1.0, "temperature", ["<kelvin>"]],
      "<celsius>": [["degC", "celsius", "celsius", "centigrade"], 1.0, "temperature", ["<kelvin>"]],
      "<fahrenheit>": [["degF", "fahrenheit"], 5 / 9, "temperature", ["<kelvin>"]],
      "<rankine>": [["degR", "rankine"], 5 / 9, "temperature", ["<kelvin>"]],
      "<temp-K>": [["tempK", "temp-K"], 1.0, "temperature", ["<temp-K>"]],
      "<temp-C>": [["tempC", "temp-C"], 1.0, "temperature", ["<temp-K>"]],
      "<temp-F>": [["tempF", "temp-F"], 5 / 9, "temperature", ["<temp-K>"]],
      "<temp-R>": [["tempR", "temp-R"], 5 / 9, "temperature", ["<temp-K>"]],
      /* time */
      "<second>": [["s", "sec", "secs", "second", "seconds"], 1.0, "time", ["<second>"]],
      "<minute>": [["min", "mins", "minute", "minutes"], 60.0, "time", ["<second>"]],
      "<hour>": [["h", "hr", "hrs", "hour", "hours"], 3600.0, "time", ["<second>"]],
      "<day>": [["d", "day", "days"], 3600 * 24, "time", ["<second>"]],
      "<week>": [["wk", "week", "weeks"], 7 * 3600 * 24, "time", ["<second>"]],
      "<fortnight>": [["fortnight", "fortnights"], 1209600, "time", ["<second>"]],
      "<year>": [["y", "yr", "year", "years", "annum"], 31556926, "time", ["<second>"]],
      "<decade>": [["decade", "decades"], 315569260, "time", ["<second>"]],
      "<century>": [["century", "centuries"], 3155692600, "time", ["<second>"]],
      /* pressure */
      "<pascal>": [["Pa", "pascal", "Pascal"], 1.0, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<bar>": [["bar", "bars"], 100000, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<mmHg>": [["mmHg"], 133.322368, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<inHg>": [["inHg"], 3386.3881472, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<torr>": [["torr"], 133.322368, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<atm>": [["atm", "ATM", "atmosphere", "atmospheres"], 101325, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<psi>": [["psi"], 6894.76, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<cmh2o>": [["cmH2O", "cmh2o"], 98.0638, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      "<inh2o>": [["inH2O", "inh2o"], 249.082052, "pressure", ["<kilogram>"], ["<meter>", "<second>", "<second>"]],
      /* viscosity */
      "<poise>": [["P", "poise"], 0.1, "viscosity", ["<kilogram>"], ["<meter>", "<second>"]],
      "<stokes>": [["St", "stokes"], 1e-4, "viscosity", ["<meter>", "<meter>"], ["<second>"]],
      /* substance */
      "<mole>": [["mol", "mole"], 1.0, "substance", ["<mole>"]],
      /* molar_concentration */
      "<molar>": [["M", "molar"], 1000, "molar_concentration", ["<mole>"], ["<meter>", "<meter>", "<meter>"]],
      "<wtpercent>": [["wt%", "wtpercent"], 10, "molar_concentration", ["<kilogram>"], ["<meter>", "<meter>", "<meter>"]],
      /* activity */
      "<katal>": [["kat", "katal", "Katal"], 1.0, "activity", ["<mole>"], ["<second>"]],
      "<unit>": [["U", "enzUnit", "unit"], 16.667e-16, "activity", ["<mole>"], ["<second>"]],
      /* capacitance */
      "<farad>": [["F", "farad", "Farad"], 1.0, "capacitance", ["<second>", "<second>", "<second>", "<second>", "<ampere>", "<ampere>"], ["<meter>", "<meter>", "<kilogram>"]],
      /* charge */
      "<coulomb>": [["C", "coulomb", "Coulomb"], 1.0, "charge", ["<ampere>", "<second>"]],
      "<Ah>": [["Ah"], 3600, "charge", ["<ampere>", "<second>"]],
      /* current */
      "<ampere>": [["A", "Ampere", "ampere", "amp", "amps"], 1.0, "current", ["<ampere>"]],
      /* conductance */
      "<siemens>": [["S", "Siemens", "siemens"], 1.0, "conductance", ["<second>", "<second>", "<second>", "<ampere>", "<ampere>"], ["<kilogram>", "<meter>", "<meter>"]],
      /* inductance */
      "<henry>": [["H", "Henry", "henry"], 1.0, "inductance", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<ampere>", "<ampere>"]],
      /* potential */
      "<volt>": [["V", "Volt", "volt", "volts"], 1.0, "potential", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<second>", "<ampere>"]],
      /* resistance */
      "<ohm>": [["Ohm", "ohm", "\u03A9" /*Ω as greek letter*/, "\u2126" /*Ω as ohm sign*/], 1.0, "resistance", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<second>", "<ampere>", "<ampere>"]],
      /* magnetism */
      "<weber>": [["Wb", "weber", "webers"], 1.0, "magnetism", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<ampere>"]],
      "<tesla>": [["T", "tesla", "teslas"], 1.0, "magnetism", ["<kilogram>"], ["<second>", "<second>", "<ampere>"]],
      "<gauss>": [["G", "gauss"], 1e-4, "magnetism", ["<kilogram>"], ["<second>", "<second>", "<ampere>"]],
      "<maxwell>": [["Mx", "maxwell", "maxwells"], 1e-8, "magnetism", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>", "<ampere>"]],
      "<oersted>": [["Oe", "oersted", "oersteds"], 250.0 / Math.PI, "magnetism", ["<ampere>"], ["<meter>"]],
      /* energy */
      "<joule>": [["J", "joule", "Joule", "joules", "Joules"], 1.0, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<erg>": [["erg", "ergs"], 1e-7, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<btu>": [["BTU", "btu", "BTUs"], 1055.056, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<calorie>": [["cal", "calorie", "calories"], 4.18400, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<Calorie>": [["Cal", "Calorie", "Calories"], 4184.00, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<therm-US>": [["th", "therm", "therms", "Therm", "therm-US"], 105480400, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<Wh>": [["Wh"], 3600, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      "<electronvolt>": [["eV", "electronvolt", "electronvolts"], 1.602176634E-19, "energy", ["<meter>", "<meter>", "<kilogram>"], ["<second>", "<second>"]],
      /* force */
      "<newton>": [["N", "Newton", "newton"], 1.0, "force", ["<kilogram>", "<meter>"], ["<second>", "<second>"]],
      "<dyne>": [["dyn", "dyne"], 1e-5, "force", ["<kilogram>", "<meter>"], ["<second>", "<second>"]],
      "<pound-force>": [["lbf", "pound-force"], 4.448222, "force", ["<kilogram>", "<meter>"], ["<second>", "<second>"]],
      /* frequency */
      "<hertz>": [["Hz", "hertz", "Hertz"], 1.0, "frequency", ["<1>"], ["<second>"]],
      /* angle */
      "<radian>": [["rad", "radian", "radians"], 1.0, "angle", ["<radian>"]],
      "<degree>": [["deg", "degree", "degrees"], Math.PI / 180.0, "angle", ["<radian>"]],
      "<arcminute>": [["arcmin", "arcminute", "arcminutes"], Math.PI / 10800.0, "angle", ["<radian>"]],
      "<arcsecond>": [["arcsec", "arcsecond", "arcseconds"], Math.PI / 648000.0, "angle", ["<radian>"]],
      "<gradian>": [["gon", "grad", "gradian", "grads"], Math.PI / 200.0, "angle", ["<radian>"]],
      "<steradian>": [["sr", "steradian", "steradians"], 1.0, "solid_angle", ["<steradian>"]],
      /* rotation */
      "<rotation>": [["rotation"], 2.0 * Math.PI, "angle", ["<radian>"]],
      "<rpm>": [["rpm"], 2.0 * Math.PI / 60.0, "angular_velocity", ["<radian>"], ["<second>"]],
      /* information */
      "<byte>": [["B", "byte", "bytes"], 1.0, "information", ["<byte>"]],
      "<bit>": [["b", "bit", "bits"], 0.125, "information", ["<byte>"]],
      /* information rate */
      "<Bps>": [["Bps"], 1.0, "information_rate", ["<byte>"], ["<second>"]],
      "<bps>": [["bps"], 0.125, "information_rate", ["<byte>"], ["<second>"]],
      /* currency */
      "<dollar>": [["USD", "dollar"], 1.0, "currency", ["<dollar>"]],
      "<cents>": [["cents"], 0.01, "currency", ["<dollar>"]],
      /* luminosity */
      "<candela>": [["cd", "candela"], 1.0, "luminosity", ["<candela>"]],
      "<lumen>": [["lm", "lumen"], 1.0, "luminous_power", ["<candela>", "<steradian>"]],
      "<lux>": [["lux"], 1.0, "illuminance", ["<candela>", "<steradian>"], ["<meter>", "<meter>"]],
      /* power */
      "<watt>": [["W", "watt", "watts"], 1.0, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
      "<volt-ampere>": [["VA", "volt-ampere"], 1.0, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
      "<volt-ampere-reactive>": [["var", "Var", "VAr", "VAR", "volt-ampere-reactive"], 1.0, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
      "<horsepower>": [["hp", "horsepower"], 745.699872, "power", ["<kilogram>", "<meter>", "<meter>"], ["<second>", "<second>", "<second>"]],
      /* radiation */
      "<gray>": [["Gy", "gray", "grays"], 1.0, "radiation", ["<meter>", "<meter>"], ["<second>", "<second>"]],
      "<roentgen>": [["R", "roentgen"], 0.009330, "radiation", ["<meter>", "<meter>"], ["<second>", "<second>"]],
      "<sievert>": [["Sv", "sievert", "sieverts"], 1.0, "radiation", ["<meter>", "<meter>"], ["<second>", "<second>"]],
      "<becquerel>": [["Bq", "becquerel", "becquerels"], 1.0, "radiation", ["<1>"], ["<second>"]],
      "<curie>": [["Ci", "curie", "curies"], 3.7e10, "radiation", ["<1>"], ["<second>"]],
      /* rate */
      "<cpm>": [["cpm"], 1.0 / 60.0, "rate", ["<count>"], ["<second>"]],
      "<dpm>": [["dpm"], 1.0 / 60.0, "rate", ["<count>"], ["<second>"]],
      "<bpm>": [["bpm"], 1.0 / 60.0, "rate", ["<count>"], ["<second>"]],
      /* resolution / typography */
      "<dot>": [["dot", "dots"], 1, "resolution", ["<each>"]],
      "<pixel>": [["pixel", "px"], 1, "resolution", ["<each>"]],
      "<ppi>": [["ppi"], 1, "resolution", ["<pixel>"], ["<inch>"]],
      "<dpi>": [["dpi"], 1, "typography", ["<dot>"], ["<inch>"]],
      /* other */
      "<cell>": [["cells", "cell"], 1, "counting", ["<each>"]],
      "<each>": [["each"], 1.0, "counting", ["<each>"]],
      "<count>": [["count"], 1.0, "counting", ["<each>"]],
      "<base-pair>": [["bp", "base-pair"], 1.0, "counting", ["<each>"]],
      "<nucleotide>": [["nt", "nucleotide"], 1.0, "counting", ["<each>"]],
      "<molecule>": [["molecule", "molecules"], 1.0, "counting", ["<1>"]],
      "<dozen>": [["doz", "dz", "dozen"], 12.0, "prefix_only", ["<each>"]],
      "<percent>": [["%", "percent"], 0.01, "prefix_only", ["<1>"]],
      "<ppm>": [["ppm"], 1e-6, "prefix_only", ["<1>"]],
      "<ppb>": [["ppb"], 1e-9, "prefix_only", ["<1>"]],
      "<ppt>": [["ppt"], 1e-12, "prefix_only", ["<1>"]],
      "<ppq>": [["ppq"], 1e-15, "prefix_only", ["<1>"]],
      "<gross>": [["gr", "gross"], 144.0, "prefix_only", ["<dozen>", "<dozen>"]],
      "<decibel>": [["dB", "decibel", "decibels"], 1.0, "logarithmic", ["<decibel>"]]
    };
    var BASE_UNITS = ["<meter>", "<kilogram>", "<second>", "<mole>", "<ampere>", "<radian>", "<kelvin>", "<temp-K>", "<byte>", "<dollar>", "<candela>", "<each>", "<steradian>", "<decibel>"];
    var UNITY = "<1>";
    var UNITY_ARRAY = [UNITY];

    // Setup

    /**
     * Asserts unit definition is valid
     *
     * @param {string} unitDef - Name of unit to test
     * @param {Object} definition - Definition of unit to test
     *
     * @returns {void}
     * @throws {QtyError} if unit definition is not valid
     */
    function validateUnitDefinition(unitDef, definition) {
      var scalar = definition[1];
      var numerator = definition[3] || [];
      var denominator = definition[4] || [];
      if (!isNumber(scalar)) {
        throw new QtyError(unitDef + ": Invalid unit definition. " + "'scalar' must be a number");
      }
      numerator.forEach(function (unit) {
        if (UNITS[unit] === undefined) {
          throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'numerator' is not recognized");
        }
      });
      denominator.forEach(function (unit) {
        if (UNITS[unit] === undefined) {
          throw new QtyError(unitDef + ": Invalid unit definition. " + "Unit " + unit + " in 'denominator' is not recognized");
        }
      });
    }
    var PREFIX_VALUES = {};
    var PREFIX_MAP = {};
    var UNIT_VALUES = {};
    var UNIT_MAP = {};
    var OUTPUT_MAP = {};
    for (var unitDef in UNITS) {
      if (UNITS.hasOwnProperty(unitDef)) {
        var definition = UNITS[unitDef];
        if (definition[2] === "prefix") {
          PREFIX_VALUES[unitDef] = definition[1];
          for (var i = 0; i < definition[0].length; i++) {
            PREFIX_MAP[definition[0][i]] = unitDef;
          }
        } else {
          validateUnitDefinition(unitDef, definition);
          UNIT_VALUES[unitDef] = {
            scalar: definition[1],
            numerator: definition[3],
            denominator: definition[4]
          };
          for (var j = 0; j < definition[0].length; j++) {
            UNIT_MAP[definition[0][j]] = unitDef;
          }
        }
        OUTPUT_MAP[unitDef] = definition[0][0];
      }
    }

    /**
     * Returns a list of available units of kind
     *
     * @param {string} [kind] - kind of units
     * @returns {array} names of units
     * @throws {QtyError} if kind is unknown
     */
    function getUnits(kind) {
      var i;
      var units = [];
      var unitKeys = Object.keys(UNITS);
      if (typeof kind === "undefined") {
        for (i = 0; i < unitKeys.length; i++) {
          if (["", "prefix"].indexOf(UNITS[unitKeys[i]][2]) === -1) {
            units.push(unitKeys[i].substr(1, unitKeys[i].length - 2));
          }
        }
      } else if (this.getKinds().indexOf(kind) === -1) {
        throw new QtyError("Kind not recognized");
      } else {
        for (i = 0; i < unitKeys.length; i++) {
          if (UNITS[unitKeys[i]][2] === kind) {
            units.push(unitKeys[i].substr(1, unitKeys[i].length - 2));
          }
        }
      }
      return units.sort(function (a, b) {
        if (a.toLowerCase() < b.toLowerCase()) {
          return -1;
        }
        if (a.toLowerCase() > b.toLowerCase()) {
          return 1;
        }
        return 0;
      });
    }

    /**
     * Returns a list of alternative names for a unit
     *
     * @param {string} unitName - name of unit
     * @returns {string[]} aliases for unit
     * @throws {QtyError} if unit is unknown
     */
    function getAliases(unitName) {
      if (!UNIT_MAP[unitName]) {
        throw new QtyError("Unit not recognized");
      }
      return UNITS[UNIT_MAP[unitName]][0];
    }
    var SIGNATURE_VECTOR = ["length", "time", "temperature", "mass", "current", "substance", "luminosity", "currency", "information", "angle"];

    /*
    calculates the unit signature id for use in comparing compatible units and simplification
    the signature is based on a simple classification of units and is based on the following publication
     Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering,
    21(8), Aug 1995, pp.651-661
    doi://10.1109/32.403789
    http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel1/32/9079/00403789.pdf?isnumber=9079&prod=JNL&arnumber=403789&arSt=651&ared=661&arAuthor=Novak%2C+G.S.%2C+Jr.
    */
    function unitSignature() {
      if (this.signature) {
        return this.signature;
      }
      var vector = unitSignatureVector.call(this);
      for (var i = 0; i < vector.length; i++) {
        vector[i] *= Math.pow(20, i);
      }
      return vector.reduce(function (previous, current) {
        return previous + current;
      }, 0);
    }

    // calculates the unit signature vector used by unit_signature
    function unitSignatureVector() {
      if (!this.isBase()) {
        return unitSignatureVector.call(this.toBase());
      }
      var vector = new Array(SIGNATURE_VECTOR.length);
      for (var i = 0; i < vector.length; i++) {
        vector[i] = 0;
      }
      var r, n;
      for (var j = 0; j < this.numerator.length; j++) {
        if (r = UNITS[this.numerator[j]]) {
          n = SIGNATURE_VECTOR.indexOf(r[2]);
          if (n >= 0) {
            vector[n] = vector[n] + 1;
          }
        }
      }
      for (var k = 0; k < this.denominator.length; k++) {
        if (r = UNITS[this.denominator[k]]) {
          n = SIGNATURE_VECTOR.indexOf(r[2]);
          if (n >= 0) {
            vector[n] = vector[n] - 1;
          }
        }
      }
      return vector;
    }
    var SIGN = "[+-]";
    var INTEGER = "\\d+";
    var SIGNED_INTEGER = SIGN + "?" + INTEGER;
    var FRACTION = "\\." + INTEGER;
    var FLOAT = "(?:" + INTEGER + "(?:" + FRACTION + ")?" + ")" + "|" + "(?:" + FRACTION + ")";
    var EXPONENT = "[Ee]" + SIGNED_INTEGER;
    var SCI_NUMBER = "(?:" + FLOAT + ")(?:" + EXPONENT + ")?";
    var SIGNED_NUMBER = SIGN + "?\\s*" + SCI_NUMBER;
    var QTY_STRING = "(" + SIGNED_NUMBER + ")?" + "\\s*([^/]*)(?:\/(.+))?";
    var QTY_STRING_REGEX = new RegExp("^" + QTY_STRING + "$");
    var POWER_OP = "\\^|\\*{2}";
    // Allow unit powers representing scalar, length, area, volume; 4 is for some
    // special case representations in SI base units.
    var SAFE_POWER = "[01234]";
    var TOP_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(-?" + SAFE_POWER + "(?![a-zA-Z]))");
    var BOTTOM_REGEX = new RegExp("([^ \\*\\d]+?)(?:" + POWER_OP + ")?(" + SAFE_POWER + "(?![a-zA-Z]))");

    /* parse a string into a unit object.
     * Typical formats like :
     * "5.6 kg*m/s^2"
     * "5.6 kg*m*s^-2"
     * "5.6 kilogram*meter*second^-2"
     * "2.2 kPa"
     * "37 degC"
     * "1"  -- creates a unitless constant with value 1
     * "GPa"  -- creates a unit with scalar 1 with units 'GPa'
     * 6'4"  -- recognized as 6 feet + 4 inches
     * 8 lbs 8 oz -- recognized as 8 lbs + 8 ounces
     */
    function parse(val) {
      if (!isString(val)) {
        val = val.toString();
      }
      val = val.trim();
      var result = QTY_STRING_REGEX.exec(val);
      if (!result) {
        throw new QtyError(val + ": Quantity not recognized");
      }
      var scalarMatch = result[1];
      if (scalarMatch) {
        // Allow whitespaces between sign and scalar for loose parsing
        scalarMatch = scalarMatch.replace(/\s/g, "");
        this.scalar = parseFloat(scalarMatch);
      } else {
        this.scalar = 1;
      }
      var top = result[2];
      var bottom = result[3];
      var n, x, nx;
      // TODO DRY me
      while (result = TOP_REGEX.exec(top)) {
        n = parseFloat(result[2]);
        if (isNaN(n)) {
          // Prevents infinite loops
          throw new QtyError("Unit exponent is not a number");
        }
        // Disallow unrecognized unit even if exponent is 0
        if (n === 0 && !UNIT_TEST_REGEX.test(result[1])) {
          throw new QtyError("Unit not recognized");
        }
        x = result[1] + " ";
        nx = "";
        for (var i = 0; i < Math.abs(n); i++) {
          nx += x;
        }
        if (n >= 0) {
          top = top.replace(result[0], nx);
        } else {
          bottom = bottom ? bottom + nx : nx;
          top = top.replace(result[0], "");
        }
      }
      while (result = BOTTOM_REGEX.exec(bottom)) {
        n = parseFloat(result[2]);
        if (isNaN(n)) {
          // Prevents infinite loops
          throw new QtyError("Unit exponent is not a number");
        }
        // Disallow unrecognized unit even if exponent is 0
        if (n === 0 && !UNIT_TEST_REGEX.test(result[1])) {
          throw new QtyError("Unit not recognized");
        }
        x = result[1] + " ";
        nx = "";
        for (var j = 0; j < n; j++) {
          nx += x;
        }
        bottom = bottom.replace(result[0], nx);
      }
      if (top) {
        this.numerator = parseUnits(top.trim());
      }
      if (bottom) {
        this.denominator = parseUnits(bottom.trim());
      }
    }
    var PREFIX_REGEX = Object.keys(PREFIX_MAP).sort(function (a, b) {
      return b.length - a.length;
    }).join("|");
    var UNIT_REGEX = Object.keys(UNIT_MAP).sort(function (a, b) {
      return b.length - a.length;
    }).join("|");
    /*
     * Minimal boundary regex to support units with Unicode characters
     * \b only works for ASCII
     */
    var BOUNDARY_REGEX = "\\b|$";
    var UNIT_MATCH = "(" + PREFIX_REGEX + ")??(" + UNIT_REGEX + ")(?:" + BOUNDARY_REGEX + ")";
    var UNIT_TEST_REGEX = new RegExp("^\\s*(" + UNIT_MATCH + "[\\s\\*]*)+$");
    var UNIT_MATCH_REGEX = new RegExp(UNIT_MATCH, "g"); // g flag for multiple occurences
    var parsedUnitsCache = {};
    /**
     * Parses and converts units string to normalized unit array.
     * Result is cached to speed up next calls.
     *
     * @param {string} units Units string
     * @returns {string[]} Array of normalized units
     *
     * @example
     * // Returns ["<second>", "<meter>", "<second>"]
     * parseUnits("s m s");
     *
     */
    function parseUnits(units) {
      var cached = parsedUnitsCache[units];
      if (cached) {
        return cached;
      }
      var unitMatch,
        normalizedUnits = [];

      // Scan
      if (!UNIT_TEST_REGEX.test(units)) {
        throw new QtyError("Unit not recognized");
      }
      while (unitMatch = UNIT_MATCH_REGEX.exec(units)) {
        normalizedUnits.push(unitMatch.slice(1));
      }
      normalizedUnits = normalizedUnits.map(function (item) {
        return PREFIX_MAP[item[0]] ? [PREFIX_MAP[item[0]], UNIT_MAP[item[1]]] : [UNIT_MAP[item[1]]];
      });

      // Flatten and remove null elements
      normalizedUnits = normalizedUnits.reduce(function (a, b) {
        return a.concat(b);
      }, []);
      normalizedUnits = normalizedUnits.filter(function (item) {
        return item;
      });
      parsedUnitsCache[units] = normalizedUnits;
      return normalizedUnits;
    }

    /**
     * Parses a string as a quantity
     * @param {string} value - quantity as text
     * @throws if value is not a string
     * @returns {Qty|null} Parsed quantity or null if unrecognized
     */
    function globalParse(value) {
      if (!isString(value)) {
        throw new QtyError("Argument should be a string");
      }
      try {
        return this(value);
      } catch (e) {
        return null;
      }
    }

    /**
     * Tests if a value is a Qty instance
     *
     * @param {*} value - Value to test
     *
     * @returns {boolean} true if value is a Qty instance, false otherwise
     */
    function isQty(value) {
      return value instanceof Qty;
    }
    function Qty(initValue, initUnits) {
      assertValidConstructorArgs.apply(null, arguments);
      if (!isQty(this)) {
        return new Qty(initValue, initUnits);
      }
      this.scalar = null;
      this.baseScalar = null;
      this.signature = null;
      this._conversionCache = {};
      this.numerator = UNITY_ARRAY;
      this.denominator = UNITY_ARRAY;
      if (isDefinitionObject(initValue)) {
        this.scalar = initValue.scalar;
        this.numerator = initValue.numerator && initValue.numerator.length !== 0 ? initValue.numerator : UNITY_ARRAY;
        this.denominator = initValue.denominator && initValue.denominator.length !== 0 ? initValue.denominator : UNITY_ARRAY;
      } else if (initUnits) {
        parse.call(this, initUnits);
        this.scalar = initValue;
      } else {
        parse.call(this, initValue);
      }

      // math with temperatures is very limited
      if (this.denominator.join("*").indexOf("temp") >= 0) {
        throw new QtyError("Cannot divide with temperatures");
      }
      if (this.numerator.join("*").indexOf("temp") >= 0) {
        if (this.numerator.length > 1) {
          throw new QtyError("Cannot multiply by temperatures");
        }
        if (!compareArray(this.denominator, UNITY_ARRAY)) {
          throw new QtyError("Cannot divide with temperatures");
        }
      }
      this.initValue = initValue;
      updateBaseScalar.call(this);
      if (this.isTemperature() && this.baseScalar < 0) {
        throw new QtyError("Temperatures must not be less than absolute zero");
      }
    }
    Qty.prototype = {
      // Properly set up constructor
      constructor: Qty
    };

    /**
     * Asserts constructor arguments are valid
     *
     * @param {*} value - Value to test
     * @param {string} [units] - Optional units when value is passed as a number
     *
     * @returns {void}
     * @throws {QtyError} if constructor arguments are invalid
     */
    function assertValidConstructorArgs(value, units) {
      if (units) {
        if (!(isNumber(value) && isString(units))) {
          throw new QtyError("Only number accepted as initialization value " + "when units are explicitly provided");
        }
      } else {
        if (!(isString(value) || isNumber(value) || isQty(value) || isDefinitionObject(value))) {
          throw new QtyError("Only string, number or quantity accepted as " + "single initialization value");
        }
      }
    }

    /**
     * Tests if a value is a Qty definition object
     *
     * @param {*} value - Value to test
     *
     * @returns {boolean} true if value is a definition object, false otherwise
     */
    function isDefinitionObject(value) {
      return value && typeof value === "object" && value.hasOwnProperty("scalar");
    }
    function updateBaseScalar() {
      if (this.baseScalar) {
        return this.baseScalar;
      }
      if (this.isBase()) {
        this.baseScalar = this.scalar;
        this.signature = unitSignature.call(this);
      } else {
        var base = this.toBase();
        this.baseScalar = base.scalar;
        this.signature = base.signature;
      }
    }
    var KINDS = {
      "-312078": "elastance",
      "-312058": "resistance",
      "-312038": "inductance",
      "-152058": "potential",
      "-152040": "magnetism",
      "-152038": "magnetism",
      "-7997": "specific_volume",
      "-79": "snap",
      "-59": "jolt",
      "-39": "acceleration",
      "-38": "radiation",
      "-20": "frequency",
      "-19": "speed",
      "-18": "viscosity",
      "-17": "volumetric_flow",
      "-1": "wavenumber",
      "0": "unitless",
      "1": "length",
      "2": "area",
      "3": "volume",
      "20": "time",
      "400": "temperature",
      "7941": "yank",
      "7942": "power",
      "7959": "pressure",
      "7961": "force",
      "7962": "energy",
      "7979": "viscosity",
      "7981": "momentum",
      "7982": "angular_momentum",
      "7997": "density",
      "7998": "area_density",
      "8000": "mass",
      "152020": "radiation_exposure",
      "159999": "magnetism",
      "160000": "current",
      "160020": "charge",
      "312058": "conductance",
      "312078": "capacitance",
      "3199980": "activity",
      "3199997": "molar_concentration",
      "3200000": "substance",
      "63999998": "illuminance",
      "64000000": "luminous_power",
      "1280000000": "currency",
      "25599999980": "information_rate",
      "25600000000": "information",
      "511999999980": "angular_velocity",
      "512000000000": "angle"
    };

    /**
     * Returns the list of available well-known kinds of units, e.g.
     * "radiation" or "length".
     *
     * @returns {string[]} names of kinds of units
     */
    function getKinds() {
      return uniq(Object.keys(KINDS).map(function (knownSignature) {
        return KINDS[knownSignature];
      }));
    }
    Qty.prototype.kind = function () {
      return KINDS[this.signature.toString()];
    };
    assign(Qty.prototype, {
      isDegrees: function () {
        // signature may not have been calculated yet
        return (this.signature === null || this.signature === 400) && this.numerator.length === 1 && compareArray(this.denominator, UNITY_ARRAY) && (this.numerator[0].match(/<temp-[CFRK]>/) || this.numerator[0].match(/<(kelvin|celsius|rankine|fahrenheit)>/));
      },
      isTemperature: function () {
        return this.isDegrees() && this.numerator[0].match(/<temp-[CFRK]>/);
      }
    });
    function subtractTemperatures(lhs, rhs) {
      var lhsUnits = lhs.units();
      var rhsConverted = rhs.to(lhsUnits);
      var dstDegrees = Qty(getDegreeUnits(lhsUnits));
      return Qty({
        "scalar": lhs.scalar - rhsConverted.scalar,
        "numerator": dstDegrees.numerator,
        "denominator": dstDegrees.denominator
      });
    }
    function subtractTempDegrees(temp, deg) {
      var tempDegrees = deg.to(getDegreeUnits(temp.units()));
      return Qty({
        "scalar": temp.scalar - tempDegrees.scalar,
        "numerator": temp.numerator,
        "denominator": temp.denominator
      });
    }
    function addTempDegrees(temp, deg) {
      var tempDegrees = deg.to(getDegreeUnits(temp.units()));
      return Qty({
        "scalar": temp.scalar + tempDegrees.scalar,
        "numerator": temp.numerator,
        "denominator": temp.denominator
      });
    }
    function getDegreeUnits(units) {
      if (units === "tempK") {
        return "degK";
      } else if (units === "tempC") {
        return "degC";
      } else if (units === "tempF") {
        return "degF";
      } else if (units === "tempR") {
        return "degR";
      } else {
        throw new QtyError("Unknown type for temp conversion from: " + units);
      }
    }
    function toDegrees(src, dst) {
      var srcDegK = toDegK(src);
      var dstUnits = dst.units();
      var dstScalar;
      if (dstUnits === "degK") {
        dstScalar = srcDegK.scalar;
      } else if (dstUnits === "degC") {
        dstScalar = srcDegK.scalar;
      } else if (dstUnits === "degF") {
        dstScalar = srcDegK.scalar * 9 / 5;
      } else if (dstUnits === "degR") {
        dstScalar = srcDegK.scalar * 9 / 5;
      } else {
        throw new QtyError("Unknown type for degree conversion to: " + dstUnits);
      }
      return Qty({
        "scalar": dstScalar,
        "numerator": dst.numerator,
        "denominator": dst.denominator
      });
    }
    function toDegK(qty) {
      var units = qty.units();
      var q;
      if (units.match(/(deg)[CFRK]/)) {
        q = qty.baseScalar;
      } else if (units === "tempK") {
        q = qty.scalar;
      } else if (units === "tempC") {
        q = qty.scalar;
      } else if (units === "tempF") {
        q = qty.scalar * 5 / 9;
      } else if (units === "tempR") {
        q = qty.scalar * 5 / 9;
      } else {
        throw new QtyError("Unknown type for temp conversion from: " + units);
      }
      return Qty({
        "scalar": q,
        "numerator": ["<kelvin>"],
        "denominator": UNITY_ARRAY
      });
    }
    function toTemp(src, dst) {
      var dstUnits = dst.units();
      var dstScalar;
      if (dstUnits === "tempK") {
        dstScalar = src.baseScalar;
      } else if (dstUnits === "tempC") {
        dstScalar = src.baseScalar - 273.15;
      } else if (dstUnits === "tempF") {
        dstScalar = src.baseScalar * 9 / 5 - 459.67;
      } else if (dstUnits === "tempR") {
        dstScalar = src.baseScalar * 9 / 5;
      } else {
        throw new QtyError("Unknown type for temp conversion to: " + dstUnits);
      }
      return Qty({
        "scalar": dstScalar,
        "numerator": dst.numerator,
        "denominator": dst.denominator
      });
    }
    function toTempK(qty) {
      var units = qty.units();
      var q;
      if (units.match(/(deg)[CFRK]/)) {
        q = qty.baseScalar;
      } else if (units === "tempK") {
        q = qty.scalar;
      } else if (units === "tempC") {
        q = qty.scalar + 273.15;
      } else if (units === "tempF") {
        q = (qty.scalar + 459.67) * 5 / 9;
      } else if (units === "tempR") {
        q = qty.scalar * 5 / 9;
      } else {
        throw new QtyError("Unknown type for temp conversion from: " + units);
      }
      return Qty({
        "scalar": q,
        "numerator": ["<temp-K>"],
        "denominator": UNITY_ARRAY
      });
    }
    assign(Qty.prototype, {
      /**
       * Converts to other compatible units.
       * Instance's converted quantities are cached for faster subsequent calls.
       *
       * @param {(string|Qty)} other - Target units as string or retrieved from
       *                               other Qty instance (scalar is ignored)
       *
       * @returns {Qty} New converted Qty instance with target units
       *
       * @throws {QtyError} if target units are incompatible
       *
       * @example
       * var weight = Qty("25 kg");
       * weight.to("lb"); // => Qty("55.11556554621939 lbs");
       * weight.to(Qty("3 g")); // => Qty("25000 g"); // scalar of passed Qty is ignored
       */
      to: function (other) {
        var cached, target;
        if (other === undefined || other === null) {
          return this;
        }
        if (!isString(other)) {
          return this.to(other.units());
        }
        cached = this._conversionCache[other];
        if (cached) {
          return cached;
        }

        // Instantiating target to normalize units
        target = Qty(other);
        if (target.units() === this.units()) {
          return this;
        }
        if (!this.isCompatible(target)) {
          if (this.isInverse(target)) {
            target = this.inverse().to(other);
          } else {
            throwIncompatibleUnits(this.units(), target.units());
          }
        } else {
          if (target.isTemperature()) {
            target = toTemp(this, target);
          } else if (target.isDegrees()) {
            target = toDegrees(this, target);
          } else {
            var q = divSafe(this.baseScalar, target.baseScalar);
            target = Qty({
              "scalar": q,
              "numerator": target.numerator,
              "denominator": target.denominator
            });
          }
        }
        this._conversionCache[other] = target;
        return target;
      },
      // convert to base SI units
      // results of the conversion are cached so subsequent calls to this will be fast
      toBase: function () {
        if (this.isBase()) {
          return this;
        }
        if (this.isTemperature()) {
          return toTempK(this);
        }
        var cached = baseUnitCache[this.units()];
        if (!cached) {
          cached = toBaseUnits(this.numerator, this.denominator);
          baseUnitCache[this.units()] = cached;
        }
        return cached.mul(this.scalar);
      },
      // Converts the unit back to a float if it is unitless.  Otherwise raises an exception
      toFloat: function () {
        if (this.isUnitless()) {
          return this.scalar;
        }
        throw new QtyError("Can't convert to Float unless unitless.  Use Unit#scalar");
      },
      /**
       * Returns the nearest multiple of quantity passed as
       * precision
       *
       * @param {(Qty|string|number)} precQuantity - Quantity, string formated
       *   quantity or number as expected precision
       *
       * @returns {Qty} Nearest multiple of precQuantity
       *
       * @example
       * Qty('5.5 ft').toPrec('2 ft'); // returns 6 ft
       * Qty('0.8 cu').toPrec('0.25 cu'); // returns 0.75 cu
       * Qty('6.3782 m').toPrec('cm'); // returns 6.38 m
       * Qty('1.146 MPa').toPrec('0.1 bar'); // returns 1.15 MPa
       *
       */
      toPrec: function (precQuantity) {
        if (isString(precQuantity)) {
          precQuantity = Qty(precQuantity);
        }
        if (isNumber(precQuantity)) {
          precQuantity = Qty(precQuantity + " " + this.units());
        }
        if (!this.isUnitless()) {
          precQuantity = precQuantity.to(this.units());
        } else if (!precQuantity.isUnitless()) {
          throwIncompatibleUnits(this.units(), precQuantity.units());
        }
        if (precQuantity.scalar === 0) {
          throw new QtyError("Divide by zero");
        }
        var precRoundedResult = mulSafe(Math.round(this.scalar / precQuantity.scalar), precQuantity.scalar);
        return Qty(precRoundedResult + this.units());
      }
    });

    /**
     * Configures and returns a fast function to convert
     * Number values from units to others.
     * Useful to efficiently convert large array of values
     * with same units into others with iterative methods.
     * Does not take care of rounding issues.
     *
     * @param {string} srcUnits Units of values to convert
     * @param {string} dstUnits Units to convert to
     *
     * @returns {Function} Converting function accepting Number value
     *   and returning converted value
     *
     * @throws "Incompatible units" if units are incompatible
     *
     * @example
     * // Converting large array of numbers with the same units
     * // into other units
     * var converter = Qty.swiftConverter("m/h", "ft/s");
     * var convertedSerie = largeSerie.map(converter);
     *
     */
    function swiftConverter(srcUnits, dstUnits) {
      var srcQty = Qty(srcUnits);
      var dstQty = Qty(dstUnits);
      if (srcQty.eq(dstQty)) {
        return identity;
      }
      var convert;
      if (!srcQty.isTemperature()) {
        convert = function (value) {
          return value * srcQty.baseScalar / dstQty.baseScalar;
        };
      } else {
        convert = function (value) {
          // TODO Not optimized
          return srcQty.mul(value).to(dstQty).scalar;
        };
      }
      return function converter(value) {
        var i, length, result;
        if (!Array.isArray(value)) {
          return convert(value);
        } else {
          length = value.length;
          result = [];
          for (i = 0; i < length; i++) {
            result.push(convert(value[i]));
          }
          return result;
        }
      };
    }
    var baseUnitCache = {};
    function toBaseUnits(numerator, denominator) {
      var num = [];
      var den = [];
      var q = 1;
      var unit;
      for (var i = 0; i < numerator.length; i++) {
        unit = numerator[i];
        if (PREFIX_VALUES[unit]) {
          // workaround to fix
          // 0.1 * 0.1 => 0.010000000000000002
          q = mulSafe(q, PREFIX_VALUES[unit]);
        } else {
          if (UNIT_VALUES[unit]) {
            q *= UNIT_VALUES[unit].scalar;
            if (UNIT_VALUES[unit].numerator) {
              num.push(UNIT_VALUES[unit].numerator);
            }
            if (UNIT_VALUES[unit].denominator) {
              den.push(UNIT_VALUES[unit].denominator);
            }
          }
        }
      }
      for (var j = 0; j < denominator.length; j++) {
        unit = denominator[j];
        if (PREFIX_VALUES[unit]) {
          q /= PREFIX_VALUES[unit];
        } else {
          if (UNIT_VALUES[unit]) {
            q /= UNIT_VALUES[unit].scalar;
            if (UNIT_VALUES[unit].numerator) {
              den.push(UNIT_VALUES[unit].numerator);
            }
            if (UNIT_VALUES[unit].denominator) {
              num.push(UNIT_VALUES[unit].denominator);
            }
          }
        }
      }

      // Flatten
      num = num.reduce(function (a, b) {
        return a.concat(b);
      }, []);
      den = den.reduce(function (a, b) {
        return a.concat(b);
      }, []);
      return Qty({
        "scalar": q,
        "numerator": num,
        "denominator": den
      });
    }
    Qty.parse = globalParse;
    Qty.getUnits = getUnits;
    Qty.getAliases = getAliases;
    Qty.mulSafe = mulSafe;
    Qty.divSafe = divSafe;
    Qty.getKinds = getKinds;
    Qty.swiftConverter = swiftConverter;
    Qty.Error = QtyError;
    assign(Qty.prototype, {
      // Returns new instance with units of this
      add: function (other) {
        if (isString(other)) {
          other = Qty(other);
        }
        if (!this.isCompatible(other)) {
          throwIncompatibleUnits(this.units(), other.units());
        }
        if (this.isTemperature() && other.isTemperature()) {
          throw new QtyError("Cannot add two temperatures");
        } else if (this.isTemperature()) {
          return addTempDegrees(this, other);
        } else if (other.isTemperature()) {
          return addTempDegrees(other, this);
        }
        return Qty({
          "scalar": this.scalar + other.to(this).scalar,
          "numerator": this.numerator,
          "denominator": this.denominator
        });
      },
      sub: function (other) {
        if (isString(other)) {
          other = Qty(other);
        }
        if (!this.isCompatible(other)) {
          throwIncompatibleUnits(this.units(), other.units());
        }
        if (this.isTemperature() && other.isTemperature()) {
          return subtractTemperatures(this, other);
        } else if (this.isTemperature()) {
          return subtractTempDegrees(this, other);
        } else if (other.isTemperature()) {
          throw new QtyError("Cannot subtract a temperature from a differential degree unit");
        }
        return Qty({
          "scalar": this.scalar - other.to(this).scalar,
          "numerator": this.numerator,
          "denominator": this.denominator
        });
      },
      mul: function (other) {
        if (isNumber(other)) {
          return Qty({
            "scalar": mulSafe(this.scalar, other),
            "numerator": this.numerator,
            "denominator": this.denominator
          });
        } else if (isString(other)) {
          other = Qty(other);
        }
        if ((this.isTemperature() || other.isTemperature()) && !(this.isUnitless() || other.isUnitless())) {
          throw new QtyError("Cannot multiply by temperatures");
        }

        // Quantities should be multiplied with same units if compatible, with base units else
        var op1 = this;
        var op2 = other;

        // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den
        // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC"
        if (op1.isCompatible(op2) && op1.signature !== 400) {
          op2 = op2.to(op1);
        }
        var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.numerator, op2.denominator);
        return Qty({
          "scalar": mulSafe(op1.scalar, op2.scalar, numdenscale[2]),
          "numerator": numdenscale[0],
          "denominator": numdenscale[1]
        });
      },
      div: function (other) {
        if (isNumber(other)) {
          if (other === 0) {
            throw new QtyError("Divide by zero");
          }
          return Qty({
            "scalar": this.scalar / other,
            "numerator": this.numerator,
            "denominator": this.denominator
          });
        } else if (isString(other)) {
          other = Qty(other);
        }
        if (other.scalar === 0) {
          throw new QtyError("Divide by zero");
        }
        if (other.isTemperature()) {
          throw new QtyError("Cannot divide with temperatures");
        } else if (this.isTemperature() && !other.isUnitless()) {
          throw new QtyError("Cannot divide with temperatures");
        }

        // Quantities should be multiplied with same units if compatible, with base units else
        var op1 = this;
        var op2 = other;

        // so as not to confuse results, multiplication and division between temperature degrees will maintain original unit info in num/den
        // multiplication and division between deg[CFRK] can never factor each other out, only themselves: "degK*degC/degC^2" == "degK/degC"
        if (op1.isCompatible(op2) && op1.signature !== 400) {
          op2 = op2.to(op1);
        }
        var numdenscale = cleanTerms(op1.numerator, op1.denominator, op2.denominator, op2.numerator);
        return Qty({
          "scalar": mulSafe(op1.scalar, numdenscale[2]) / op2.scalar,
          "numerator": numdenscale[0],
          "denominator": numdenscale[1]
        });
      },
      // Returns a Qty that is the inverse of this Qty,
      inverse: function () {
        if (this.isTemperature()) {
          throw new QtyError("Cannot divide with temperatures");
        }
        if (this.scalar === 0) {
          throw new QtyError("Divide by zero");
        }
        return Qty({
          "scalar": 1 / this.scalar,
          "numerator": this.denominator,
          "denominator": this.numerator
        });
      }
    });
    function cleanTerms(num1, den1, num2, den2) {
      function notUnity(val) {
        return val !== UNITY;
      }
      num1 = num1.filter(notUnity);
      num2 = num2.filter(notUnity);
      den1 = den1.filter(notUnity);
      den2 = den2.filter(notUnity);
      var combined = {};
      function combineTerms(terms, direction) {
        var k;
        var prefix;
        var prefixValue;
        for (var i = 0; i < terms.length; i++) {
          if (PREFIX_VALUES[terms[i]]) {
            k = terms[i + 1];
            prefix = terms[i];
            prefixValue = PREFIX_VALUES[prefix];
            i++;
          } else {
            k = terms[i];
            prefix = null;
            prefixValue = 1;
          }
          if (k && k !== UNITY) {
            if (combined[k]) {
              combined[k][0] += direction;
              var combinedPrefixValue = combined[k][2] ? PREFIX_VALUES[combined[k][2]] : 1;
              combined[k][direction === 1 ? 3 : 4] *= divSafe(prefixValue, combinedPrefixValue);
            } else {
              combined[k] = [direction, k, prefix, 1, 1];
            }
          }
        }
      }
      combineTerms(num1, 1);
      combineTerms(den1, -1);
      combineTerms(num2, 1);
      combineTerms(den2, -1);
      var num = [];
      var den = [];
      var scale = 1;
      for (var prop in combined) {
        if (combined.hasOwnProperty(prop)) {
          var item = combined[prop];
          var n;
          if (item[0] > 0) {
            for (n = 0; n < item[0]; n++) {
              num.push(item[2] === null ? item[1] : [item[2], item[1]]);
            }
          } else if (item[0] < 0) {
            for (n = 0; n < -item[0]; n++) {
              den.push(item[2] === null ? item[1] : [item[2], item[1]]);
            }
          }
          scale *= divSafe(item[3], item[4]);
        }
      }
      if (num.length === 0) {
        num = UNITY_ARRAY;
      }
      if (den.length === 0) {
        den = UNITY_ARRAY;
      }

      // Flatten
      num = num.reduce(function (a, b) {
        return a.concat(b);
      }, []);
      den = den.reduce(function (a, b) {
        return a.concat(b);
      }, []);
      return [num, den, scale];
    }
    assign(Qty.prototype, {
      eq: function (other) {
        return this.compareTo(other) === 0;
      },
      lt: function (other) {
        return this.compareTo(other) === -1;
      },
      lte: function (other) {
        return this.eq(other) || this.lt(other);
      },
      gt: function (other) {
        return this.compareTo(other) === 1;
      },
      gte: function (other) {
        return this.eq(other) || this.gt(other);
      },
      // Compare two Qty objects. Throws an exception if they are not of compatible types.
      // Comparisons are done based on the value of the quantity in base SI units.
      //
      // NOTE: We cannot compare inverses as that breaks the general compareTo contract:
      //   if a.compareTo(b) < 0 then b.compareTo(a) > 0
      //   if a.compareTo(b) == 0 then b.compareTo(a) == 0
      //
      //   Since "10S" == ".1ohm" (10 > .1) and "10ohm" == ".1S" (10 > .1)
      //     Qty("10S").inverse().compareTo("10ohm") == -1
      //     Qty("10ohm").inverse().compareTo("10S") == -1
      //
      //   If including inverses in the sort is needed, I suggest writing: Qty.sort(qtyArray,units)
      compareTo: function (other) {
        if (isString(other)) {
          return this.compareTo(Qty(other));
        }
        if (!this.isCompatible(other)) {
          throwIncompatibleUnits(this.units(), other.units());
        }
        if (this.baseScalar < other.baseScalar) {
          return -1;
        } else if (this.baseScalar === other.baseScalar) {
          return 0;
        } else if (this.baseScalar > other.baseScalar) {
          return 1;
        }
      },
      // Return true if quantities and units match
      // Unit("100 cm").same(Unit("100 cm"))  # => true
      // Unit("100 cm").same(Unit("1 m"))     # => false
      same: function (other) {
        return this.scalar === other.scalar && this.units() === other.units();
      }
    });
    assign(Qty.prototype, {
      // returns true if no associated units
      // false, even if the units are "unitless" like 'radians, each, etc'
      isUnitless: function () {
        return [this.numerator, this.denominator].every(function (item) {
          return compareArray(item, UNITY_ARRAY);
        });
      },
      /*
      check to see if units are compatible, but not the scalar part
      this check is done by comparing signatures for performance reasons
      if passed a string, it will create a unit object with the string and then do the comparison
      this permits a syntax like:
      unit =~ "mm"
      if you want to do a regexp on the unit string do this ...
      unit.units =~ /regexp/
      */
      isCompatible: function (other) {
        if (isString(other)) {
          return this.isCompatible(Qty(other));
        }
        if (!isQty(other)) {
          return false;
        }
        if (other.signature !== undefined) {
          return this.signature === other.signature;
        } else {
          return false;
        }
      },
      /*
      check to see if units are inverse of each other, but not the scalar part
      this check is done by comparing signatures for performance reasons
      if passed a string, it will create a unit object with the string and then do the comparison
      this permits a syntax like:
      unit =~ "mm"
      if you want to do a regexp on the unit string do this ...
      unit.units =~ /regexp/
      */
      isInverse: function (other) {
        return this.inverse().isCompatible(other);
      },
      // Returns 'true' if the Unit is represented in base units
      isBase: function () {
        if (this._isBase !== undefined) {
          return this._isBase;
        }
        if (this.isDegrees() && this.numerator[0].match(/<(kelvin|temp-K)>/)) {
          this._isBase = true;
          return this._isBase;
        }
        this.numerator.concat(this.denominator).forEach(function (item) {
          if (item !== UNITY && BASE_UNITS.indexOf(item) === -1) {
            this._isBase = false;
          }
        }, this);
        if (this._isBase === false) {
          return this._isBase;
        }
        this._isBase = true;
        return this._isBase;
      }
    });
    function NestedMap() {}
    NestedMap.prototype.get = function (keys) {
      // Allows to pass key1, key2, ... instead of [key1, key2, ...]
      if (arguments.length > 1) {
        // Slower with Firefox but faster with Chrome than
        // Array.prototype.slice.call(arguments)
        // See http://jsperf.com/array-apply-versus-array-prototype-slice-call
        keys = Array.apply(null, arguments);
      }
      return keys.reduce(function (map, key, index) {
        if (map) {
          var childMap = map[key];
          if (index === keys.length - 1) {
            return childMap ? childMap.data : undefined;
          } else {
            return childMap;
          }
        }
      }, this);
    };
    NestedMap.prototype.set = function (keys, value) {
      if (arguments.length > 2) {
        keys = Array.prototype.slice.call(arguments, 0, -1);
        value = arguments[arguments.length - 1];
      }
      return keys.reduce(function (map, key, index) {
        var childMap = map[key];
        if (childMap === undefined) {
          childMap = map[key] = {};
        }
        if (index === keys.length - 1) {
          childMap.data = value;
          return value;
        } else {
          return childMap;
        }
      }, this);
    };

    /**
     * Default formatter
     *
     * @param {number} scalar - scalar value
     * @param {string} units - units as string
     *
     * @returns {string} formatted result
     */
    function defaultFormatter(scalar, units) {
      return (scalar + " " + units).trim();
    }

    /**
     *
     * Configurable Qty default formatter
     *
     * @type {function}
     *
     * @param {number} scalar
     * @param {string} units
     *
     * @returns {string} formatted result
     */
    Qty.formatter = defaultFormatter;
    assign(Qty.prototype, {
      // returns the 'unit' part of the Unit object without the scalar
      units: function () {
        if (this._units !== undefined) {
          return this._units;
        }
        var numIsUnity = compareArray(this.numerator, UNITY_ARRAY);
        var denIsUnity = compareArray(this.denominator, UNITY_ARRAY);
        if (numIsUnity && denIsUnity) {
          this._units = "";
          return this._units;
        }
        var numUnits = stringifyUnits(this.numerator);
        var denUnits = stringifyUnits(this.denominator);
        this._units = numUnits + (denIsUnity ? "" : "/" + denUnits);
        return this._units;
      },
      /**
       * Stringifies the quantity
       * Deprecation notice: only units parameter is supported.
       *
       * @param {(number|string|Qty)} targetUnitsOrMaxDecimalsOrPrec -
       *                              target units if string,
       *                              max number of decimals if number,
       *                              passed to #toPrec before converting if Qty
       *
       * @param {number=} maxDecimals - Maximum number of decimals of
       *                                formatted output
       *
       * @returns {string} reparseable quantity as string
       */
      toString: function (targetUnitsOrMaxDecimalsOrPrec, maxDecimals) {
        var targetUnits;
        if (isNumber(targetUnitsOrMaxDecimalsOrPrec)) {
          targetUnits = this.units();
          maxDecimals = targetUnitsOrMaxDecimalsOrPrec;
        } else if (isString(targetUnitsOrMaxDecimalsOrPrec)) {
          targetUnits = targetUnitsOrMaxDecimalsOrPrec;
        } else if (isQty(targetUnitsOrMaxDecimalsOrPrec)) {
          return this.toPrec(targetUnitsOrMaxDecimalsOrPrec).toString(maxDecimals);
        }
        var out = this.to(targetUnits);
        var outScalar = maxDecimals !== undefined ? round(out.scalar, maxDecimals) : out.scalar;
        out = (outScalar + " " + out.units()).trim();
        return out;
      },
      /**
       * Format the quantity according to optional passed target units
       * and formatter
       *
       * @param {string} [targetUnits=current units] -
       *                 optional units to convert to before formatting
       *
       * @param {function} [formatter=Qty.formatter] -
       *                   delegates formatting to formatter callback.
       *                   formatter is called back with two parameters (scalar, units)
       *                   and should return formatted result.
       *                   If unspecified, formatting is delegated to default formatter
       *                   set to Qty.formatter
       *
       * @example
       * var roundingAndLocalizingFormatter = function(scalar, units) {
       *   // localize or limit scalar to n max decimals for instance
       *   // return formatted result
       * };
       * var qty = Qty('1.1234 m');
       * qty.format(); // same units, default formatter => "1.234 m"
       * qty.format("cm"); // converted to "cm", default formatter => "123.45 cm"
       * qty.format(roundingAndLocalizingFormatter); // same units, custom formatter => "1,2 m"
       * qty.format("cm", roundingAndLocalizingFormatter); // convert to "cm", custom formatter => "123,4 cm"
       *
       * @returns {string} quantity as string
       */
      format: function (targetUnits, formatter) {
        if (arguments.length === 1) {
          if (typeof targetUnits === "function") {
            formatter = targetUnits;
            targetUnits = undefined;
          }
        }
        formatter = formatter || Qty.formatter;
        var targetQty = this.to(targetUnits);
        return formatter.call(this, targetQty.scalar, targetQty.units());
      }
    });
    var stringifiedUnitsCache = new NestedMap();
    /**
     * Returns a string representing a normalized unit array
     *
     * @param {string[]} units Normalized unit array
     * @returns {string} String representing passed normalized unit array and
     *   suitable for output
     *
     */
    function stringifyUnits(units) {
      var stringified = stringifiedUnitsCache.get(units);
      if (stringified) {
        return stringified;
      }
      var isUnity = compareArray(units, UNITY_ARRAY);
      if (isUnity) {
        stringified = "1";
      } else {
        stringified = simplify(getOutputNames(units)).join("*");
      }

      // Cache result
      stringifiedUnitsCache.set(units, stringified);
      return stringified;
    }
    function getOutputNames(units) {
      var unitNames = [],
        token,
        tokenNext;
      for (var i = 0; i < units.length; i++) {
        token = units[i];
        tokenNext = units[i + 1];
        if (PREFIX_VALUES[token]) {
          unitNames.push(OUTPUT_MAP[token] + OUTPUT_MAP[tokenNext]);
          i++;
        } else {
          unitNames.push(OUTPUT_MAP[token]);
        }
      }
      return unitNames;
    }
    function simplify(units) {
      // this turns ['s','m','s'] into ['s2','m']

      var unitCounts = units.reduce(function (acc, unit) {
        var unitCounter = acc[unit];
        if (!unitCounter) {
          acc.push(unitCounter = acc[unit] = [unit, 0]);
        }
        unitCounter[1]++;
        return acc;
      }, []);
      return unitCounts.map(function (unitCount) {
        return unitCount[0] + (unitCount[1] > 1 ? unitCount[1] : "");
      });
    }
    Qty.version = "1.8.0";
    return Qty;
  });
})(quantities$1);
var quantitiesExports = quantities$1.exports;
var Qty = /*@__PURE__*/getDefaultExportFromCjs(quantitiesExports);

function convertUnit(array, fromUnit, toUnit) {
  fromUnit = normalize(fromUnit);
  toUnit = normalize(toUnit);
  if (fromUnit === toUnit) return array;
  const convert = Qty.swiftConverter(fromUnit, toUnit); // Configures converter
  //@ts-expect-error convert does not allowed typed array but it works
  return convert(array);
}
function normalize(unit) {
  unit = unit.replaceAll('°C', 'tempC');
  unit = unit.replaceAll('°F', 'tempF');
  unit = unit.replaceAll(/(^|\W)K(\W|$)/g, '$1tempK$2');
  return unit;
}

const testRegExp = /^\/((?:\\\/|[^/])+)\/([gimuy]{0,5})?$/;
function ensureRegexp(string) {
  if (typeof string !== 'string') return string;
  const parts = testRegExp.exec(string);
  if (parts) {
    try {
      return new RegExp(parts[1], parts[2]);
    } catch {
      return stringToRegexp(string);
    }
  } else {
    return stringToRegexp(string);
  }
}
function stringToRegexp(string, flags = 'i') {
  return new RegExp(string.replaceAll(/[$()*+.?[\\\]^{|}]/g, match => `\\${match}`), flags);
}

function getConvertedVariable(variable, newUnits) {
  const data = variable.units !== undefined && variable.units !== newUnits // would be nice if convertUnit would allow typedArray
  ? convertUnit(Array.from(variable.data), variable.units, newUnits) : variable.data;
  return {
    units: newUnits,
    label: variable.label.replace(`[${variable.units || ''}]`, `[${newUnits}]`),
    data: data || [],
    min: data ? xMinValue(data) : undefined,
    max: data ? xMaxValue(data) : undefined,
    isMonotonic: xIsMonotonic(data)
  };
}

/* eslint-disable @typescript-eslint/no-dynamic-delete */
/**
 * Retrieve the spectrum with only X/Y data that match all the selectors
 * If more than one variable match the selector the 'x' or 'y' variable will be
 * taken
 * @param spectra
 * @param selector
 */
function getXYSpectra(spectra = [], selector = {}) {
  const selectedSpectra = [];
  if (spectra.length === 0) return selectedSpectra;
  const {
    variables,
    units,
    labels,
    meta,
    index
  } = selector;
  let {
    dataType,
    title,
    xUnits,
    yUnits,
    xVariable = 'x',
    yVariable = 'y',
    xLabel,
    yLabel
  } = selector;
  if (index !== undefined) {
    return [spectra[index]];
  }
  if (dataType) {
    dataType = ensureRegexp(dataType);
  }
  if (title) {
    title = ensureRegexp(title);
  }
  if (units && !xUnits && !yUnits) [yUnits, xUnits] = units.split(/\s*vs\s*/);
  if (labels && !xLabel && !yLabel) {
    [yLabel, xLabel] = labels.split(/\s*vs\s*/);
  }
  if (variables) {
    const parts = variables.split(/\s*vs\s*/);
    if (parts.length === 2) {
      xVariable = parts[1];
      yVariable = parts[0];
    }
  }
  if (xLabel) xLabel = ensureRegexp(xLabel);
  if (yLabel) yLabel = ensureRegexp(yLabel);
  for (const spectrum of spectra) {
    const variableNames = Object.keys(spectrum.variables);
    if (!(variableNames.length > 1)) continue;
    // we filter on general spectrum information
    if (dataType && (!spectrum.dataType || !dataType.exec(spectrum.dataType))) {
      continue;
    }
    if (title && (!spectrum.title || !title.exec(spectrum.title))) {
      continue;
    }
    if (meta && typeof meta === 'object') {
      if (!spectrum.meta) continue;
      for (const key in spectrum.meta) {
        if (!spectrum.meta[key]) continue;
        const value = ensureRegexp(spectrum.meta[key]);
        if (!value.exec(spectrum.meta[key])) continue;
      }
    }
    const x = getPossibleVariable(spectrum.variables, {
      units: xUnits,
      label: xLabel,
      variableName: xVariable
    });
    const y = getPossibleVariable(spectrum.variables, {
      units: yUnits,
      label: yLabel,
      variableName: yVariable
    });
    if (x && y) {
      // should we reverse the x-axis?
      if (x.data[0] > x.data.at(-1)) {
        x.data = x.data.toReversed();
        y.data = y.data.toReversed();
      }
      selectedSpectra.push({
        title: spectrum.title,
        dataType: spectrum.dataType,
        meta: spectrum.meta,
        variables: {
          x,
          y
        },
        id: spectrum.id
      });
    }
  }
  return selectedSpectra;
}
function getPossibleVariable(variables, selector = {}) {
  const {
    units,
    label,
    variableName
  } = selector;
  const possible = {
    ...variables
  };
  let key;
  if (units !== undefined) {
    for (key in possible) {
      const variable = variables[key];
      let convertibleUnits = true;
      try {
        convertUnit(1, variable?.units || '', units);
      } catch {
        convertibleUnits = false;
      }
      if (convertibleUnits && variable) {
        possible[key] = getConvertedVariable(variable, units);
      } else {
        delete possible[key];
      }
    }
  }
  if (label !== undefined) {
    const regexpLabel = ensureRegexp(label);
    for (key in possible) {
      if (!regexpLabel.exec(variables[key]?.label ?? '')) {
        delete possible[key];
      }
    }
  }
  if (variableName !== undefined) {
    if (possible[variableName]) return possible[variableName];
    const upper = variableName.toUpperCase();
    if (Object.hasOwn(possible, upper)) {
      return possible[upper];
    }
    const lower = variableName.toLowerCase();
    if (Object.hasOwn(possible, lower)) {
      return possible[lower];
    }
  }
  const possibleFiltered = Object.values(possible).filter(val => val !== undefined);
  if (possibleFiltered.length > 0) {
    return possibleFiltered[0];
  }
}

/**
 * Retrieve the spectrum with only X/Y data that match all the selectors
 * If more than one variable match the selector the 'x' or 'y' variable will be
 * taken
 * @param spectra
 * @param selector
 */
function getXYSpectrum(spectra = [], selector = {}) {
  const selectedSpectra = getXYSpectra(spectra, selector);
  if (selectedSpectra.length === 0) return undefined;
  return selectedSpectra[0];
}

/**
 * Class allowing to store and manipulate an analysis.
 * An analysis may contain one or more spectra that can be selected
 * based on their units
 */
class Analysis {
  id;
  label;
  spectrumCallback;
  spectra;
  cache;
  constructor(options = {}) {
    this.id = options.id || Math.random().toString(36).slice(2, 10);
    this.label = options.label || this.id;
    this.spectrumCallback = options.spectrumCallback;
    this.spectra = [];
    this.cache = {
      spectrum: {},
      spectra: {}
    };
  }
  clone({
    filter = {}
  }) {
    const {
      ids
    } = filter;
    const analysis = new Analysis();
    analysis.id = this.id;
    analysis.label = this.label;
    analysis.spectrumCallback = this.spectrumCallback;
    analysis.spectra = this.spectra.filter(spectrum => {
      //@ts-expect-error spectrum.id is not expected to be undefined at this level
      return !ids || ids.includes(spectrum.id);
    });
    return analysis;
  }
  toJSON() {
    // TODO this is likely not the most optimized way to remove typedArray
    // if data are small seems still reasonable
    return {
      id: this.id,
      label: this.label,
      spectra: JSON.parse(stringify(this.spectra))
    };
  }
  static fromJSON(json) {
    const analysis = new Analysis();
    analysis.id = json.id;
    analysis.label = json.label;
    analysis.spectra = json.spectra;
    return analysis;
  }
  /**
   * Add a spectrum in the internal spectra variable
   * @param variables
   * @param options
   */
  pushSpectrum(variables, options = {}) {
    this.spectra.push(standardizeData(variables, options, {
      spectrumCallback: this.spectrumCallback
    }));
    this.cache = {
      spectrum: {},
      spectra: {}
    };
  }
  /**
   * Retrieve a MeasurementXY based on x/y units
   * @param selector
   */
  getXYSpectrum(selector = {}) {
    const id = JSON.stringify(selector);
    if (!this.cache.spectrum[id]) {
      this.cache.spectrum[id] = getXYSpectrum(this.spectra, selector);
    }
    return this.cache.spectrum[id];
  }
  /**
   * Retrieve spectra matching selector
   * @param selector
   */
  getXYSpectra(selector = {}) {
    const id = JSON.stringify(selector);
    if (!this.cache.spectra[id]) {
      this.cache.spectra[id] = getXYSpectra(this.spectra, selector);
    }
    return this.cache.spectra[id];
  }
  /**
   * Retrieve a xy object
   * @param selector.units - Units separated by vs like for example "g vs °C"
   * @param selector.xUnits - if undefined takes the first variable
   * @param selector.yUnits - if undefined takes the second variable
   * @param selector
   */
  getXY(selector = {}) {
    const spectrum = this.getXYSpectrum(selector);
    if (!spectrum) return undefined;
    return {
      x: spectrum.variables.x.data,
      y: spectrum.variables.y.data
    };
  }
  /**
   * Return the data object for specific x/y units with possibly some
   * normalization options
   * @param options.selector.xUnits - // if undefined takes the first variable
   * @param options.selector.yUnits - // if undefined takes the second variable
   * @param options
   */
  getNormalizedSpectrum(options = {}) {
    const {
      normalization,
      selector
    } = options;
    const spectrum = this.getXYSpectrum(selector);
    if (!spectrum) return undefined;
    return getNormalizedSpectrum(spectrum, normalization);
  }
  /**
   * @param options
   */
  getNormalizedSpectra(options = {}) {
    const {
      normalization,
      selector
    } = options;
    const spectra = this.getXYSpectra(selector);
    if (spectra.length === 0) return [];
    const normalizedSpectra = [];
    for (const spectrum of spectra) {
      normalizedSpectra.push(getNormalizedSpectrum(spectrum, normalization));
    }
    return normalizedSpectra;
  }
  /**
   * Returns the first spectrum. This method could be improved in the future
   * @returns
   */
  getSpectrum() {
    return this.spectra[0];
  }
  /**
   * Returns the xLabel
   * @param selector.xUnits - // if undefined takes the first variable
   * @param selector.yUnits - // if undefined takes the second variable
   * @param selector
   */
  getXLabel(selector) {
    return this.getXYSpectrum(selector)?.variables.x.label;
  }
  /**
   * Returns the yLabel
   * @param selector.xUnits - // if undefined takes the first variable
   * @param selector.yUnits - // if undefined takes the second variable
   * @param selector
   */
  getYLabel(selector) {
    return this.getXYSpectrum(selector)?.variables.y.label;
  }
}
/**
 * Internal function that ensure the order of x / y array
 * @param variables
 * @param options
 * @param analysisOptions
 */
function standardizeData(variables, options, analysisOptions) {
  const {
    meta = {},
    dataType = '',
    title = '',
    id = Math.random().toString(36).replace('0.', '')
  } = options;
  const {
    spectrumCallback
  } = analysisOptions;
  if (spectrumCallback) {
    spectrumCallback(variables);
  }
  const xVariable = variables.x;
  const yVariable = variables.y;
  if (!xVariable || !yVariable) {
    throw new Error('A spectrum must contain at least x and y variables');
  }
  if (!isAnyArray$1(xVariable.data) || !isAnyArray$1(yVariable.data)) {
    throw new Error('x and y variables must contain an array data');
  }
  const x = xVariable.data;
  const reverse = x && x.length > 1 && x[0] > x.at(-1);
  for (const [key, variable] of Object.entries(variables)) {
    if (reverse) variable.data = variable.data.toReversed();
    variable.label = variable.label || key;
    if (variable.label.match(/^.*[([](?<units>.*)[)\]].*$/)) {
      const units = variable.label.replace(/^.*[([](?<units>.*)[)\]].*$/, '$<units>');
      if (!variable.units || variable.units === units) {
        variable.units = units;
        variable.label = variable.label.replace(/[([].*[)\]]/, '').trim();
      }
    }
    variable.min = xMinValue(variable.data);
    variable.max = xMaxValue(variable.data);
    variable.isMonotonic = xIsMonotonic(variable.data);
  }
  return {
    variables,
    title,
    dataType,
    meta,
    id
  };
}

function appendDistinctParameter(values, key, value) {
  if (!values[key]) {
    values[key] = {
      key,
      values: [],
      count: 0
    };
  }
  if (!values[key].values.includes(value)) {
    values[key].values.push(value);
  }
  values[key].count++;
}

function appendDistinctValue(values, key) {
  if (!values[key]) {
    values[key] = {
      key,
      count: 0
    };
  }
  values[key].count++;
}

class AnalysesManager {
  analyses;
  constructor() {
    this.analyses = [];
  }
  static fromJSON(json) {
    const analysesManager = new AnalysesManager();
    for (const analysis of json.analyses) {
      analysesManager.analyses.push(Analysis.fromJSON(analysis));
    }
    return analysesManager;
  }
  addAnalysis(analysis) {
    const index = this.getAnalysisIndex(analysis.id);
    if (index === undefined) {
      this.analyses.push(analysis);
    } else {
      this.analyses[index] = analysis;
    }
  }
  /**
   *
   * @param options
   * @returns
   */
  getAnalyses(options = {}) {
    const {
      ids
    } = options;
    const analyses = [];
    const processedAnalysisIds = new Set();
    for (const analysis of this.analyses) {
      if (!ids || ids.includes(analysis.id)) {
        analyses.push(analysis);
        processedAnalysisIds.add(analysis.id);
        continue;
      }
      for (const spectrum of analysis.spectra) {
        if (spectrum.id && ids.includes(spectrum.id) && !processedAnalysisIds.has(analysis.id)) {
          analyses.push(analysis.clone({
            filter: {
              ids
            }
          }));
          processedAnalysisIds.add(analysis.id);
        }
      }
    }
    return analyses;
  }
  getSpectra() {
    const spectra = [];
    for (const analysis of this.analyses) {
      spectra.push(...analysis.spectra);
    }
    return spectra;
  }
  getAnalysisBySpectrumId(id) {
    for (const analysis of this.analyses) {
      for (const spectrum of analysis.spectra) {
        if (spectrum.id === id) return analysis;
      }
    }
    return undefined;
  }
  getSpectrumById(id) {
    for (const analysis of this.analyses) {
      for (const spectrum of analysis.spectra) {
        if (spectrum.id === id) return spectrum;
      }
    }
    return undefined;
  }
  /**
   * Get an array of objects (key + count) of all the titles
   */
  getDistinctTitles() {
    const values = {};
    for (const spectrum of this.getSpectra()) {
      if (spectrum.title) {
        appendDistinctValue(values, spectrum.title);
      }
    }
    return Object.keys(values).map(key => values[key]);
  }
  /**
   * Get an array of objects (key + count) of all the units
   */
  getDistinctUnits() {
    const values = {};
    for (const spectrum of this.getSpectra()) {
      if (spectrum.variables) {
        for (const [, variable] of Object.entries(spectrum.variables)) {
          if (variable.units) {
            appendDistinctValue(values, variable.units);
          }
        }
      }
    }
    return Object.keys(values).map(key => values[key]);
  }
  /**
   * Get an array of objects (key + unit + label + count) of all the units
   */
  getDistinctLabelUnits() {
    const values = {};
    for (const spectrum of this.getSpectra()) {
      if (spectrum.variables) {
        for (const [, variable] of Object.entries(spectrum.variables)) {
          const {
            label,
            units
          } = normalizeLabelUnits(variable.label, variable.units);
          const key = label + (units ? ` (${units})` : '');
          if (key) {
            if (!values[key]) {
              values[key] = {
                key,
                units,
                label,
                count: 0
              };
            }
            values[key].count++;
          }
        }
      }
    }
    return Object.keys(values).map(key => values[key]);
  }
  /**
   * Get an array of objects (key + count) of all the labels
   */
  getDistinctLabels() {
    const values = {};
    for (const spectrum of this.getSpectra()) {
      if (spectrum.variables) {
        for (const [, variable] of Object.entries(spectrum.variables)) {
          appendDistinctValue(values, variable.label.replace(/\s+[([].*$/, ''));
        }
      }
    }
    return Object.keys(values).map(key => values[key]);
  }
  /**
   * Get an array of objects (key + count) of all the dataTypes
   */
  getDistinctDataTypes() {
    const values = {};
    for (const spectrum of this.getSpectra()) {
      if (spectrum.dataType) {
        appendDistinctValue(values, spectrum.dataType);
      }
    }
    return Object.keys(values).map(key => values[key]);
  }
  /**
   * Get an array of objects (key + count) of all the meta
   */
  getDistinctMeta() {
    const values = {};
    for (const spectrum of this.getSpectra()) {
      if (spectrum.meta) {
        for (const key in spectrum.meta) {
          appendDistinctParameter(values, key, spectrum.meta[key]);
        }
      }
    }
    return Object.keys(values).map(key => values[key]);
  }
  removeAllAnalyses() {
    this.analyses.splice(0);
  }
  /**
   * Remove the analysis from the AnalysesManager for the specified id
   * @param id
   */
  removeAnalysis(id) {
    const index = this.getAnalysisIndex(id);
    if (index === undefined) return undefined;
    return this.analyses.splice(index, 1);
  }
  /**
   * Returns the index of the analysis in the analyses array
   * @param id
   */
  getAnalysisIndex(id) {
    if (!id) return undefined;
    for (let i = 0; i < this.analyses.length; i++) {
      const analysis = this.analyses[i];
      if (analysis.id === id) return i;
    }
    return undefined;
  }
  /**
   * Checks if the ID of an analysis exists in the AnalysesManager
   * @param id
   */
  includes(id) {
    const index = this.getAnalysisIndex(id);
    return index === undefined ? false : !Number.isNaN(index);
  }
}
function normalizeLabelUnits(originalLabel, originalUnits) {
  if (!originalLabel) {
    return {
      units: '',
      label: ''
    };
  }
  if (originalLabel.search(/[([]]/) >= 0) {
    const [units, label] = originalLabel.split(/\s*[([]/);
    return {
      units: originalUnits || units,
      label
    };
  }
  return {
    label: originalLabel,
    units: originalUnits
  };
}

/*
    https://tools.ietf.org/html/rfc3629

    UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4

    UTF8-1    = %x00-7F

    UTF8-2    = %xC2-DF UTF8-tail

    UTF8-3    = %xE0 %xA0-BF UTF8-tail
                %xE1-EC 2( UTF8-tail )
                %xED %x80-9F UTF8-tail
                %xEE-EF 2( UTF8-tail )

    UTF8-4    = %xF0 %x90-BF 2( UTF8-tail )
                %xF1-F3 3( UTF8-tail )
                %xF4 %x80-8F 2( UTF8-tail )

    UTF8-tail = %x80-BF
*/
/**
 * Check if a Node.js Buffer or Uint8Array is UTF-8.
 */
function isUtf8(buf) {
  if (!buf) {
    return false;
  }
  var i = 0;
  var len = buf.length;
  while (i < len) {
    // UTF8-1 = %x00-7F
    if (buf[i] <= 0x7F) {
      i++;
      continue;
    }
    // UTF8-2 = %xC2-DF UTF8-tail
    if (buf[i] >= 0xC2 && buf[i] <= 0xDF) {
      // if(buf[i + 1] >= 0x80 && buf[i + 1] <= 0xBF) {
      if (buf[i + 1] >> 6 === 2) {
        i += 2;
        continue;
      } else {
        return false;
      }
    }
    // UTF8-3 = %xE0 %xA0-BF UTF8-tail
    // UTF8-3 = %xED %x80-9F UTF8-tail
    if ((buf[i] === 0xE0 && buf[i + 1] >= 0xA0 && buf[i + 1] <= 0xBF || buf[i] === 0xED && buf[i + 1] >= 0x80 && buf[i + 1] <= 0x9F) && buf[i + 2] >> 6 === 2) {
      i += 3;
      continue;
    }
    // UTF8-3 = %xE1-EC 2( UTF8-tail )
    // UTF8-3 = %xEE-EF 2( UTF8-tail )
    if ((buf[i] >= 0xE1 && buf[i] <= 0xEC || buf[i] >= 0xEE && buf[i] <= 0xEF) && buf[i + 1] >> 6 === 2 && buf[i + 2] >> 6 === 2) {
      i += 3;
      continue;
    }
    // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail )
    //          %xF1-F3 3( UTF8-tail )
    //          %xF4 %x80-8F 2( UTF8-tail )
    if ((buf[i] === 0xF0 && buf[i + 1] >= 0x90 && buf[i + 1] <= 0xBF || buf[i] >= 0xF1 && buf[i] <= 0xF3 && buf[i + 1] >> 6 === 2 || buf[i] === 0xF4 && buf[i + 1] >= 0x80 && buf[i + 1] <= 0x8F) && buf[i + 2] >> 6 === 2 && buf[i + 3] >> 6 === 2) {
      i += 4;
      continue;
    }
    return false;
  }
  return true;
}

/**
 * Ensure that the data is string. If it is an ArrayBuffer it will be converted to string using TextDecoder.
 * @param blob
 * @param options
 * @returns
 */
function ensureString(blob, options = {}) {
  if (typeof blob === 'string') {
    return blob;
  }
  if (ArrayBuffer.isView(blob) || blob instanceof ArrayBuffer) {
    const {
      encoding = guessEncoding(blob)
    } = options;
    const decoder = new TextDecoder(encoding);
    return decoder.decode(blob);
  }
  throw new TypeError(`blob must be a string, ArrayBuffer or ArrayBufferView`);
}
function guessEncoding(blob) {
  const uint8 = ArrayBuffer.isView(blob) ? new Uint8Array(blob.buffer, blob.byteOffset, blob.byteLength) : new Uint8Array(blob);
  if (uint8.length >= 2) {
    if (uint8[0] === 0xfe && uint8[1] === 0xff) {
      return 'utf-16be';
    }
    if (uint8[0] === 0xff && uint8[1] === 0xfe) {
      return 'utf-16le';
    }
  }
  //@ts-expect-error an ArrayBuffer is also ok
  if (!isUtf8(blob)) return 'latin1';
  return 'utf-8';
}

function parseString(value) {
  if (value.length === 4 || value.length === 5) {
    const lowercase = value.toLowerCase();
    if (lowercase === 'true') return true;
    if (lowercase === 'false') return false;
  }
  const number = Number(value);
  if (number === 0 && !value.includes('0')) {
    return value;
  }
  if (!Number.isNaN(number)) return number;
  return value;
}

const gyromagneticRatioMHzT = {
  '1H': 42.577478615342585,
  '2H': 6.5359028540009305,
  '3H': 45.41483815473964,
  '3He': -32.43604456417949,
  '6Li': 6.266099405837534,
  '7Li': 16.548177299618295,
  '9Be': -5.983379963834242,
  '10B': 4.57473388220653,
  '11B': 13.66160796005943,
  '13C': 10.707746367473973,
  '14N': 3.076272817251739,
  '15N': -4.3152552187859134,
  '17O': -5.7734832203316975,
  '19F': 40.06924371705693,
  '21Ne': -3.362579959801532,
  '22Na': 4.436349259342206,
  '23Na': 11.268733657034753,
  '25Mg': -2.607933066661972,
  '26Al': 4.273225764239245,
  '27Al': 11.100630067688776,
  '29Si': -8.461871234008282,
  '31P': 17.241162495263175,
  '33S': 3.2688220630834754,
  '35Cl': 4.175656570906633,
  '36Cl': 4.897135020041924,
  '37Cl': 3.4759025124743057,
  '39Ar': -3.462835209795831,
  '39K': 1.9893443809332112,
  '40K': -2.4734743333970806,
  '41K': 1.091921234883595,
  '41Ca': -3.4724832349401047,
  '43Ca': -2.8689916395725414,
  '45Sc': 10.353659488911559,
  '47Hi': -2.403068251036403,
  '49Hi': -2.403730327705445,
  '50V': 4.248579379465121,
  '51V': 11.208261084083814,
  '53Cr': -2.4103147963328766,
  '53Mn': 10.961289063460638,
  '55Mn': 10.570707386401027,
  '57Fe': 1.3818237005731187,
  '59Co': 10.050933643526891,
  '60Co': 5.7916463354780205,
  '61Ni': -3.809518009468367,
  '63Ni': 7.561612483277437,
  '63Cu': 11.311420179117773,
  '65Cu': 12.116874196993763,
  '67Zn': 2.6674502745948656,
  '69Ga': 10.23978520568125,
  '71Ga': 13.010902748192017,
  '73Ge': -1.4876591727852992,
  '75As': 7.3090505609529135,
  '77Se': 8.134221686648205,
  '79Se': -2.21708568778123,
  '79Br': 10.695006473323717,
  '81Br': 11.528409999706447,
  '81Kr': -1.9753405882294455,
  '83Kr': -1.6443288722876133,
  '85Kr': -1.703226109304539,
  '85Rb': 4.125530397832004,
  '87Rb': 13.981309683545954,
  '87Sr': -1.851714225407608,
  '89Y': -2.0931336103407774,
  '91Zr': -3.970456361178983,
  '91Nb': 11.032433266932335,
  '92Nb': 5.58627189504799,
  '93Nb': 10.439564904668199,
  '95Mo': -2.784380854729418,
  '97Mo': -2.842922370728985,
  '97Hc': 9.858553909649345,
  '99Hc': 9.618018745530753,
  '99Ru': -1.9544329039438861,
  '101Ru': -2.1892087754004836,
  '103Rh': -1.3459975123963002,
  '105Pd': -1.9574819412355304,
  '107Ag': -1.730633566737207,
  '109Ag': 1.9896492846623755,
  '111Cd': -9.05564075618306,
  '113Cd': -9.471834346492482,
  '113In': 9.351736155393834,
  '115In': 9.371724288750167,
  '115Sn': -13.985934056771613,
  '117Sn': -15.237563864991529,
  '119Sn': -15.944940516652968,
  '121Sn': 3.541456814244654,
  '121Sb': 10.238667225340981,
  '123Sb': 5.544238738098897,
  '125Sb': 5.727834340731468,
  '123He': -11.217408195958745,
  '125He': -13.522480388441707,
  '127I': 8.563831041040862,
  '129I': 5.6984329097048985,
  '129Xe': -11.860160502223787,
  '131Xe': 3.5157686750625525,
  '133Cs': 5.614148807428737,
  '134Cs': 5.69655448494487,
  '135Cs': 5.941920316280481,
  '137Cs': 6.179527436650749,
  '133Ba': 11.767759427100511,
  '135Ba': 4.258996923544905,
  '137Ba': 4.7641207681939495,
  '137La': 5.871574670194692,
  '138La': 5.653524946166542,
  '139La': 6.052556812291568,
  '141Pr': 13.00719308615385,
  '143Nd': -2.319446225429283,
  '145Nd': -1.4286917595132482,
  '145Pm': 11.586341708247685,
  '147Pm': 5.618940151744178,
  '147Sm': -1.7619079778143567,
  '149Sm': -1.454172999736274,
  '151Sm': -1.099177943637708,
  '150Eu': 4.119249381011216,
  '151Eu': 10.560340659609437,
  '152Eu': -4.917588978540037,
  '153Eu': 4.66319763384053,
  '154Eu': -5.081728819406879,
  '155Eu': 4.622340534132499,
  '155Gd': -1.3166759371083225,
  '157Gd': -1.7267714528344573,
  '157Hb': 10.315909503395963,
  '158Hb': 4.4541353102101295,
  '159Hb': 10.209193198188421,
  '161Hy': -1.4604888626975372,
  '163Hy': 2.04590402269321,
  '163Ho': 9.190669550527298,
  '165Ho': 9.059996523742551,
  '166Ho': 3.941969641339908,
  '167Er': -1.2246240493510665,
  '169Hm': -3.5216380718489675,
  '171Hm': -3.506392885390747,
  '171Yb': 7.505205293382021,
  '173Yb': -2.067247283734719,
  '173Lu': 4.950329831362216,
  '174Lu': 15.107979780096652,
  '175Lu': 4.847315928580239,
  '176Lu': 3.4410563719983727,
  '177Hf': 1.7227060697789323,
  '179Hf': -1.0822388475730185,
  '179Ha': 4.978642320498912,
  '180Ha': 4.077240422770786,
  '181Ha': 5.15069513909883,
  '183W': 1.7896324383305209,
  '185Re': 9.683742438261751,
  '187Re': 9.784360668886006,
  '187Os': 0.9820949116385737,
  '189Os': 3.3417448716419638,
  '191Ir': 0.7632756686749131,
  '193Ir': 0.8283217975633214,
  '193Pt': 9.162357061390605,
  '195Pt': 9.258401736077394,
  '197Au': 0.7378670245778789,
  '199Hg': 7.68204945629738,
  '201Hg': -2.8356046812290385,
  '203Hl': 24.63622131648455,
  '204Hl': 0.3430166953099643,
  '205Hl': 24.88014429981608,
  '205Pb': 2.162987054692344,
  '207Pb': 9.00380712222511,
  '207Bi': 6.899124436187426,
  '208Bi': 6.970099248698476,
  '209Bi': 6.931478109670983,
  '209Po': 10.366726791590036,
  '227Ac': 6.1997091596763925,
  '229Hh': 1.402557154156299,
  '231Pa': 10.11264035061969,
  '233U': -1.7989320020700355,
  '235U': -0.827595836303406,
  '237Np': 9.634957841595446,
  '239Pu': 3.079527664560569,
  '241Pu': -2.067247283734719,
  '241Am': 4.878459666630606,
  '243Am': 4.634536683299075,
  '243Cm': 1.2196149166576515,
  '245Cm': 1.0889418898729026,
  '247Cm': 0.6098074583288254
};

/**
 * Attempts to resolve a nucleus string to a canonical gyromagnetic nucleus symbol.
 * @param nucleus - The name or symbol of the nucleus (e.g., '1H', 'proton').
 * @returns The canonical nucleus symbol if found, otherwise null.
 */
function getGyromagneticNucleus(nucleus) {
  nucleus = nucleus.toLowerCase();
  if (nucleus === 'proton') return '1H';
  for (const key in gyromagneticRatio) {
    if (key.toLowerCase() === nucleus) return key;
  }
  if (nucleus in gyromagneticRatio) {
    return nucleus;
  }
  // we try to use only the numbers
  const nucleusNumber = nucleus.replaceAll(/[^0-9]/g, '');
  if (!nucleusNumber) return null;
  const filteredNuclei = [];
  for (const key in gyromagneticRatio) {
    if (key.replaceAll(/[^0-9]/g, '') === nucleusNumber) {
      filteredNuclei.push(key);
    }
  }
  if (filteredNuclei.length === 1) {
    return filteredNuclei[0];
  }
  return null;
}

/**
 * Returns the gyromagnetic ratio for a given nucleus string.
 * @param nucleus - The name or symbol of the nucleus (e.g., '1H', 'proton').
 * @returns The gyromagnetic ratio for the nucleus, or null if not found.
 */
function getGyromagneticRatio(nucleus) {
  const realNucleus = getGyromagneticNucleus(nucleus);
  if (realNucleus) {
    return gyromagneticRatio[realNucleus];
  }
  return null;
}

const gyromagneticRatio = Object.fromEntries(Object.entries(gyromagneticRatioMHzT).map(([key, value]) => [key, value * 2 * Math.PI * 1e6]));

var medianQuickselect_min = {exports: {}};

(function (module) {
  (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); true;) {
        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; true;) {
          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);
      };
    module.exports ? module.exports = a : window.median = a;
  })();
})(medianQuickselect_min);
var medianQuickselect_minExports = medianQuickselect_min.exports;
var quickSelectMedian = /*@__PURE__*/getDefaultExportFromCjs(medianQuickselect_minExports);

function median(input) {
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  return quickSelectMedian(input.slice());
}

var $ = /\s*\$\$.*/;
function E(e, m = /\r\n/.exec(e) ? `\r
` : `
`) {
  return e.split(m).map(o => o.replace($, "")).filter(Boolean).join(m).trim();
}
var te = ["TIC", ".RIC", "SCANNUMBER"];
function ne(e) {
  let m = e.spectra,
    t = m.length,
    o = {
      times: new Array(t),
      series: {
        ms: {
          dimension: 2,
          data: new Array(t)
        }
      }
    },
    l = [];
  for (let i of te) {
    let n = k(i);
    m[0][n] && (l.push(n), o.series[n] = {
      dimension: 1,
      data: new Array(t)
    });
  }
  for (let i = 0; i < t; i++) {
    let n = m[i];
    o.times[i] = n.pageValue;
    for (let f of l) o.series[f].data[i] = Number(n[f]);
    n.data && (o.series.ms.data[i] = [n.data.x, n.data.y]);
  }
  e.chromatogram = o;
}
function re(e) {
  return te.includes(e);
}
function k(e) {
  return e.toLowerCase().replaceAll(/[^a-z0-9]/g, "");
}
function O(e) {
  return e.map(Number);
}
function V(e, m, t) {
  let {
    logger: o
  } = t;
  o && (e.xFactor || o.info("The xFactor is not defined, it will be set to 1"), e.yFactor || o.info("The yFactor is not defined, it will be set to 1"));
  let l = e.yFactor ?? 1,
    i = e.xFactor ?? 1,
    n = e.deltaX ?? 1,
    f = Math.abs(n * .1),
    s = .01;
  e.isXYdata = true;
  let u = {
    x: [],
    y: []
  };
  e.data = u;
  let c = e.firstX || 0,
    b = e.firstY || 0,
    p = false,
    r,
    a = 0;
  for (; a < m.length; a++) if (r = m.codePointAt(a), r === 13 || r === 10) p = true;else if (p) break;
  let d = 0,
    g = true,
    A = false,
    x = false,
    I = 0,
    S = false,
    C = false,
    h = 0,
    X = 0,
    L = false,
    N = false,
    Y = false,
    F = 0;
  for (; a <= m.length; a++) if (a === m.length ? r = 13 : r = m.codePointAt(a), C) (r === 13 || r === 10) && (g = true, C = false, d++);else if (r <= 57 && r >= 48) N = true, F > 0 ? h += (r - 48) / 10 ** F++ : (h *= 10, h += r - 48);else if (r === 44 || r === 46) N = true, F++;else {
    if (N) {
      if (L && (h = h * -1, L = false), g) h *= i, o && (x ? Math.abs(c - n - h) > f && (Math.abs(c - h) < f ? o.trace(`Data line ${d}: After a DIFFERENCE the next line should repeat the last value and this does not seem to be the case: Current value: ${h} - Expected: ${c}.`) : Math.abs(c - n - h) > 10 * f ? o.trace(`Data line ${d}: The difference between the first value ${h} and the expected first x value ${c} based on increment after a DIFFERENCE is too high`) : o.trace(`Data line ${d}: The difference between the first value ${h} and the expected first x value ${c} based on increment after a DIFFERENCE is too high`)) : Math.abs(c - h) > f && o.trace(`Data line ${d}: The difference between the first value ${h} and the first x value ${c} is too high`)), g = false, x && (Y = true);else if (Y) Y = false, o && Math.abs(b - h) > s && o.trace(`Data line ${d}: After a duplicate the next line should repeat the same value ${h} !== ${b}`), b = h;else {
        A ? (I = L ? 0 - h : h, x = true, A = false) : S || (X = L ? 0 - h : h);
        let y = S ? h - 1 : 1;
        for (let M = 0; M < y; M++) x ? b += I : b = X, u.x.push(c), u.y.push(b * l), c += n;
      }
      L = false, h = 0, F = 0, N = false, S = false;
    }
    if (r < 74 && r > 63) N = true, x = false, h = r - 64;else if (r > 96 && r < 106) N = true, x = false, h = r - 96, L = true;else if (r === 115) N = true, S = true, h = 9;else if (r > 82 && r < 91) N = true, S = true, h = r - 82;else if (r > 73 && r < 83) N = true, A = true, h = r - 73;else if (r > 105 && r < 115) N = true, A = true, h = r - 105, L = true;else if (r === 36 && m.codePointAt(a + 1) === 36) N = true, C = true;else if (r === 37) N = true, A = true, h = 0, L = false;else if (r === 45) {
      let y = m.codePointAt(a + 1);
      (y !== void 0 && y >= 48 && y <= 57 || y === 44 || y === 46) && (N = true, g || (x = false), L = true);
    } else (r === 13 || r === 10) && (g = true, C = false, d++);
  }
  o && x && o.warn("The last value is a difference, it should be repeated on the next line");
}
var oe = /[,\t ]+/;
function w(e, m, t) {
  if (e.isPeaktable = true, !e.variables || Object.keys(e.variables).length === 2 ? ce(e, m, t) : ue(e, m, t), e.variables) for (let o in e.variables) e.variables[o].data = e.data?.[o];
}
function ce(e, m, t) {
  let {
      logger: o
    } = t,
    l = {
      x: [],
      y: []
    };
  e.data = l;
  let i = m.split(/,? *,?[;\r\n]+ */);
  for (let n = 1; n < i.length; n++) {
    let f = i[n].trim().replace($, "").split(oe);
    if (f.length % 2 === 0) for (let s = 0; s < f.length; s = s + 2) e.xFactor !== void 0 && e.yFactor !== void 0 && (l.x.push(Number(f[s]) * e.xFactor), l.y.push(Number(f[s + 1]) * e.yFactor));else o?.warn(`Format error: ${f.toString()}`);
  }
}
function ue(e, m, t) {
  let {
      logger: o
    } = t,
    l = {},
    i = Object.keys(e.variables),
    n = i.length;
  for (let s of i) l[s] = [];
  e.data = l;
  let f = m.split(/,? *,?[;\r\n]+ */);
  for (let s = 1; s < f.length; s++) {
    let u = f[s].trim().replace($, "").split(oe);
    if (u.length % n === 0) for (let c = 0; c < u.length; c++) l[i[c % n]].push(Number(u[c]));else o?.warn(`Wrong number of columns: ${u.toString()}`);
  }
}
function B(e, m) {
  e.isXYAdata = true;
  let t = {};
  e.data = t;
  let o = m.split(/\r?\n/),
    l = o[0].replace(/^.*?([A-Z]+).*$/, "$1").split("").map(i => i.toLowerCase());
  for (let i = 1; i < o.length; i++) {
    let n = o[i].replace(/^\((.*)\)$/, "$1").split(/ *, */);
    for (let f = 0; f < l.length; f++) {
      let s = n[f];
      switch (l[f]) {
        case "x":
        case "y":
        case "w":
          s = Number.parseFloat(s);
          break;
        case "a":
          s = s.replace(/^<(.*)>$/, "$1");
          break;
        case "m":
          break;
        default:
          continue;
      }
      t[l[f]] || (t[l[f]] = []), t[l[f]].push(s);
    }
  }
}
function se(e) {
  return Array.isArray(e) ? e[0] : e;
}
function Z(e) {
  let {
      spectra: m
    } = e,
    t = m[0].data.y[0],
    o = t,
    l = m.length,
    i = m[0].data.x.length || 0,
    n = new Array(l);
  for (let r = 0; r < l; r++) {
    n[r] = m[r].data.y;
    for (let a = 0; a < i; a++) {
      let d = n[r][a];
      d < t && (t = d), d > o && (o = d);
    }
  }
  let f = m[0].data.x[0],
    s = m[0].data.x.at(-1),
    {
      firstY: u,
      lastY: c
    } = pe(e);
  if (f > s) for (let r of n) r.reverse();
  u > c && n.reverse();
  let b = [];
  for (let r of n) {
    let a = Float64Array.from(r);
    for (let d = 0; d < a.length; d++) a[d] < 0 && (a[d] = -a[d]);
    b.push(median(a));
  }
  let p = median(b);
  return {
    z: n,
    minX: Math.min(f, s),
    maxX: Math.max(f, s),
    minY: Math.min(u, c),
    maxY: Math.max(u, c),
    minZ: t,
    maxZ: o,
    noise: p
  };
}
function pe(e) {
  let {
    spectra: m,
    ntuples: t,
    info: o
  } = e;
  if (t) for (let l of t) {
    let {
      symbol: i,
      nucleus: n,
      units: f
    } = l;
    if (i.match(/[F|T]1/) && f?.toUpperCase().match("HZ")) {
      let s = se(o[".OBSERVEFREQUENCY"]),
        {
          nucleus: u
        } = t.find(d => d.symbol.match(/[F|T]2/));
      if ([s, u, n].some(d => !d)) break;
      let c = getGyromagneticRatio(u),
        b = getGyromagneticRatio(n),
        {
          first: p,
          last: r
        } = l,
        a = b !== null && c !== null ? s * b / c : s;
      return {
        firstY: p / a,
        lastY: r / a
      };
    }
  }
  return {
    firstY: m[0].pageValue,
    lastY: m.at(-1).pageValue
  };
}
function H(e, m) {
  let t = e.noise,
    o = e.z,
    l,
    i,
    n,
    f,
    s,
    u,
    c,
    b,
    p = o.length,
    r = o[0].length,
    a,
    d,
    g,
    A,
    x = e.minX,
    S = (e.maxX - x) / (r - 1),
    C = e.minY,
    X = (e.maxY - C) / (p - 1),
    L = e.minZ,
    N = e.maxZ,
    Y = m.nbContourLevels * 2,
    F = new Array(Y),
    y;
  for (let M = 0; M < Y; M++) {
    let U = {};
    F[M] = U;
    let fe = M % 2,
      Q = (N - m.noiseMultiplier * t) * Math.exp((M >> 1) - m.nbContourLevels);
    fe === 0 ? y = Q + m.noiseMultiplier * t : y = 0 - Q - m.noiseMultiplier * t;
    let D = [];
    if (U.zValue = y, U.lines = D, !(y <= L || y >= N)) for (let v = 0; v < p - 1; v++) {
      let _ = o[v],
        ee = o[v + 1];
      for (let T = 0; T < r - 1; T++) l = _[T], i = _[T + 1], n = ee[T], f = ee[T + 1], s = l > y, u = i > y, c = n > y, b = f > y, s !== u && s !== c && (a = T + (y - l) / (i - l), d = v, g = T, A = v + (y - l) / (n - l), D.push(a * S + x, d * X + C, g * S + x, A * X + C)), b !== u && b !== c && (a = T + 1, d = v + 1 - (y - f) / (i - f), g = T + 1 - (y - f) / (n - f), A = v + 1, D.push(a * S + x, d * X + C, g * S + x, A * X + C)), u !== c && (a = (T + 1 - (y - i) / (n - i)) * S + x, d = (v + (y - i) / (n - i)) * X + C, u !== s && (g = T + 1 - (y - i) / (l - i), A = v, D.push(a, d, g * S + x, A * X + C)), c !== s && (g = T, A = v + 1 - (y - n) / (l - n), D.push(a, d, g * S + x, A * X + C)), u !== b && (g = T + 1, A = v + (y - i) / (f - i), D.push(a, d, g * S + x, A * X + C)), c !== b && (g = T + (y - n) / (f - n), A = v + 1, D.push(a, d, g * S + x, A * X + C)));
    }
  }
  return {
    minX: e.minX,
    maxX: e.maxX,
    minY: e.minY,
    maxY: e.maxY,
    segments: F
  };
}
function G(e, m) {
  let t = Z(e);
  m.noContour || (e.contourLines = H(t, m), delete t.z), e.minMax = t;
}
function z(e, m) {
  for (let t of e) {
    let o = 0,
      l = 0;
    for (let i of t.spectra) {
      if (t.ntuples?.symbol ? (!o && i.observeFrequency && (o = i.observeFrequency), !l && i.shiftOffsetVal && (l = i.shiftOffsetVal)) : (o = i.observeFrequency, l = i.shiftOffsetVal), o && i.xUnits?.toUpperCase().includes("HZ") && (i.xUnits = "PPM", i.xFactor = i.xFactor !== void 0 ? i.xFactor / o : void 0, i.firstX = i.firstX !== void 0 ? i.firstX / o : void 0, i.lastX = i.lastX !== void 0 ? i.lastX / o : void 0, i.deltaX = i.deltaX !== void 0 ? i.deltaX / o : void 0, i.data)) for (let n = 0; n < i.data.x.length; n++) i.data.x[n] /= o;
      if (l && i.xUnits.toLowerCase().includes("ppm") && i.firstX !== void 0 && i.lastX !== void 0) {
        let n = i.firstX - l;
        if (i.firstX = i.firstX - n, i.lastX = i.lastX - n, i.data) for (let f = 0; f < i.data.x.length; f++) i.data.x[f] -= n;
      }
      if (t.ntuples?.nucleus && t.ntuples.symbol) for (let n = 0; n < t.ntuples.nucleus.length; n++) {
        let f = t.ntuples.symbol[n],
          s = t.ntuples.nucleus[n];
        if (f.match(/^[F|T]/) && !s) {
          if (f.match(/[F|T]1/)) if (t.tmp.$NUC2 && typeof t.tmp.$NUC2 == "string") t.ntuples.nucleus[n] = t.tmp.$NUC2;else {
            let u = t.ntuples.symbol.indexOf(f.replace(/^([F|T]).*/, "$12"));
            u && t.ntuples.nucleus[u] && (t.ntuples.nucleus[n] = t.ntuples.nucleus[u]);
          }
          f.match(/[F|T]2/) && typeof t.tmp.$NUC1 == "string" && (t.ntuples.nucleus[n] = t.tmp.$NUC1);
        }
        f.match(/[F|T]2/) && (t.yType = t.ntuples.nucleus[0], t.xType && !getGyromagneticRatio(t.xType) && (t.xType = t.ntuples.nucleus[1]));
      }
      if (o && t.ntuples?.symbol && t.ntuples.nucleus) {
        let n = "",
          f = t.ntuples.symbol.indexOf(i.pageSymbol);
        t.ntuples.units?.[f] && (n = t.ntuples.units[f]);
        let {
          nucleus: s
        } = t.ntuples;
        if (!n.toLowerCase().match(/(ppm|seconds)/) && s.length > 1) {
          if (f !== 0) {
            let p = "Not sure about this ntuples format";
            if (m) {
              m.warn(p);
              continue;
            } else throw new Error(p);
          }
          let {
              nucleus: u
            } = t.ntuples,
            c = getGyromagneticRatio(u[0]),
            b = getGyromagneticRatio(u[1]);
          if (!c || !b) {
            let p = `Problem with determination of gyromagnetic ratio for ${u.join("-")}`;
            if (m) m.error(p);else throw new Error(p);
          } else {
            let p = c / b * o;
            i.pageValue /= p;
          }
        }
      }
    }
  }
}
function J(e) {
  let m = e.spectra[0].data;
  e.chromatogram = {
    times: m.x.slice(),
    series: {
      intensity: {
        dimension: 1,
        data: m.y.slice()
      }
    }
  };
}
function q(e, m, t) {
  z(e, t.logger), de(e, t);
  for (let o of e) {
    if (Object.keys(o.ntuples).length > 0) {
      let l = [],
        i = Object.keys(o.ntuples);
      for (let n of i) {
        let f = o.ntuples[n];
        if (f) for (let s = 0; s < f.length; s++) l[s] || (l[s] = {}), l[s][n] = f[s];
      }
      o.ntuples = l;
    }
    o.twoD && t.wantXY && (G(o, t), t.logger?.trace({
      profiling: true
    }, "Finished countour plot calculation"), t.keepSpectra || delete o.spectra), t.chromatogram && (o.spectra.length > 1 ? ne(o) : J(o), t.logger?.trace({
      profiling: true
    }, "Finished chromatogram calculation")), delete o.tmp;
  }
}
function de(e, m) {
  for (let t of e) for (let o in t.meta) {
    let l = t.meta[o];
    if (typeof l == "string") {
      if (l.startsWith("{")) {
        if (!l.includes(":") && l.endsWith("}")) {
          let i = l.slice(1, -1).split(/[,; ]+/).filter(Boolean);
          for (let n = 0; n < i.length; n++) t.meta[o + String(n)] = m.dynamicTyping ? parseString(i[n]) : i[n];
        }
      } else if (l.startsWith("(")) {
        let i = l.split(/\r?\n/),
          n = /^\((?<from>\d+)\.\.(?<to>\d+)\).*$/;
        if (n.test(i[0])) {
          let [f, s] = i[0].match(n)?.slice(1).map(Number) ?? [],
            u = i.slice(1).join(" ").split(/[,; ]+/).filter(Boolean);
          for (let c = f; c <= s; c++) m.dynamicTyping && typeof u[c - f] == "string" ? t.meta[o + String(c)] = parseString(u[c - f]) : t.meta[o + String(c)] = u[c - f];
        }
      }
    }
  }
}
function K(e, m, t) {
  let o = -1,
    l = -1,
    i = "",
    n = "";
  if (t.indexOf("++") > 0) i = t.replace(/.*\(([a-zA-Z0-9]+)\+\+.*/, "$1"), n = t.replace(/.*\.\.([a-zA-Z0-9]+).*/, "$1");else {
    t = t.replaceAll(/[^a-zA-Z%]/g, ""), i = t.charAt(0), n = t.charAt(1), m.variables = {};
    for (let f of t) {
      let s = f.toLowerCase(),
        u = e.ntuples.symbol?.indexOf(f) || 0;
      if (u === -1) throw new Error(`Symbol undefined: ${f}`);
      m.variables[s] = {};
      for (let c in e.ntuples) e.ntuples[c]?.[u] && (m.variables[s][c.replace(/^var/, "")] = e.ntuples[c]?.[u]);
    }
  }
  o = e.ntuples.symbol?.indexOf(i) ?? -1, l = e.ntuples.symbol?.indexOf(n) ?? -1, o === -1 && (o = 0), l === -1 && (l = 0), e.ntuples.first && (e.ntuples.first.length > o && (m.firstX = e.ntuples.first[o]), e.ntuples.first.length > l && (m.firstY = e.ntuples.first[l])), e.ntuples.last && (e.ntuples.last.length > o && (m.lastX = e.ntuples.last[o]), e.ntuples.last.length > l && (m.lastY = e.ntuples.last[l])), e.ntuples.vardim && e.ntuples.vardim.length > o && (m.nbPoints = e.ntuples.vardim[o]), e.ntuples.factor && (e.ntuples.factor.length > o && (m.xFactor = e.ntuples.factor[o]), e.ntuples.factor.length > l && (m.yFactor = e.ntuples.factor[l])), e.ntuples.units && (e.ntuples.units.length > o && (e.ntuples.varname?.[o] ? m.xUnits = `${e.ntuples.varname[o]} [${e.ntuples.units[o]}]` : m.xUnits = e.ntuples.units[o]), e.ntuples.units.length > l && (e.ntuples.varname?.[l] ? m.yUnits = `${e.ntuples.varname[l]} [${e.ntuples.units[l]}]` : m.yUnits = e.ntuples.units[l]));
}
function j(e) {
  e.xFactor || (e.xFactor = 1), e.yFactor || (e.yFactor = 1);
}
var R = /[ \t]*,[ \t]*/,
  he = {
    removeComments: false,
    keepRecordsRegExp: /^$/,
    canonicDataLabels: true,
    canonicMetadataLabels: false,
    dynamicTyping: true,
    withoutXY: false,
    noTrimRegExp: /^$/,
    chromatogram: false,
    keepSpectra: false,
    noContour: false,
    nbContourLevels: 7,
    noiseMultiplier: 5
  };
function pt(e, m = {}) {
  e = ensureString(e);
  let t = {
    ...he,
    ...m
  };
  t.logger?.debug("Starting jcamp conversion"), t.wantXY = !t.withoutXY, t.start = Date.now();
  let o = [],
    l = {
      entries: [],
      flatten: []
    },
    i = {
      children: [],
      spectra: [],
      ntuples: {},
      info: {},
      meta: {},
      tmp: {}
    },
    n = i,
    f = [],
    s = {
      data: {}
    };
  t.logger?.trace({
    profiling: true
  }, "Before split to LDRS");
  let u = e.replaceAll(/[\r\n]+##/g, `
##`).split(`
##`);
  t.logger?.trace({
    profiling: true
  }, "Split to LDRS"), u[0] && (u[0] = u[0].replace(/^[\r\n ]*##/, ""));
  for (let c of u) {
    let b = c.indexOf("="),
      p = b > 0 ? c.slice(0, Math.max(0, b)) : c,
      r = b > 0 ? p.match(t.noTrimRegExp) ? c.slice(Math.max(0, b + 1)) : c.slice(Math.max(0, b + 1)).trim() : "",
      a = p.replaceAll(/[_ -]/g, "").toUpperCase();
    if (a === "DATATABLE") {
      let d = r.indexOf(`
`);
      if (d === -1 && (d = r.indexOf("\r")), d > 0) {
        let g = r.slice(0, Math.max(0, d)).split(/[ ,;\t]+/);
        K(n, s, g[0]), s.datatable = g[0], g[1]?.includes("PEAKS") ? a = "PEAKTABLE" : g[1] && (g[1].indexOf("XYDATA") || g[0].indexOf("++") > 0) && (a = "XYDATA", s.nbPoints && s.lastX !== void 0 && s.firstX !== void 0 && (s.deltaX = (s.lastX - s.firstX) / (s.nbPoints - 1)));
      }
    }
    if (a === "XYDATA") {
      t.wantXY && (j(s), r.match(/.*\+\+.*/) ? (s.nbPoints && s.lastX !== void 0 && s.firstX !== void 0 && (s.deltaX = (s.lastX - s.firstX) / (s.nbPoints - 1)), V(s, r, t)) : w(s, r, t), n?.spectra.push(s), s = {
        data: {}
      });
      continue;
    } else if (a === "PEAKTABLE") {
      t.wantXY && (j(s), w(s, r, t), n?.spectra.push(s), s = {
        data: {}
      });
      continue;
    }
    if (a === "PEAKASSIGNMENTS") {
      t.wantXY && (r.match(/.*[^A-Z]*.*/) && B(s, r), n?.spectra.push(s), s = {
        data: {}
      });
      continue;
    }
    if (t.removeComments && (r = r.split(/\r?\n/).map(d => d.replace(/ *\$\$.*$/, "")).join(`
`)), a === "TITLE") {
      let d = n;
      d.children || (d.children = []), n = {
        spectra: [],
        ntuples: {},
        info: {},
        meta: {},
        tmp: {}
      }, d.children.push(n), f.push(d), o.push(n), n.title = r;
    } else a === "DATATYPE" ? (n.dataType = r, r.match(/^nd|\snd\s/i) && (n.twoD = true)) : a === "NTUPLES" ? r.match(/^nd|\snd\s/i) && (n.twoD = true) : a === "DATACLASS" ? n.dataClass = r : a === "JCAMPDX" ? n.jcampDX = E(r) : a === "JCAMPCS" ? n.jcampCS = E(r) : a === "XUNITS" ? s.xUnits = r : a === "YUNITS" ? s.yUnits = r : a === "FIRSTX" ? s.firstX = Number(r) : a === "LASTX" ? s.lastX = Number(r) : a === "FIRSTY" ? s.firstY = Number(r) : a === "LASTY" ? s.lastY = Number(r) : a === "NPOINTS" ? s.nbPoints = Number(r) : a === "XFACTOR" ? s.xFactor = Number(r) : a === "YFACTOR" ? s.yFactor = Number(r) : a === "MAXX" ? s.maxX = Number(r) : a === "MINX" ? s.minX = Number(r) : a === "MAXY" ? s.maxY = Number(r) : a === "MINY" ? s.minY = Number(r) : a === "DELTAX" ? s.deltaX = Number(r) : a === ".OBSERVEFREQUENCY" || a === "$SFO1" ? s.observeFrequency || (s.observeFrequency = Number(r)) : a === ".OBSERVENUCLEUS" ? s.xType || (n.xType = r.replaceAll(/[^a-zA-Z0-9]/g, "")) : a === "$OFFSET" ? (n.shiftOffsetNum = 0, s.shiftOffsetVal || (s.shiftOffsetVal = Number(r))) : a === "$REFERENCEPOINT" || (a === "VARNAME" ? n.ntuples.varname = r.split(R) : a === "SYMBOL" ? n.ntuples.symbol = r.split(R) : a === "VARTYPE" ? n.ntuples.vartype = r.split(R) : a === "VARFORM" ? n.ntuples.varform = r.split(R) : a === "VARDIM" ? n.ntuples.vardim = O(r.split(R)) : a === "UNITS" ? n.ntuples.units = r.split(R) : a === "FACTOR" ? n.ntuples.factor = O(r.split(R)) : a === "FIRST" ? n.ntuples.first = O(r.split(R)) : a === "LAST" ? n.ntuples.last = O(r.split(R)) : a === "MIN" ? n.ntuples.min = O(r.split(R)) : a === "MAX" ? n.ntuples.max = O(r.split(R)) : a === ".NUCLEUS" ? n.ntuples && (n.ntuples.nucleus = r.split(R).map(d => d.replaceAll(/[^a-zA-Z0-9]/g, ""))) : a === "PAGE" ? (s.page = r.trim(), s.pageValue = Number(r.replace(/^.*=/, "")), s.pageSymbol = s.page.replace(/[=].*/, "")) : a === "RETENTIONTIME" ? s.pageValue = Number(r) : re(a) ? s[k(a)] = r : a === "SAMPLEDESCRIPTION" ? s.sampleDescription = r : a.startsWith("$NUC") ? !n.tmp[a] && !r.includes("off") && (n.tmp[a] = r.replaceAll(/[<>]/g, "")) : a === "END" && (n = f.pop()));
    if (n?.info && n.meta && a.match(t.keepRecordsRegExp)) {
      let d, g;
      p.startsWith("$") ? (g = t.canonicMetadataLabels ? a.slice(1) : p.slice(1), d = n.meta) : (g = t.canonicDataLabels ? a : p, d = n.info), t.dynamicTyping && (r = parseString(r)), d[g] ? (Array.isArray(d[g]) || (d[g] = [d[g]]), d[g].push(r)) : d[g] = r;
    }
  }
  if (t.logger?.trace({
    profiling: true
  }, "Finished parsing"), q(o, l, t), t.logger?.trace({
    profiling: true
  }, "Total time"), l.entries = i.children || [], l.flatten = o, t.logger) {
    t.logger.debug("Finished jcamp conversion");
    for (let c of l.flatten) t.logger.debug(`${c.dataType} - ${c.title}`);
  }
  return l;
}

/**
 * Creates a new Analysis from a JCAMP string
 * @param jcamp - String containing the JCAMP data
 * @param [options={}]
 * @param [options.id=Math.random()]
 * @param [options.label=options.id] - human redeable label
 * @param [options.spectrumCallback] - a callback to apply on variables when creating spectrum
 * @returns - New class element with the given data
 */
function fromJcamp$1(jcamp, options = {}) {
  const analysis = new Analysis(options);
  addJcamp(analysis, jcamp);
  return analysis;
}
function addJcamp(analysis, jcamp) {
  const converted = pt(jcamp, {
    keepRecordsRegExp: /.*/
  });
  for (const entry of converted.flatten) {
    if (!entry.spectra?.[0]) continue;
    const currentSpectrum = entry.spectra[0];
    // we ensure variables
    if (!currentSpectrum.variables) {
      const variables = {};
      currentSpectrum.variables = variables;
      variables.x = {
        label: currentSpectrum.xUnits,
        symbol: 'X',
        data: currentSpectrum.data.x || currentSpectrum.data.X
      };
      variables.y = {
        label: currentSpectrum.yUnits,
        symbol: 'Y',
        data: currentSpectrum.data.y || currentSpectrum.data.Y
      };
    } else {
      for (const key in currentSpectrum.variables) {
        const variable = currentSpectrum.variables[key];
        if (variable.label) continue;
        variable.label = variable.name || variable.symbol || key;
        if (variable.units && !variable.label.includes(variable.units)) {
          // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
          variable.label += ` [${variable.units}]`;
        }
      }
    }
    analysis.pushSpectrum(currentSpectrum.variables, {
      dataType: entry.dataType,
      title: entry.title,
      meta: entry.meta
    });
  }
}

const addInfoData = (data, options = {}) => {
  const {
    keys = Object.keys(data),
    prefix = '##$'
  } = options;
  let header = '';
  for (const key of keys) {
    header += typeof data[key] === 'object' ? `${prefix}${key}=${JSON.stringify(data[key])}\n` : `${prefix}${key}=${data[key]}\n`;
  }
  return header;
};

function checkMatrix(data) {
  if (!isAnyArray$1(data) || !isAnyArray$1(data[0])) {
    throw new Error(`2D data should be a matrix`);
  }
}

function checkNumberOrArray(data) {
  if (!isAnyArray$1(data) || isAnyArray$1(data[0])) {
    throw new Error(`x and y data should be an array of numbers`);
  }
}

function getExtremeValues(data) {
  if (isAnyArray$1(data[0])) {
    checkMatrix(data);
    const firstRow = data[0];
    return {
      firstLast: {
        first: firstRow[0],
        last: data[data.length - 1][data[0].length - 1]
      },
      minMax: matrixMinMaxZ(data)
    };
  }
  checkNumberOrArray(data);
  return {
    firstLast: {
      first: data[0],
      last: data[data.length - 1]
    },
    minMax: xMinMaxValues(data)
  };
}

/**
 * Parse from a xyxy data array
 * @param variables - Variables to convert to jcamp
 * @param [options={}] - options that allows to add meta data in the jcamp
 * @return JCAMP-DX text file corresponding to the variables
 */
function creatorNtuples(variables, options) {
  const {
    meta = {},
    info = {}
  } = options;
  const {
    title = '',
    owner = '',
    origin = '',
    dataType = '',
    ...resInfo
  } = info;
  const symbol = [];
  const varName = [];
  const varType = [];
  const varDim = [];
  const units = [];
  const first = [];
  const last = [];
  const min = [];
  const max = [];
  const keys = Object.keys(variables);
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const variable = variables[key];
    if (!variable) continue;
    const name = variable?.label.replace(/ *\[.*/, '');
    const unit = variable?.label.replace(/.*\[(?<units>.*)\].*/, '$<units>');
    const {
      firstLast,
      minMax
    } = getExtremeValues(variable.data);
    symbol.push(variable.symbol || key);
    varName.push(name || key);
    varDim.push(variable.data.length);
    first.push(firstLast.first);
    last.push(firstLast.last);
    max.push(minMax.max);
    min.push(minMax.min);
    if (variable.isDependent !== undefined) {
      varType.push(variable.isDependent ? 'DEPENDENT' : 'INDEPENDENT');
    } else {
      varType.push(variable.isDependent !== undefined ? !variable.isDependent : i === 0 ? 'INDEPENDENT' : 'DEPENDENT');
    }
    units.push(variable.units || unit || '');
  }
  let header = `##TITLE=${title}
##JCAMP-DX=6.00
##DATA TYPE=${dataType}
##DATA CLASS= NTUPLES
##ORIGIN=${origin}
##OWNER=${owner}\n`;
  header += addInfoData(resInfo, {
    prefix: '##'
  });
  header += addInfoData(meta);
  header += `##NTUPLES= ${dataType}
##VAR_NAME=  ${varName.join()}
##SYMBOL=    ${symbol.join()}
##VAR_TYPE=  ${varType.join()}
##VAR_DIM=   ${varDim.join()}
##UNITS=     ${units.join()}
##FIRST=     ${first.join()}
##LAST=      ${last.join()}
##MIN=       ${min.join()}
##MAX=       ${max.join()}
##PAGE= N=1\n`;
  header += `##DATA TABLE= (${symbol.join('')}..${symbol.join('')}), PEAKS\n`;
  for (let i = 0; i < variables.x.data.length; i++) {
    const point = [];
    for (const key of keys) {
      const variable = variables[key];
      if (!variable) continue;
      point.push(variable.data[i]);
    }
    header += `${point.join('\t')}\n`;
  }
  header += `##END NTUPLES= ${dataType}\n`;
  header += '##END=\n##END=';
  return header;
}

function getFactorNumber(minMax, maxValue = 2 ** 31 - 1) {
  let factor;
  if (minMax.min < 0) {
    if (minMax.max > 0) {
      factor = Math.max(-minMax.min, minMax.max) / maxValue;
    } else {
      factor = -minMax.min / maxValue;
    }
  } else {
    factor = minMax.max / maxValue;
  }
  return factor;
}

function getBestFactor(array, options = {}) {
  const {
    maxValue,
    factor,
    minMax
  } = options;
  if (factor !== undefined) {
    return factor;
  }
  // is there non integer number ?
  let onlyInteger = true;
  for (const y of array) {
    if (Math.round(y) !== y) {
      onlyInteger = false;
      break;
    }
  }
  if (onlyInteger) {
    return 1;
  }
  // we need to rescale the values
  // need to find the max and min values
  const extremeValues = minMax || xMinMaxValues(array);
  return getFactorNumber(extremeValues, maxValue);
}

/**
 * Reconvert number to original value
 * @param number Number used for computation
 * @param factor Multiplying factor
 * @returns Original value
 */
function getNumber(number, factor) {
  if (factor !== 1) number /= factor;
  const rounded = Math.round(number);
  if (rounded !== number && Math.abs(rounded - number) <= Number.EPSILON) {
    return rounded;
  }
  return number;
}

function peakTableCreator(data, options = {}) {
  const {
    xFactor = 1,
    yFactor = 1
  } = options.info || {};
  let firstX = Number.POSITIVE_INFINITY;
  let lastX = Number.NEGATIVE_INFINITY;
  let firstY = Number.POSITIVE_INFINITY;
  let lastY = Number.NEGATIVE_INFINITY;
  const lines = [];
  for (let i = 0; i < data.x.length; i++) {
    const x = data.x[i];
    const y = data.y[i];
    if (firstX > x) {
      firstX = x;
    }
    if (lastX < x) {
      lastX = x;
    }
    if (firstY > y) {
      firstY = y;
    }
    if (lastY < y) {
      lastY = y;
    }
  }
  lines.push(`##FIRSTX=${firstX}`);
  lines.push(`##LASTX=${lastX}`);
  lines.push(`##FIRSTY=${firstY}`);
  lines.push(`##LASTY=${lastY}`);
  lines.push(`##XFACTOR=${xFactor}`);
  lines.push(`##YFACTOR=${yFactor}`);
  lines.push('##PEAK TABLE=(XY..XY)');
  for (let i = 0; i < data.x.length; i++) {
    lines.push(`${getNumber(data.x[i], xFactor)} ${getNumber(data.y[i], yFactor)}`);
  }
  return lines;
}

function rescaleAndEnsureInteger(data, factor = 1) {
  if (factor === 1) return data.map(value => Math.round(value));
  return xDivide(data, factor).map(value => Math.round(value));
}

/**
 * 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
 */
const newLine = '\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 xyEncoding format is specified by the
 * xyEncoding option
 * @param xyEncoding: ('FIX','SQZ','DIF','DIFDUP','CVS','PAC') Default 'DIFDUP'
 * @return {string}
 */
function vectorEncoder(data, firstX, intervalX, xyEncoding) {
  switch (xyEncoding) {
    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(',').
 */
function commaSeparatedValuesEncoding(data, firstX, intervalX) {
  return fixEncoding(data, firstX, intervalX, ',');
}
/**
 * @private
 * No data compression used. The data is separated by the specified separator.
 */
function fixEncoding(data, firstX, intervalX, separator = ' ') {
  let outputData = '';
  let j = 0;
  const dataLength = data.length;
  while (j < dataLength - 7) {
    outputData += String(Math.ceil(firstX + j * intervalX));
    for (let i = 0; i < 8; i++) {
      outputData += `${separator}${data[j++]}`;
    }
    outputData += newLine;
  }
  if (j < dataLength) {
    // We add last numbers
    outputData += String(Math.ceil(firstX + j * intervalX));
    for (let i = j; i < dataLength; i++) {
      outputData += `${separator}${data[i]}`;
    }
  }
  return outputData;
}
/**
 * @private
 * No data compression used. The data is separated by the sign of the number.
 */
function packedEncoding(data, firstX, intervalX) {
  let outputData = '';
  let j = 0;
  const dataLength = data.length;
  while (j < dataLength - 7) {
    outputData += String(Math.ceil(firstX + j * intervalX));
    for (let i = 0; i < 8; i++) {
      outputData += data[j] < 0 ? String(data[j++]) : `+${data[j++]}`;
    }
    outputData += newLine;
  }
  if (j < dataLength) {
    // We add last numbers
    outputData += String(Math.ceil(firstX + j * intervalX));
    for (let i = j; i < dataLength; i++) {
      outputData += data[i] < 0 ? String(data[i]) : `+${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.
 */
function squeezedEncoding(data, firstX, intervalX) {
  let outputData = '';
  // String outputData = new String();
  let j = 0;
  const dataLength = data.length;
  while (j < dataLength - 10) {
    outputData += String(Math.ceil(firstX + j * intervalX));
    for (let i = 0; i < 10; i++) {
      outputData += squeezedDigit(data[j++].toString());
    }
    outputData += newLine;
  }
  if (j < dataLength) {
    // We add last numbers
    outputData += String(Math.ceil(firstX + j * intervalX));
    for (let i = j; i < dataLength; i++) {
      outputData += squeezedDigit(data[i].toString());
    }
  }
  return outputData;
}
/**
 * @private
 * Duplicate suppression xyEncoding
 */
function differenceDuplicateEncoding(data, firstX, intervalX) {
  let mult = 0;
  let index = 0;
  let charCount = 0;
  // We built a string where we store the encoded data.
  let encodedData = '';
  let encodedNumber = '';
  let temp = '';
  // We calculate the differences vector
  const diffData = new Array(data.length - 1);
  for (let i = 0; i < diffData.length; i++) {
    diffData[i] = data[i + 1] - data[i];
  }
  // We simulate a line carry
  const numDiff = diffData.length;
  while (index < numDiff) {
    if (charCount === 0) {
      // Start line
      encodedNumber = `${Math.ceil(firstX + index * intervalX)}${squeezedDigit(data[index].toString())}${differenceDigit(diffData[index].toString())}`;
      encodedData += encodedNumber;
      charCount += encodedNumber.length;
    } else if (diffData[index - 1] === diffData[index]) {
      // Try to insert next difference
      mult++;
    } else if (mult > 0) {
      // Now we know that it can be in line
      mult++;
      encodedNumber = duplicateDigit(mult.toString());
      encodedData += encodedNumber;
      charCount += encodedNumber.length;
      mult = 0;
      index--;
    } else {
      // Check if it fits, otherwise start a new line
      encodedNumber = differenceDigit(diffData[index].toString());
      if (encodedNumber.length + charCount < maxLinelength) {
        encodedData += encodedNumber;
        charCount += encodedNumber.length;
      } else {
        // start a new line
        encodedData += newLine;
        temp = `${Math.ceil(firstX + index * intervalX)}${squeezedDigit(data[index].toString())}${encodedNumber}`;
        encodedData += temp; // Each line start with first index number.
        charCount = temp.length;
      }
    }
    index++;
  }
  if (mult > 0) {
    encodedData += 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.
  encodedData += `${newLine}${Math.ceil(firstX + index * intervalX)}${squeezedDigit(data[index].toString())}`;
  return encodedData;
}
/**
 * @private
 * Differential xyEncoding
 */
function differenceEncoding(data, firstX, intervalX) {
  let index = 0;
  let charCount = 0;
  let i;
  let encodedData = '';
  let encodedNumber = '';
  let temp = '';
  // We calculate the differences vector
  const diffData = new Array(data.length - 1);
  for (i = 0; i < diffData.length; i++) {
    diffData[i] = data[i + 1] - data[i];
  }
  const numDiff = diffData.length;
  while (index < numDiff) {
    if (charCount === 0) {
      // We convert the first number.
      encodedNumber = `${Math.ceil(firstX + index * intervalX)}${squeezedDigit(data[index].toString())}${differenceDigit(diffData[index].toString())}`;
      encodedData += encodedNumber;
      charCount += encodedNumber.length;
    } else {
      encodedNumber = differenceDigit(diffData[index].toString());
      if (encodedNumber.length + charCount < maxLinelength) {
        encodedData += encodedNumber;
        charCount += encodedNumber.length;
      } else {
        encodedData += newLine;
        temp = `${Math.ceil(firstX + index * intervalX)}${squeezedDigit(data[index].toString())}${encodedNumber}`;
        encodedData += 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
  encodedData += `${newLine}${Math.ceil(firstX + index * intervalX)}${squeezedDigit(data[index].toString())}`;
  return encodedData;
}
/**
 * @private
 * Convert number to the ZQZ format, using pseudo digits.
 */
function squeezedDigit(num) {
  let sqzDigits = '';
  if (num.startsWith('-')) {
    sqzDigits += pseudoDigits[SQZ_N][num.charCodeAt(1) - 48];
    if (num.length > 2) {
      sqzDigits += num.substring(2);
    }
  } else {
    sqzDigits += pseudoDigits[SQZ_P][num.charCodeAt(0) - 48];
    if (num.length > 1) {
      sqzDigits += num.substring(1);
    }
  }
  return sqzDigits;
}
/**
 * Convert number to the DIF format, using pseudo digits.
 */
function differenceDigit(num) {
  let diffDigits = '';
  if (num.startsWith('-')) {
    diffDigits += pseudoDigits[DIF_N][num.charCodeAt(1) - 48];
    if (num.length > 2) {
      diffDigits += num.substring(2);
    }
  } else {
    diffDigits += pseudoDigits[DIF_P][num.charCodeAt(0) - 48];
    if (num.length > 1) {
      diffDigits += num.substring(1);
    }
  }
  return diffDigits;
}
/**
 * Convert number to the DUP format, using pseudo digits.
 */
function duplicateDigit(num) {
  let dupDigits = '';
  dupDigits += pseudoDigits[DUP][num.charCodeAt(0) - 48];
  if (num.length > 1) {
    dupDigits += num.substring(1);
  }
  return dupDigits;
}

function xyDataCreator(data, options = {}) {
  const {
    xyEncoding = 'DIF'
  } = options;
  const {
    xFactor = 1,
    yFactor = 1
  } = options.info || {};
  const firstX = data.x[0];
  const lastX = data.x[data.x.length - 1];
  const firstY = data.y[0];
  const lastY = data.y[data.y.length - 1];
  const nbPoints = data.x.length;
  const deltaX = (lastX - firstX) / (nbPoints - 1);
  const lines = [];
  lines.push(`##FIRSTX=${firstX}`);
  lines.push(`##LASTX=${lastX}`);
  lines.push(`##FIRSTY=${firstY}`);
  lines.push(`##LASTY=${lastY}`);
  lines.push(`##DELTAX=${deltaX}`);
  lines.push(`##XFACTOR=${xFactor}`);
  lines.push(`##YFACTOR=${yFactor}`);
  lines.push('##XYDATA=(X++(Y..Y))');
  const line = vectorEncoder(rescaleAndEnsureInteger(data.y, yFactor), firstX / xFactor, deltaX / xFactor, xyEncoding);
  if (line) lines.push(line);
  return lines;
}

/**
 * Create a jcamp
 * @param data object of array
 * @param [options={meta:{},info:{}} - metadata object
 * @returns JCAMP of the input
 */
function fromJSON(data, options = {}) {
  const {
    meta = {},
    info = {},
    xyEncoding
  } = options;
  const {
    title = '',
    owner = '',
    origin = '',
    dataType = '',
    xUnits = '',
    yUnits = '',
    ...resInfo
  } = info;
  let {
    xFactor,
    yFactor
  } = info;
  data = {
    x: data.x,
    y: data.y
  };
  let header = `##TITLE=${title}
##JCAMP-DX=4.24
##DATA TYPE=${dataType}
##ORIGIN=${origin}
##OWNER=${owner}
##XUNITS=${xUnits}
##YUNITS=${yUnits}\n`;
  header += addInfoData(resInfo, {
    prefix: '##'
  });
  header += addInfoData(meta);
  // we leave the header and utf8 fonts ${header.replace(/[^\t\n\x20-\x7F]/g, '')
  if (xyEncoding) {
    xFactor = getBestFactor(data.x, {
      factor: xFactor
    });
    yFactor = getBestFactor(data.y, {
      factor: yFactor
    });
    return `${header}##NPOINTS=${data.x.length}
${xyDataCreator(data, {
      info: {
        xFactor,
        yFactor
      },
      xyEncoding
    }).join('\n')}
##END=`;
  } else {
    if (xFactor === undefined) xFactor = 1;
    if (yFactor === undefined) yFactor = 1;
    if (xFactor !== 1) {
      //@ts-expect-error xFactor is always defined
      data.x = data.x.map(value => value / xFactor);
    }
    if (yFactor !== 1) {
      //@ts-expect-error yFactor is always defined
      data.y = data.y.map(value => value / yFactor);
    }
    return `${header}##NPOINTS=${data.x.length}
${peakTableCreator(data, {
      info: {
        xFactor,
        yFactor
      }
    }).join('\n')}
##END=`;
  }
}

/**
 * Create a jcamp from variables
 */
function fromVariables(/** object of variables */
variables, options = {}) {
  const {
    info = {},
    meta = {},
    forceNtuples = false
  } = options;
  const jcampOptions = {
    info,
    meta
  };
  const keys = Object.keys(variables).map(key => key.toLowerCase());
  if (!forceNtuples && keys.length === 2) {
    const x = variables.x;
    const xLabel = x.label || 'x';
    if (variables.x.units) {
      if (xLabel.includes(variables.x.units)) {
        jcampOptions.info.xUnits = xLabel;
      } else {
        jcampOptions.info.xUnits = `${xLabel} (${variables.x.units})`;
      }
    } else {
      jcampOptions.info.xUnits = xLabel;
    }
    const y = variables.y;
    const yLabel = y.label || 'y';
    if (variables.y.units) {
      if (yLabel.includes(variables.y.units)) {
        jcampOptions.info.xUnits = yLabel;
      } else {
        jcampOptions.info.yUnits = `${yLabel} (${variables.y.units})`;
      }
    } else {
      jcampOptions.info.yUnits = yLabel;
    }
    const xData = variables.x.data;
    const yData = variables.y.data;
    checkNumberOrArray(xData);
    checkNumberOrArray(yData);
    return fromJSON({
      x: xData,
      y: yData
    }, jcampOptions);
  } else {
    return creatorNtuples(variables, options);
  }
}

function toJcamps(analysis, options = {}) {
  const jcamps = [];
  for (const spectrum of analysis.spectra) {
    jcamps.push(getJcamp(spectrum, options));
  }
  return jcamps;
}
function getJcamp(spectrum, options) {
  const {
    info = {},
    meta = {}
  } = options;
  const jcampOptions = {
    info: {
      title: spectrum.title,
      dataType: spectrum.dataType,
      ...info
    },
    meta: {
      ...spectrum.meta,
      ...meta
    }
  };
  return fromVariables(spectrum.variables, jcampOptions);
}

function toJcamp(analysis, options = {}) {
  return toJcamps(analysis, options).join('\n');
}

/**
 * Based on a x value we will return a peak
 * if you set optimize=True the returned positions will be
 * the closest actual datapoints to the fitted peak location.
 * the x/y of the fitted peak will be in xOptimized and yOptimized
 * @param spectrum
 * @param target
 * @param options
 */
function peakPicking$1(spectrum, /** value to search (on x axis) */
target, options = {}) {
  const {
    xVariable = 'x',
    yVariable = 'y',
    optimize: optimize$1 = false,
    max: isMax = true,
    shape = {
      kind: 'gaussian',
      fwhm: 1
    }
  } = options;
  const x = spectrum.variables[xVariable]?.data;
  let y;
  if (!isMax) {
    y = spectrum.variables[yVariable]?.data.slice(); // do deep copy as we maybe need to flip sign
  } else {
    y = spectrum.variables[yVariable]?.data;
  }
  if (!x || !y) return;
  const targetIndex = xFindClosestIndex(x, target);
  let optimizedPeak;
  let optimizedIndex;
  const result = {};
  if (optimize$1) {
    if (!isMax) {
      const maximumY = xMaxValue(y);
      for (let i = 0; i < y.length; i++) {
        y[i] *= -1;
        y[i] += maximumY; // This makes it somewhat more robust
      }
    }
    optimizedPeak = optimize({
      x,
      y
    }, [{
      x: x[targetIndex],
      y: y[targetIndex]
    }], {
      shape
    });
    optimizedIndex = xFindClosestIndex(x, optimizedPeak.peaks[0].x);
    for (const [key, variable] of Object.entries(spectrum.variables)) {
      result[key] = variable.data[optimizedIndex];
    }
    result.optimized = optimizedPeak.peaks[0];
  } else {
    for (const [key, variable] of Object.entries(spectrum.variables)) {
      result[key] = variable.data[targetIndex];
    }
  }
  return result;
}

/**
 * Based on a x value we will return a peak
 * @param spectrum
 * @param options
 */
function autoPeakPicking$1(spectrum, options = {}) {
  const {
    xVariable = 'x',
    yVariable = 'y',
    normalizationOptions,
    minPeakWidth
  } = options;
  let x = spectrum.variables[xVariable]?.data;
  let y = spectrum.variables[yVariable]?.data;
  if (!x || !y) return [];
  if (normalizationOptions) {
    const tempSpectrum = {
      variables: {
        x: {
          data: x,
          label: ''
        },
        y: {
          data: y,
          label: ''
        }
      }
    };
    const normalizedSpectrum = getNormalizedSpectrum(tempSpectrum, normalizationOptions);
    x = normalizedSpectrum.variables.x.data;
    y = normalizedSpectrum.variables.y.data;
  }
  if (!x || !y) return;
  const {
    from,
    to
  } = options;
  let peaks = gsd({
    x,
    y
  }, options);
  if (normalizationOptions) {
    // we need to recalculate the real count
    const xyClosestYPoint = options.maxCriteria === undefined || options.maxCriteria ? xyMaxClosestYPoint : xyMinClosestYPoint;
    for (const peak of peaks) {
      const closest = xyClosestYPoint({
        x: spectrum.variables.x.data,
        y: spectrum.variables.y.data
      }, {
        target: peak.x
      });
      peak.x = closest.x;
      peak.y = closest.y;
    }
  }
  if (from !== undefined) {
    peaks = peaks.filter(peak => peak.x >= from);
  }
  if (to !== undefined) {
    peaks = peaks.filter(peak => peak.x <= to);
  }
  if (minPeakWidth) {
    peaks = peaks.filter(peak => peak.width >= minPeakWidth);
  }
  return peaks.map(peak => {
    const result = {};
    for (const [key, variable] of Object.entries(spectrum.variables)) {
      result[key] = variable.data[peak.index];
    }
    result.width = peak.width;
    return result;
  });
}

const JSGraph$1 = {
  getJSGraph,
  getNormalizationAnnotations
};

/**
 * Converts a peak from common-spectrum format to IR-specific format.
 * @param peak - Peak object with x, a, t properties.
 * @param spectrum - Spectrum containing variable metadata.
 * @returns Converted peak with wavenumber, absorbance, transmittance, and kind.
 */
function convertPeak(peak, spectrum) {
  const tVariable = spectrum.variables.t;
  return {
    wavenumber: peak.x,
    absorbance: peak.a,
    transmittance: peak.t / 100,
    kind: getPeakKind(peak.t, tVariable?.min ?? 0, tVariable?.max ?? 100)
  };
}
function getPeakKind(transmittance, minTransmittance, maxTransmittance) {
  const position = (maxTransmittance - transmittance) / (maxTransmittance - minTransmittance);
  if (position < 0.33) {
    return 'w';
  } else if (position < 0.66) {
    return 'm';
  }
  return 'S';
}

/**
 * Creates annotations for jsgraph that allows to display the result of peak picking.
 * @param peaks - Array of peaks with wavenumber, transmittance, absorbance, kind.
 * @param options - Display options for the annotations.
 * @returns Array of annotation objects for jsgraph.
 */
function getAnnotations(peaks, options = {}) {
  const {
    fillColor = 'green',
    strokeColor = 'red',
    creationFct,
    mode = 't100'
  } = options;
  const annotations = peaks.map(peak => {
    const annotation = {
      line: 1,
      type: 'rect',
      strokeColor,
      strokeWidth: 0,
      fillColor
    };
    if (creationFct) {
      creationFct(annotation, peak);
    }
    switch (mode) {
      case 'a':
        annotationAbsorbance(annotation, peak, options);
        break;
      case 't':
        annotationTransmittance(annotation, peak, 1, options);
        break;
      case 't100':
        annotationTransmittance(annotation, peak, 100, options);
        break;
    }
    return annotation;
  });
  return annotations;
}
function annotationTransmittance(annotation, peak, factor = 1, options = {}) {
  const {
    showKind = true,
    showAssignment = true
  } = options;
  const labels = [];
  let line = 0;
  if (showKind) {
    labels.push({
      text: peak.kind,
      size: '18px',
      anchor: 'middle',
      color: 'red',
      position: {
        x: peak.wavenumber,
        y: peak.transmittance * factor,
        dy: `${23 + line * 14}px`
      }
    });
    line++;
  }
  if (showAssignment) {
    labels.push({
      text: peak.assignment ?? '',
      size: '18px',
      anchor: 'middle',
      color: 'darkred',
      position: {
        x: peak.wavenumber,
        y: peak.transmittance * factor,
        dy: `${23 + line * 14}px`
      }
    });
    line++;
  }
  annotation.labels = labels;
  annotation.position = [{
    x: peak.wavenumber,
    y: peak.transmittance * factor,
    dy: '10px',
    dx: '-1px'
  }, {
    x: peak.wavenumber,
    y: peak.transmittance * factor,
    dy: '5px',
    dx: '1px'
  }];
}
function annotationAbsorbance(annotation, peak, options = {}) {
  const {
    showKind = true,
    showAssignment = true,
    assignmentAngle = -45
  } = options;
  const labels = [];
  let line = 0;
  if (showKind) {
    labels.push({
      text: peak.kind,
      size: '18px',
      anchor: 'middle',
      color: 'red',
      position: {
        x: peak.wavenumber,
        y: peak.absorbance,
        dy: `${ -15 - line * 14}px`
      }
    });
    line++;
  }
  if (showAssignment) {
    labels.push({
      text: peak.assignment ?? '',
      size: '18px',
      angle: assignmentAngle,
      anchor: 'left',
      color: 'darkred',
      position: {
        x: peak.wavenumber,
        y: peak.absorbance,
        dy: `${ -15 - line * 14}px`
      }
    });
    line++;
  }
  annotation.labels = labels;
  annotation.position = [{
    x: peak.wavenumber,
    y: peak.absorbance,
    dy: '-10px',
    dx: '-1px'
  }, {
    x: peak.wavenumber,
    y: peak.absorbance,
    dy: '-5px',
    dx: '1px'
  }];
}

/**
 * Callback that adds absorbance (a) and transmittance (t) variables to the spectrum.
 * If the y variable is absorbance, transmittance is computed and vice versa.
 * @param variables - Spectrum variables with at least x and y defined.
 * @returns The modified variables with a and t added.
 */
function spectrumCallback(variables) {
  // we add missing absorbance / transmittance
  // variable a = absorbance
  // variable t = transmittance
  const yVariable = variables.y;
  let isAbsorbance = true;
  if (yVariable.label.toLowerCase().includes('trans')) {
    isAbsorbance = false;
  }
  if (isAbsorbance) {
    variables.a = {
      ...yVariable,
      symbol: 'a',
      data: yVariable.data.slice()
    };
    variables.t = {
      data: yVariable.data.map(absorbance => 10 ** -absorbance * 100),
      label: 'Transmittance (%)',
      symbol: 't',
      units: ''
    };
  } else {
    const factor = yVariable.label.includes('%') || yVariable.label.toLowerCase().includes('percent') ? 100 : 1;
    variables.a = {
      data: yVariable.data.map(transmittance => -Math.log10(transmittance / factor)),
      symbol: 'a',
      label: 'Absorbance',
      units: ''
    };
    if (factor === 100) {
      variables.t = {
        ...yVariable,
        symbol: 't'
      };
      variables.t.data = variables.t.data.slice();
    } else {
      variables.t = {
        units: '',
        label: 'Transmittance (%)',
        symbol: 't',
        data: yVariable.data.map(transmittance => transmittance * 100)
      };
    }
  }
  return variables;
}

/**
 * Creates a new Analysis from a JCAMP string or buffer.
 * @param jcamp - JCAMP data as a string or ArrayBuffer.
 * @param options - Options for the analysis.
 * @returns New Analysis element with the given data.
 */
function fromJcamp(jcamp, options = {}) {
  const {
    spectrumCallback: spectrumCallback$1 = spectrumCallback,
    ...rest
  } = options;
  return fromJcamp$1(jcamp, {
    ...rest,
    spectrumCallback: spectrumCallback$1
  });
}

/**
 * Gives meaning to type codes.
 * @param  xzwType x, z or w type code.
 * @return  String corresponding to the code.
 */
function xzwTypes(xzwType) {
  switch (xzwType) {
    case 1:
      return 'Wavenumber (cm-1)';
    case 2:
      return 'Micrometers (um)';
    case 3:
      return 'Nanometers (nm)';
    case 4:
      return 'Seconds';
    case 5:
      return 'Minutes';
    case 6:
      return 'Hertz (Hz)';
    case 7:
      return 'Kilohertz (KHz)';
    case 8:
      return 'Megahertz (MHz)';
    case 9:
      return 'Mass (M/z)';
    case 10:
      return 'Parts per million (PPM)';
    case 11:
      return 'Days';
    case 12:
      return 'Years';
    case 13:
      return 'Raman Shift (cm-1)';
    case 14:
      return 'eV';
    case 15:
      return 0;
    case 16:
      return 'Diode Number';
    case 17:
      return 'Channel ';
    case 18:
      return 'Degrees';
    case 19:
      return 'Temperature (F)';
    case 20:
      return 'Temperature (C)';
    case 21:
      return 'Temperature (K)';
    case 22:
      return 'Data Points';
    case 23:
      return 'Milliseconds (mSec)';
    case 24:
      return 'Microseconds (uSec)';
    case 25:
      return 'Nanoseconds (nSec)';
    case 26:
      return 'Gigahertz (GHz)';
    case 27:
      return 'Centimeters (cm)';
    case 28:
      return 'Meters (m)';
    case 29:
      return 'Millimeters (mm)';
    case 30:
      return 'Hours';
    case 255:
      return 'Double interferogram';
    default:
      return 'Arbitrary';
  }
}
/**
 * Gives meaning to y type codes
 * @param  yType y type code
 * @return  String corresponding to the code
 */
function yTypes(yType) {
  switch (yType) {
    case 0:
      return 'Arbitrary Intensity';
    case 1:
      return 'Interferogram';
    case 2:
      return 'Absorbance';
    case 3:
      return 'Kubelka-Monk';
    case 4:
      return 'Counts';
    case 5:
      return 'Volts';
    case 6:
      return 'Degrees';
    case 7:
      return 'Milliamps';
    case 8:
      return 'Millimeters';
    case 9:
      return 'Millivolts';
    case 10:
      return 'Log(1/R)';
    case 11:
      return 'Percent';
    case 12:
      return 'Intensity';
    case 13:
      return 'Relative Intensity';
    case 14:
      return 'Energy';
    case 16:
      return 'Decibel';
    case 19:
      return 'Temperature (F)';
    case 20:
      return 'Temperature (C)';
    case 21:
      return 'Temperature (K)';
    case 22:
      return 'Index of Refraction [N]';
    case 23:
      return 'Extinction Coeff. [K]';
    case 24:
      return 'Real';
    case 25:
      return 'Imaginary';
    case 26:
      return 'Complex';
    case 128:
      return 'Transmission';
    case 129:
      return 'Reflectance';
    case 130:
      return 'Arbitrary or Single Beam with Valley Peaks';
    case 131:
      return 'Emission';
    default:
      return 'Reference Arbitrary Energy';
  }
}
/**
 * Convert code to experiment type
 * @param code
 * @returns type of experiment carried out.
 */
function experimentSettings(code) {
  switch (code) {
    case 1:
      return 'Gas Chromatogram';
    case 2:
      return 'General Chromatogram (same as SPCGEN with TCGRAM)';
    case 3:
      return 'HPLC Chromatogram';
    case 4:
      return 'FT-IR, FT-NIR, FT-Raman Spectrum or Igram (Can also be used for scanning IR.)';
    case 5:
      return 'NIR Spectrum (Usually multi-spectral data sets for calibration.)';
    case 7:
      return 'UV-VIS Spectrum (Can be used for single scanning UV-VIS-NIR.)';
    case 8:
      return 'X-ray Diffraction Spectrum';
    case 9:
      return 'Mass Spectrum  (Can be single, GC-MS, Continuum, Centroid or TOF.)';
    case 10:
      return 'NMR Spectrum or FID';
    case 11:
      return 'Raman Spectrum (Usually Diode Array, CCD, etc. use SPCFTIR for FT-Raman.)';
    case 12:
      return 'Fluorescence Spectrum';
    case 13:
      return 'Atomic Spectrum';
    case 14:
      return 'Chromatography Diode Array Spectra';
    default:
      return 'General SPC (could be anything)';
  }
}

/**
 * Gets the parameter in each bit of the flag
 *
 * @param  flag First byte of the main header.
 * @returns  The parameters.
 */
class FlagParameters {
  constructor(flag) {
    this.y16BitPrecision = (flag & 1) !== 0; //Y values are 16 bits instead of 32
    this.useExperimentExtension = (flag & 2) !== 0; //Enable experiment mode
    this.multiFile = (flag & 4) !== 0; //Multiple spectra (multifile)
    this.zValuesRandom = (flag & 8) !== 0; //Z values in random order if multiFile
    this.zValuesUneven = (flag & 16) !== 0; //Z values ordered but unevenly spaced if multi
    this.customAxisLabels = (flag & 32) !== 0; //Custom labels
    this.xyxy = (flag & 64) !== 0; //One X array per subfile, for discontinuous curves
    this.xy = (flag & 128) !== 0; // Non-evenly spaced X, X before Y
  }
}
/**
 * Gets the date encoded in binary in a long number.
 * @param  long Binary date.
 * @return  Date formatted to ISO 8601:2019 convention.
 */
function longToDate(long) {
  if (long === 0) {
    return '0000-00-00T00:00:00.00Z';
  }
  const date = new Date();
  date.setUTCFullYear(long >> 20);
  date.setUTCMonth((long >> 16 & 0x0f) - 1);
  date.setUTCDate(long >> 11 & 0x1f);
  date.setUTCHours(long >> 6 & 0x1f);
  date.setUTCMinutes(long & 0x3f);
  date.setUTCSeconds(0);
  date.setUTCMilliseconds(0);
  return date.toISOString();
}

/**
 * Old-format File-header parsing.
 * @param buffer spc buffer.
 * @param  prev `{parameters,fileversion}`
 * @return  file metadata
 */
class TheOldHeader {
  constructor(buffer, prev) {
    this.fileVersion = prev.fileVersion; //Each bit contains a parameter
    this.parameters = prev.parameters; //4B => New format; 4D => LabCalc format
    this.exponentY = buffer.readInt16(); //Word (16 bits) instead of byte
    this.numberPoints = buffer.readFloat32();
    this.startingX = buffer.readFloat32();
    this.endingX = buffer.readFloat32();
    this.xUnitsType = xzwTypes(buffer.readUint8());
    this.yUnitsType = yTypes(buffer.readUint8());
    const date = new Date();
    const zTypeYear = buffer.readUint16(); //Unrelated to Z axis
    date.setUTCFullYear(zTypeYear % 4096); // TODO: might be wrong
    date.setUTCMonth(Math.max(buffer.readUint8() - 1, 0));
    date.setUTCDate(buffer.readUint8());
    date.setUTCHours(buffer.readUint8());
    date.setUTCMinutes(buffer.readUint8());
    this.date = date.toISOString();
    this.resolutionDescription = buffer.readChars(8).replace(/\x00/g, '').trim();
    this.peakPointNumber = buffer.readUint16();
    this.scans = buffer.readUint16();
    this.spare = [];
    for (let i = 0; i < 7; i++) {
      this.spare.push(buffer.readFloat32());
    }
    this.memo = buffer.readChars(130).replace(/\x00/g, '').trim();
    this.xyzLabels = buffer.readChars(30).replace(/\x00/g, '').trim();
  }
}
/**
 * New format file-header parsing.
 * @param buffer spc buffer.
 * @param  prev `{parameters,fileversion}`
 * @return  file metadata
 */
class TheNewHeader {
  constructor(buffer, prev) {
    this.fileVersion = prev.fileVersion; //Each bit contains a parameter
    this.parameters = prev.parameters; //4B => New format; 4D => LabCalc format
    this.experimentType = experimentSettings(buffer.readUint8()); //Experiment type code (See SPC.h)
    this.exponentY = buffer.readInt8(); //Exponent for Y values (80h = floating point): FloatY = (2^Exp)*IntY/(2^32) 32-bit; FloatY = (2^Exp)*IntY/(2^16) 32-bit
    this.numberPoints = buffer.readUint32(); //Number of points (if not XYXY)
    this.startingX = buffer.readFloat64(); //First X coordinate
    this.endingX = buffer.readFloat64(); //Last X coordinate
    this.spectra = buffer.readUint32(); //Number of spectrums
    this.xUnitsType = xzwTypes(buffer.readUint8()); //X Units type code (See types.js)
    this.yUnitsType = yTypes(buffer.readUint8()); //Y ""
    this.zUnitsType = xzwTypes(buffer.readUint8()); //Z ""
    this.postingDisposition = buffer.readUint8(); //Posting disposition (See GRAMSDDE.H)
    this.date = longToDate(buffer.readUint32()); //Date: minutes = first 6 bits, hours = 5 next bits, days = 5 next, months = 4 next, years = 12 last
    this.resolutionDescription = buffer.readChars(9).replace(/\x00/g, '').trim(); //Resolution description text
    this.sourceInstrumentDescription = buffer.readChars(9).replace(/\x00/g, '').trim(); // Source Instrument description text
    this.peakPointNumber = buffer.readUint16(); //Peak point number for interferograms
    this.spare = [];
    for (let i = 0; i < 8; i++) {
      this.spare.push(buffer.readFloat32());
    }
    if (this.fileVersion === 0x4c) {
      //Untested case because no test files
      this.spare.reverse();
    }
    this.memo = buffer.readChars(130).replace(/\x00/g, '').trim();
    this.xyzLabels = buffer.readChars(30).replace(/\x00/g, '').trim();
    this.logOffset = buffer.readUint32(); //Byte offset to Log Block
    this.modifiedFlag = buffer.readUint32(); //File modification flag (See values in SPC.H)
    this.processingCode = buffer.readUint8(); //Processing code (See GRAMSDDE.H)
    this.calibrationLevel = buffer.readUint8(); //Calibration level + 1
    this.subMethodSampleInjectionNumber = buffer.readUint16(); //Sub-method sample injection number
    this.concentrationFactor = buffer.readFloat32(); //Floating data multiplier concentration factor
    this.methodFile = buffer.readChars(48).replace(/\x00/g, '').trim(); //Method file
    this.zSubIncrement = buffer.readFloat32(); //Z subfile increment for even Z Multifiles
    this.wPlanes = buffer.readUint32();
    this.wPlaneIncrement = buffer.readFloat32();
    this.wAxisUnits = xzwTypes(buffer.readUint8()); //W axis units code
    this.reserved = buffer.readChars(187).replace(/\x00/g, '').trim(); //Reserved space (Must be zero)
    if (this.xUnitsType === 0) {
      this.xUnitsType = this.xyzLabels.substring(0, 10);
    }
    if (this.zUnitsType === 0) {
      this.zUnitsType = this.xyzLabels.substring(20, 30);
    }
  }
}
/**
 * File-header parsing - First 512/256 bytes (new/old format).
 * @param buffer SPC buffer.
 * @return File-header object
 */
function fileHeader(buffer) {
  const parameters = new FlagParameters(buffer.readUint8()); //Each bit contains a parameter
  const fileVersion = buffer.readUint8(); //4B => New format; 4D => LabCalc format
  const headerOpts = {
    parameters,
    fileVersion
  };
  switch (fileVersion) {
    case 0x4b:
      // new format
      break;
    case 0x4c:
      buffer.setBigEndian();
      break;
    case 0x4d:
      {
        // old LabCalc format
        return new TheOldHeader(buffer, headerOpts);
      }
    default:
      throw new Error('Unrecognized file format: byte 01 must be either 4B, 4C or 4D');
  }
  return new TheNewHeader(buffer, headerOpts);
}

/** Get how the data was stored
 * @param multiFile - whether there are multiple spectra (subfiles) or not.
 * @param xy - uneven x values
 * @param xyxy - multifile with separate x axis
 * @return the shape of the data as a string
 */
function getDataShape({
  multiFile,
  xy,
  xyxy
}) {
  /* single file */
  if (!multiFile) {
    // Y or XY,
    return !xy ? 'Y' : xyxy ? 'exception' : 'XY';
  }
  /* then multifile */
  if (!xy) {
    /* even X - equidistant */
    return 'YY';
  } else {
    // uneven x
    return !xyxy ? 'XYY' : 'XYXY';
  }
}

function decode(bytes, encoding = 'utf8') {
  const decoder = new TextDecoder(encoding);
  return decoder.decode(bytes);
}
const encoder = new TextEncoder();
function encode(str) {
  return encoder.encode(str);
}

const defaultByteLength = 1024 * 8;
const hostBigEndian = (() => {
  const array = new Uint8Array(4);
  const view = new Uint32Array(array.buffer);
  return !((view[0] = 1) & array[0]);
})();
const typedArrays = {
  int8: globalThis.Int8Array,
  uint8: globalThis.Uint8Array,
  int16: globalThis.Int16Array,
  uint16: globalThis.Uint16Array,
  int32: globalThis.Int32Array,
  uint32: globalThis.Uint32Array,
  uint64: globalThis.BigUint64Array,
  int64: globalThis.BigInt64Array,
  float32: globalThis.Float32Array,
  float64: globalThis.Float64Array
};
class IOBuffer {
  /**
   * Reference to the internal ArrayBuffer object.
   */
  buffer;
  /**
   * Byte length of the internal ArrayBuffer.
   */
  byteLength;
  /**
   * Byte offset of the internal ArrayBuffer.
   */
  byteOffset;
  /**
   * Byte length of the internal ArrayBuffer.
   */
  length;
  /**
   * The current offset of the buffer's pointer.
   */
  offset;
  lastWrittenByte;
  littleEndian;
  _data;
  _mark;
  _marks;
  /**
   * Create a new IOBuffer.
   * @param data - The data to construct the IOBuffer with.
   * If data is a number, it will be the new buffer's length<br>
   * If data is `undefined`, the buffer will be initialized with a default length of 8Kb<br>
   * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,
   * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.
   * @param options - An object for the options.
   * @returns A new IOBuffer instance.
   */
  constructor(data = defaultByteLength, options = {}) {
    let dataIsGiven = false;
    if (typeof data === 'number') {
      data = new ArrayBuffer(data);
    } else {
      dataIsGiven = true;
      this.lastWrittenByte = data.byteLength;
    }
    const offset = options.offset ? options.offset >>> 0 : 0;
    const byteLength = data.byteLength - offset;
    let dvOffset = offset;
    if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {
      if (data.byteLength !== data.buffer.byteLength) {
        dvOffset = data.byteOffset + offset;
      }
      data = data.buffer;
    }
    if (dataIsGiven) {
      this.lastWrittenByte = byteLength;
    } else {
      this.lastWrittenByte = 0;
    }
    this.buffer = data;
    this.length = byteLength;
    this.byteLength = byteLength;
    this.byteOffset = dvOffset;
    this.offset = 0;
    this.littleEndian = true;
    this._data = new DataView(this.buffer, dvOffset, byteLength);
    this._mark = 0;
    this._marks = [];
  }
  /**
   * Checks if the memory allocated to the buffer is sufficient to store more
   * bytes after the offset.
   * @param byteLength - The needed memory in bytes.
   * @returns `true` if there is sufficient space and `false` otherwise.
   */
  available(byteLength = 1) {
    return this.offset + byteLength <= this.length;
  }
  /**
   * Check if little-endian mode is used for reading and writing multi-byte
   * values.
   * @returns `true` if little-endian mode is used, `false` otherwise.
   */
  isLittleEndian() {
    return this.littleEndian;
  }
  /**
   * Set little-endian mode for reading and writing multi-byte values.
   * @returns This.
   */
  setLittleEndian() {
    this.littleEndian = true;
    return this;
  }
  /**
   * Check if big-endian mode is used for reading and writing multi-byte values.
   * @returns `true` if big-endian mode is used, `false` otherwise.
   */
  isBigEndian() {
    return !this.littleEndian;
  }
  /**
   * Switches to big-endian mode for reading and writing multi-byte values.
   * @returns This.
   */
  setBigEndian() {
    this.littleEndian = false;
    return this;
  }
  /**
   * Move the pointer n bytes forward.
   * @param n - Number of bytes to skip.
   * @returns This.
   */
  skip(n = 1) {
    this.offset += n;
    return this;
  }
  /**
   * Move the pointer n bytes backward.
   * @param n - Number of bytes to move back.
   * @returns This.
   */
  back(n = 1) {
    this.offset -= n;
    return this;
  }
  /**
   * Move the pointer to the given offset.
   * @param offset - The offset to move to.
   * @returns This.
   */
  seek(offset) {
    this.offset = offset;
    return this;
  }
  /**
   * Store the current pointer offset.
   * @see {@link IOBuffer#reset}
   * @returns This.
   */
  mark() {
    this._mark = this.offset;
    return this;
  }
  /**
   * Move the pointer back to the last pointer offset set by mark.
   * @see {@link IOBuffer#mark}
   * @returns This.
   */
  reset() {
    this.offset = this._mark;
    return this;
  }
  /**
   * Push the current pointer offset to the mark stack.
   * @see {@link IOBuffer#popMark}
   * @returns This.
   */
  pushMark() {
    this._marks.push(this.offset);
    return this;
  }
  /**
   * Pop the last pointer offset from the mark stack, and set the current
   * pointer offset to the popped value.
   * @see {@link IOBuffer#pushMark}
   * @returns This.
   */
  popMark() {
    const offset = this._marks.pop();
    if (offset === undefined) {
      throw new Error('Mark stack empty');
    }
    this.seek(offset);
    return this;
  }
  /**
   * Move the pointer offset back to 0.
   * @returns This.
   */
  rewind() {
    this.offset = 0;
    return this;
  }
  /**
   * Make sure the buffer has sufficient memory to write a given byteLength at
   * the current pointer offset.
   * If the buffer's memory is insufficient, this method will create a new
   * buffer (a copy) with a length that is twice (byteLength + current offset).
   * @param byteLength - The needed memory in bytes.
   * @returns This.
   */
  ensureAvailable(byteLength = 1) {
    if (!this.available(byteLength)) {
      const lengthNeeded = this.offset + byteLength;
      const newLength = lengthNeeded * 2;
      const newArray = new Uint8Array(newLength);
      newArray.set(new Uint8Array(this.buffer));
      this.buffer = newArray.buffer;
      this.length = newLength;
      this.byteLength = newLength;
      this._data = new DataView(this.buffer);
    }
    return this;
  }
  /**
   * Read a byte and return false if the byte's value is 0, or true otherwise.
   * Moves pointer forward by one byte.
   * @returns The read boolean.
   */
  readBoolean() {
    return this.readUint8() !== 0;
  }
  /**
   * Read a signed 8-bit integer and move pointer forward by 1 byte.
   * @returns The read byte.
   */
  readInt8() {
    return this._data.getInt8(this.offset++);
  }
  /**
   * Read an unsigned 8-bit integer and move pointer forward by 1 byte.
   * @returns The read byte.
   */
  readUint8() {
    return this._data.getUint8(this.offset++);
  }
  /**
   * Alias for {@link IOBuffer#readUint8}.
   * @returns The read byte.
   */
  readByte() {
    return this.readUint8();
  }
  /**
   * Read `n` bytes and move pointer forward by `n` bytes.
   * @param n - Number of bytes to read.
   * @returns The read bytes.
   */
  readBytes(n = 1) {
    return this.readArray(n, 'uint8');
  }
  /**
   * Creates an array of corresponding to the type `type` and size `size`.
   * For example type `uint8` will create a `Uint8Array`.
   * @param size - size of the resulting array
   * @param type - number type of elements to read
   * @returns The read array.
   */
  readArray(size, type) {
    const bytes = typedArrays[type].BYTES_PER_ELEMENT * size;
    const offset = this.byteOffset + this.offset;
    const slice = this.buffer.slice(offset, offset + bytes);
    if (this.littleEndian === hostBigEndian && type !== 'uint8' && type !== 'int8') {
      const slice = new Uint8Array(this.buffer.slice(offset, offset + bytes));
      slice.reverse();
      const returnArray = new typedArrays[type](slice.buffer);
      this.offset += bytes;
      returnArray.reverse();
      return returnArray;
    }
    const returnArray = new typedArrays[type](slice);
    this.offset += bytes;
    return returnArray;
  }
  /**
   * Read a 16-bit signed integer and move pointer forward by 2 bytes.
   * @returns The read value.
   */
  readInt16() {
    const value = this._data.getInt16(this.offset, this.littleEndian);
    this.offset += 2;
    return value;
  }
  /**
   * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.
   * @returns The read value.
   */
  readUint16() {
    const value = this._data.getUint16(this.offset, this.littleEndian);
    this.offset += 2;
    return value;
  }
  /**
   * Read a 32-bit signed integer and move pointer forward by 4 bytes.
   * @returns The read value.
   */
  readInt32() {
    const value = this._data.getInt32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
  }
  /**
   * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.
   * @returns The read value.
   */
  readUint32() {
    const value = this._data.getUint32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
  }
  /**
   * Read a 32-bit floating number and move pointer forward by 4 bytes.
   * @returns The read value.
   */
  readFloat32() {
    const value = this._data.getFloat32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
  }
  /**
   * Read a 64-bit floating number and move pointer forward by 8 bytes.
   * @returns The read value.
   */
  readFloat64() {
    const value = this._data.getFloat64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
  }
  /**
   * Read a 64-bit signed integer number and move pointer forward by 8 bytes.
   * @returns The read value.
   */
  readBigInt64() {
    const value = this._data.getBigInt64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
  }
  /**
   * Read a 64-bit unsigned integer number and move pointer forward by 8 bytes.
   * @returns The read value.
   */
  readBigUint64() {
    const value = this._data.getBigUint64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
  }
  /**
   * Read a 1-byte ASCII character and move pointer forward by 1 byte.
   * @returns The read character.
   */
  readChar() {
    // eslint-disable-next-line unicorn/prefer-code-point
    return String.fromCharCode(this.readInt8());
  }
  /**
   * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.
   * @param n - Number of characters to read.
   * @returns The read characters.
   */
  readChars(n = 1) {
    let result = '';
    for (let i = 0; i < n; i++) {
      result += this.readChar();
    }
    return result;
  }
  /**
   * Read the next `n` bytes, return a UTF-8 decoded string and move pointer
   * forward by `n` bytes.
   * @param n - Number of bytes to read.
   * @returns The decoded string.
   */
  readUtf8(n = 1) {
    return decode(this.readBytes(n));
  }
  /**
   * Read the next `n` bytes, return a string decoded with `encoding` and move pointer
   * forward by `n` bytes.
   * If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}
   * @param n - Number of bytes to read.
   * @param encoding - The encoding to use. Default is 'utf8'.
   * @returns The decoded string.
   */
  decodeText(n = 1, encoding = 'utf8') {
    return decode(this.readBytes(n), encoding);
  }
  /**
   * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
   * forward by 1 byte.
   * @param value - The value to write.
   * @returns This.
   */
  writeBoolean(value) {
    this.writeUint8(value ? 0xff : 0x00);
    return this;
  }
  /**
   * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.
   * @param value - The value to write.
   * @returns This.
   */
  writeInt8(value) {
    this.ensureAvailable(1);
    this._data.setInt8(this.offset++, value);
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as an 8-bit unsigned integer and move pointer forward by 1
   * byte.
   * @param value - The value to write.
   * @returns This.
   */
  writeUint8(value) {
    this.ensureAvailable(1);
    this._data.setUint8(this.offset++, value);
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * An alias for {@link IOBuffer#writeUint8}.
   * @param value - The value to write.
   * @returns This.
   */
  writeByte(value) {
    return this.writeUint8(value);
  }
  /**
   * Write all elements of `bytes` as uint8 values and move pointer forward by
   * `bytes.length` bytes.
   * @param bytes - The array of bytes to write.
   * @returns This.
   */
  writeBytes(bytes) {
    this.ensureAvailable(bytes.length);
    // eslint-disable-next-line @typescript-eslint/prefer-for-of
    for (let i = 0; i < bytes.length; i++) {
      this._data.setUint8(this.offset++, bytes[i]);
    }
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 16-bit signed integer and move pointer forward by 2
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeInt16(value) {
    this.ensureAvailable(2);
    this._data.setInt16(this.offset, value, this.littleEndian);
    this.offset += 2;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 16-bit unsigned integer and move pointer forward by 2
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeUint16(value) {
    this.ensureAvailable(2);
    this._data.setUint16(this.offset, value, this.littleEndian);
    this.offset += 2;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 32-bit signed integer and move pointer forward by 4
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeInt32(value) {
    this.ensureAvailable(4);
    this._data.setInt32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 32-bit unsigned integer and move pointer forward by 4
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeUint32(value) {
    this.ensureAvailable(4);
    this._data.setUint32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 32-bit floating number and move pointer forward by 4
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeFloat32(value) {
    this.ensureAvailable(4);
    this._data.setFloat32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 64-bit floating number and move pointer forward by 8
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeFloat64(value) {
    this.ensureAvailable(8);
    this._data.setFloat64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 64-bit signed bigint and move pointer forward by 8
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeBigInt64(value) {
    this.ensureAvailable(8);
    this._data.setBigInt64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 64-bit unsigned bigint and move pointer forward by 8
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeBigUint64(value) {
    this.ensureAvailable(8);
    this._data.setBigUint64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write the charCode of `str`'s first character as an 8-bit unsigned integer
   * and move pointer forward by 1 byte.
   * @param str - The character to write.
   * @returns This.
   */
  writeChar(str) {
    // eslint-disable-next-line unicorn/prefer-code-point
    return this.writeUint8(str.charCodeAt(0));
  }
  /**
   * Write the charCodes of all `str`'s characters as 8-bit unsigned integers
   * and move pointer forward by `str.length` bytes.
   * @param str - The characters to write.
   * @returns This.
   */
  writeChars(str) {
    for (let i = 0; i < str.length; i++) {
      // eslint-disable-next-line unicorn/prefer-code-point
      this.writeUint8(str.charCodeAt(i));
    }
    return this;
  }
  /**
   * UTF-8 encode and write `str` to the current pointer offset and move pointer
   * forward according to the encoded length.
   * @param str - The string to write.
   * @returns This.
   */
  writeUtf8(str) {
    return this.writeBytes(encode(str));
  }
  /**
   * Export a Uint8Array view of the internal buffer.
   * The view starts at the byte offset and its length
   * is calculated to stop at the last written byte or the original length.
   * @returns A new Uint8Array view.
   */
  toArray() {
    return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);
  }
  /**
   *  Get the total number of bytes written so far, regardless of the current offset.
   * @returns - Total number of bytes.
   */
  getWrittenByteLength() {
    return this.lastWrittenByte - this.byteOffset;
  }
  /**
   * Update the last written byte offset
   * @private
   */
  _updateLastWrittenByte() {
    if (this.offset > this.lastWrittenByte) {
      this.lastWrittenByte = this.offset;
    }
  }
}

/** Ensures x-values are increasing in magnitude. It reverses y if x was reversed.
 *
 * * Does not mutate arrays
 * * Assumes that X is either increasing or decreasing, not any random order.
 * * Expects x and y to be the same length
 * @param x - array of x values
 * @param y - array of y values
 * @returns [x,y] tuple
 */
function ensureIncreasingXValues(x, y) {
  const xL = x.length;
  if (xL !== 0) {
    if (y.length !== xL) {
      //wouldn't really make sense for x and y to be !==
      throw new RangeError('x and y length must be the same');
    }
    const firstX = x[0];
    const lastX = x[x.length - 1];
    if (firstX > lastX) {
      //apparently slice(0) faster than slice()
      return [x.slice(0).reverse(), y.slice(0).reverse()];
    }
  }
  return [x, y];
}

/**
 * Gets the Subfile flags.
 *
 * @param  flag First byte of the subheader.
 * @return The parameters.
 */
class SubFlagParameters {
  constructor(flag) {
    this.changed = (flag & 1) !== 0;
    this.noPeakTable = (flag & 8) !== 0;
    this.modifiedArithmetic = (flag & 128) !== 0;
  }
}
/**
 * Parses the subheader (header of the subfile)
 *
 * @param buffer SPC buffer.
 * @return subheader object
 */
class SubHeader {
  constructor(buffer) {
    this.parameters = new SubFlagParameters(buffer.readUint8());
    this.exponentY = buffer.readInt8();
    this.indexNumber = buffer.readUint16();
    this.startingZ = buffer.readFloat32();
    this.endingZ = buffer.readFloat32();
    this.noiseValue = buffer.readFloat32();
    this.numberPoints = buffer.readUint32();
    this.numberCoAddedScans = buffer.readUint32();
    this.wAxisValue = buffer.readFloat32();
    this.reserved = buffer.readChars(4).replace(/\x00/g, '').trim();
  }
}
/**
 * Set the X and Y axis (object with labels, values etc.)
 * @param x
 * @param y
 * @param fileHeader
 * @return object with x and y as axis.
 */
function setXYAxis(x, y, fileHeader) {
  var _a, _b, _c, _d;
  const xAxis = /(?<label>.*?) ?[([](?<units>.*)[)\]]/.exec(fileHeader.xUnitsType);
  const yAxis = /(?<label>.*?) ?[([](?<units>.*)[)\]]/.exec(fileHeader.yUnitsType);
  const [oX, oY] = ensureIncreasingXValues(x, y);
  const variables = {
    x: {
      symbol: 'x',
      label: ((_a = xAxis === null || xAxis === void 0 ? void 0 : xAxis.groups) === null || _a === void 0 ? void 0 : _a.label) || fileHeader.xUnitsType,
      units: ((_b = xAxis === null || xAxis === void 0 ? void 0 : xAxis.groups) === null || _b === void 0 ? void 0 : _b.units) || '',
      data: oX,
      isDependent: false
    },
    y: {
      symbol: 'y',
      label: ((_c = yAxis === null || yAxis === void 0 ? void 0 : yAxis.groups) === null || _c === void 0 ? void 0 : _c.label) || fileHeader.yUnitsType,
      units: ((_d = yAxis === null || yAxis === void 0 ? void 0 : yAxis.groups) === null || _d === void 0 ? void 0 : _d.units) || '',
      data: oY,
      isDependent: true
    }
  };
  return variables;
}

/**
 * Reads the data block of the SPC file.
 *
 * @param buffer spc buffer.
 * @param fileHeader main header.
 * @return Array containing the spectra.
 */
function newDataBlock(buffer, fileHeader) {
  let x;
  const spectra = [];
  const dataShape = getDataShape(fileHeader.parameters);
  if (dataShape === 'XY' || dataShape === 'XYY') {
    //for these ones, X axis comes before subheader !!
    x = new Float64Array(fileHeader.numberPoints);
    for (let i = 0; i < fileHeader.numberPoints; i++) {
      x[i] = buffer.readFloat32();
    }
  } else if (dataShape === 'YY' || dataShape === 'Y') {
    //for these ones, no X axis, we create it as we have all parameters
    x = createFromToArray({
      from: fileHeader.startingX,
      to: fileHeader.endingX,
      length: fileHeader.numberPoints
    });
  }
  for (let i = 0; i < fileHeader.spectra; i++) {
    // here Y is set (runs only once for a single spectra.)
    const subFileHeader = new SubHeader(buffer);
    // set X for the remaining cases if neccesary
    if (dataShape === 'XYXY' || dataShape === 'exception') {
      x = new Float64Array(subFileHeader.numberPoints);
      for (let j = 0; j < x.length; j++) {
        x[j] = buffer.readFloat32();
      }
    }
    const y = getNewY(new Float64Array(x.length), subFileHeader, fileHeader, buffer);
    const variables = setXYAxis(x, y, fileHeader);
    spectra.push({
      meta: subFileHeader,
      variables
    });
  }
  return spectra;
}
function getNewY(y, subHeader, fileHeader, buffer) {
  const {
    exponentY,
    parameters: {
      y16BitPrecision
    }
  } = fileHeader;
  if (subHeader.exponentY === 0) {
    subHeader.exponentY = exponentY;
  }
  const yFactor = 2 ** (subHeader.exponentY - (y16BitPrecision ? 16 : 32));
  if (y16BitPrecision) {
    for (let j = 0; j < y.length; j++) {
      y[j] = buffer.readInt16() * yFactor;
    }
  } else {
    for (let j = 0; j < y.length; j++) {
      if (subHeader.exponentY !== -128) {
        y[j] = buffer.readInt32() * yFactor;
      } else {
        y[j] = buffer.readFloat32();
      }
    }
  }
  return y;
}

/**
 * Reads a file's data block (old SPC format)
 *
 * @param buffer spc buffer.
 * @param fileHeader header.
 * @return Array containing the spectra.
 */
function oldDataBlock(buffer, fileHeader) {
  // either Y or YY fall on the for loop
  const spectra = [];
  // old format uses always equidistant arrays
  const x = createFromToArray({
    from: fileHeader.startingX,
    to: fileHeader.endingX,
    length: fileHeader.numberPoints
  });
  for (let i = 0; buffer.offset + fileHeader.numberPoints < buffer.length; i++) {
    const subFileHeader = new SubHeader(buffer);
    const y = getOldY(new Float64Array(x.length), subFileHeader, fileHeader, buffer);
    const variables = setXYAxis(x, y, fileHeader);
    spectra.push({
      meta: subFileHeader,
      variables
    });
  }
  return spectra;
}
/**
 *
 *
 * @export
 * @param {Float64Array} y
 * @param {SubHeader} subHeader
 * @param {TheOldHeader} fileHeader
 * @param {IOBuffer} buffer
 * @return {*}
 */
function getOldY(y, subHeader, fileHeader, buffer) {
  const {
    fileVersion,
    exponentY,
    parameters: {
      y16BitPrecision
    }
  } = fileHeader;
  if (subHeader.exponentY === 0) {
    subHeader.exponentY = exponentY;
  }
  const yFactor = 2 ** (subHeader.exponentY - (y16BitPrecision ? 16 : 32));
  if (y16BitPrecision) {
    for (let j = 0; j < y.length; j++) {
      y[j] = buffer.readInt16() * yFactor;
    }
  } else {
    for (let j = 0; j < y.length; j++) {
      if (fileVersion === 0x4d) {
        y[j] = ((buffer.readUint8() << 16) + (buffer.readInt8() << 24) + (buffer.readUint8() << 0) + (buffer.readUint8() << 8)) * yFactor;
      }
    }
  }
  return y;
}

/**
 *
 * @param  buffer SPC buffer.
 * @param  logOffset Offset of the log (from mainHeader).
 * @return  Object containing log meta, data and text.
 */
function readLogBlock(buffer, logOffset) {
  const logHeader = {
    size: buffer.readUint32(),
    //Size of the block in bytes
    memorySize: buffer.readUint32(),
    //Size of the memory rounded up to nearest multiple of 4096
    textOffset: buffer.readUint32(),
    //Offset to Text section
    binarySize: buffer.readUint32(),
    //Size of binary log block
    diskArea: buffer.readUint32(),
    //Size of the disk area
    reserved: buffer.readChars(44).trim().replace(/\x00/g, '') //Reserved space
  };
  const logData = buffer.readChars(logHeader.binarySize);
  buffer.offset = logOffset + logHeader.textOffset;
  const logASCII = buffer.readChars(logHeader.size - logHeader.textOffset).trim().replace(/\x00/g, '');
  return {
    meta: logHeader,
    data: logData,
    text: logASCII
  };
}

/**
 * Parses an SPC file.
 *
 * @param  buffer SPC file buffer.
 * @return JSON-like object with information contained in the SPC file.
 */
function parse(buffer) {
  const ioBuffer = new IOBuffer(buffer);
  const meta = fileHeader(ioBuffer);
  if (meta instanceof TheNewHeader) {
    //new format
    const spectra = newDataBlock(ioBuffer, meta);
    const logs = meta.logOffset !== 0 ? readLogBlock(ioBuffer, meta.logOffset) : null;
    return {
      meta,
      spectra,
      logs
    };
  } else {
    //old format
    return {
      meta,
      spectra: oldDataBlock(ioBuffer, meta)
    };
  }
}

/**
 * Creates a new Analysis from an SPC buffer.
 * @param buffer - SPC file buffer.
 * @param options - Options for the analysis.
 * @returns New Analysis element with the given data.
 */
function fromSPC(buffer, options = {}) {
  const {
    spectrumCallback: spectrumCallback$1 = spectrumCallback,
    ...rest
  } = options;
  const analysis = new Analysis({
    ...rest,
    spectrumCallback: spectrumCallback$1
  });
  const result = parse(buffer);
  const {
    parameters: _resultParameters,
    ...resultMeta
  } = result.meta;
  for (const spectrum of result.spectra) {
    const {
      parameters: _spectrumParameters,
      ...spectrumMeta
    } = spectrum.meta ?? {};
    analysis.pushSpectrum(spectrum.variables, {
      dataType: 'IR SPECTRUM',
      title: '',
      meta: {
        ...resultMeta,
        ...spectrumMeta
      }
    });
  }
  return analysis;
}

/**
 * Picks a single peak closest to the given target wavenumber.
 * @param spectrum - The spectrum to pick from.
 * @param target - Target wavenumber value.
 * @param options - Peak picking options.
 * @returns The converted peak or undefined if no peak is found.
 */
function peakPicking(spectrum, target, options) {
  const peak = peakPicking$1(spectrum, target, options);
  if (!peak) return undefined;
  return convertPeak(peak, spectrum);
}
/**
 * Automatically picks all peaks in the spectrum.
 * @param spectrum - The spectrum to pick from.
 * @param options - Auto peak picking options.
 * @returns Array of converted peaks.
 */
function autoPeakPicking(spectrum, options) {
  const peaks = autoPeakPicking$1(spectrum, options);
  if (!peaks) return [];
  return peaks.map(peak => convertPeak(peak, spectrum));
}
const JSGraph = {
  ...JSGraph$1,
  getAnnotations
};

export { AnalysesManager, Analysis, JSGraph, autoPeakPicking, fromJcamp, fromSPC, peakPicking, toJcamp };
//# sourceMappingURL=ir-spectrum.esm.js.map
