{"version":3,"file":"ml-spectra-fitting.esm.min.js","sources":["../node_modules/is-any-array/lib/index.js","../node_modules/ml-spectra-processing/lib/x/xCheck.js","../node_modules/ml-spectra-processing/lib/x/xFindClosestIndex.js","../node_modules/ml-spectra-processing/lib/x/xGetFromToIndex.js","../node_modules/ml-matrix/matrix.js","../node_modules/ml-matrix/matrix.mjs","../node_modules/ml-spectra-processing/lib/x/xMean.js","../node_modules/ml-spectra-processing/lib/x/xMaxValue.js","../node_modules/ml-spectra-processing/lib/x/xMinValue.js","../node_modules/ml-spectra-processing/lib/x/xNorm.js","../lib/util/assert.js","../lib/util/buildOptimizationLayout.js","../lib/util/reconstructPeaks.js","../node_modules/ml-peak-shape-generator/lib/util/constants.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/gaussian/Gaussian.js","../node_modules/ml-peak-shape-generator/lib/util/erfinv.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/lorentzian/Lorentzian.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/lorentzianDispersive/LorentzianDispersive.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/pseudoVoigt/computeFactor.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/pseudoVoigt/PseudoVoigt.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/pseudoVoigtTCH/PseudoVoigtTCH.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/generalizedLorentzian/GeneralizedLorentzian.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/splitGaussian/SplitGaussian.js","../node_modules/ml-peak-shape-generator/lib/shapes/1d/getShape1D.js","../lib/util/internalPeaks/DefaultParameters.js","../lib/util/internalPeaks/getInternalPeaks.js","../node_modules/ml-levenberg-marquardt/lib/check_options.js","../node_modules/ml-levenberg-marquardt/lib/error_calculation.js","../node_modules/ml-levenberg-marquardt/lib/step.js","../node_modules/ml-levenberg-marquardt/lib/gradient_function.js","../node_modules/ml-levenberg-marquardt/lib/levenberg_marquardt.js","../node_modules/ml-direct/src/util/antiLowerConvexHull.js","../node_modules/ml-direct/src/index.js","../lib/util/wrappers/directOptimization.js","../lib/index.js","../node_modules/ml-spectra-processing/lib/x/xMaxAbsoluteValue.js","../lib/util/selectMethod.js","../lib/shapes/getSumOfShapes.js","../lib/util/getFixedParametersResult.js"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n/**\n * Checks if an object is an instance of an Array (array or typed array, except those that contain bigint values).\n * @param value - Object to check.\n * @returns True if the object is an array or a typed array.\n */\nexport function isAnyArray(value) {\n    const tag = toString.call(value);\n    return tag.endsWith('Array]') && !tag.includes('Big');\n}\n//# sourceMappingURL=index.js.map","import { isAnyArray } from 'is-any-array';\n/**\n * Checks if the input is a non-empty array of numbers.\n * Only checks the first element.\n * @param input - array to check.\n * @param options - additional checks.\n */\nexport function xCheck(input, options = {}) {\n    const { minLength = 1 } = options;\n    if (!isAnyArray(input)) {\n        throw new TypeError('input must be an array');\n    }\n    if (input.length === 0) {\n        throw new TypeError('input must not be empty');\n    }\n    if (typeof input[0] !== 'number') {\n        throw new TypeError('input must contain numbers');\n    }\n    if (input.length < minLength) {\n        throw new Error(`input must have a length of at least ${minLength}`);\n    }\n}\n//# sourceMappingURL=xCheck.js.map","/**\n * Returns the closest index of a `target`\n * @param array - array of numbers.\n * @param target - target value.\n * @param options - options.\n * @returns closest index.\n */\nexport function xFindClosestIndex(array, target, options = {}) {\n    const { sorted = true } = options;\n    if (sorted) {\n        let low = 0;\n        let high = array.length - 1;\n        let middle = 0;\n        while (high - low > 1) {\n            middle = low + ((high - low) >> 1);\n            if (array[middle] < target) {\n                low = middle;\n            }\n            else if (array[middle] > target) {\n                high = middle;\n            }\n            else {\n                return middle;\n            }\n        }\n        if (low < array.length - 1) {\n            if (Math.abs(target - array[low]) < Math.abs(array[low + 1] - target)) {\n                return low;\n            }\n            else {\n                return low + 1;\n            }\n        }\n        else {\n            return low;\n        }\n    }\n    else {\n        let index = 0;\n        let diff = Number.POSITIVE_INFINITY;\n        for (let i = 0; i < array.length; i++) {\n            const currentDiff = Math.abs(array[i] - target);\n            if (currentDiff < diff) {\n                diff = currentDiff;\n                index = i;\n            }\n        }\n        return index;\n    }\n}\n//# sourceMappingURL=xFindClosestIndex.js.map","import { xFindClosestIndex } from \"./xFindClosestIndex.js\";\n/**\n * Returns an object with {fromIndex, toIndex} for a specific from / to\n * @param x - array of numbers\n * @param options - options.\n */\nexport function xGetFromToIndex(x, options = {}) {\n    let { fromIndex, toIndex } = options;\n    const { from, to } = options;\n    if (fromIndex === undefined) {\n        if (from !== undefined) {\n            fromIndex = xFindClosestIndex(x, from);\n        }\n        else {\n            fromIndex = 0;\n        }\n    }\n    if (toIndex === undefined) {\n        if (to !== undefined) {\n            toIndex = xFindClosestIndex(x, to);\n        }\n        else {\n            toIndex = x.length - 1;\n        }\n    }\n    if (fromIndex < 0)\n        fromIndex = 0;\n    if (toIndex < 0)\n        toIndex = 0;\n    if (fromIndex >= x.length)\n        fromIndex = x.length - 1;\n    if (toIndex >= x.length)\n        toIndex = x.length - 1;\n    if (fromIndex > toIndex)\n        [fromIndex, toIndex] = [toIndex, fromIndex];\n    return { fromIndex, toIndex };\n}\n//# sourceMappingURL=xGetFromToIndex.js.map","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n/**\n * Checks if an object is an instance of an Array (array or typed array, except those that contain bigint values).\n * @param value - Object to check.\n * @returns True if the object is an array or a typed array.\n */\nfunction isAnyArray(value) {\n    const tag = toString.call(value);\n    return tag.endsWith('Array]') && !tag.includes('Big');\n}\n\n/**\n * Computes the maximum of the given values.\n *\n * @param input\n * @param options\n */\nfunction max(input, options = {}) {\n    if (!isAnyArray(input)) {\n        throw new TypeError('input must be an array');\n    }\n    if (input.length === 0) {\n        throw new TypeError('input must not be empty');\n    }\n    const { fromIndex = 0, toIndex = input.length } = options;\n    if (fromIndex < 0 ||\n        fromIndex >= input.length ||\n        !Number.isInteger(fromIndex)) {\n        throw new Error('fromIndex must be a positive integer smaller than length');\n    }\n    if (toIndex <= fromIndex ||\n        toIndex > input.length ||\n        !Number.isInteger(toIndex)) {\n        throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n    }\n    let maxValue = input[fromIndex];\n    for (let i = fromIndex + 1; i < toIndex; i++) {\n        if (input[i] > maxValue)\n            maxValue = input[i];\n    }\n    return maxValue;\n}\n\n/**\n * Computes the minimum of the given values.\n */\nfunction min(input, options = {}) {\n    if (!isAnyArray(input)) {\n        throw new TypeError('input must be an array');\n    }\n    if (input.length === 0) {\n        throw new TypeError('input must not be empty');\n    }\n    const { fromIndex = 0, toIndex = input.length } = options;\n    if (fromIndex < 0 ||\n        fromIndex >= input.length ||\n        !Number.isInteger(fromIndex)) {\n        throw new Error('fromIndex must be a positive integer smaller than length');\n    }\n    if (toIndex <= fromIndex ||\n        toIndex > input.length ||\n        !Number.isInteger(toIndex)) {\n        throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n    }\n    let minValue = input[fromIndex];\n    for (let i = fromIndex + 1; i < toIndex; i++) {\n        if (input[i] < minValue)\n            minValue = input[i];\n    }\n    return minValue;\n}\n\n/**\n * Rescale an array into a range.\n */\nfunction rescale(input, options = {}) {\n    if (!isAnyArray(input)) {\n        throw new TypeError('input must be an array');\n    }\n    else if (input.length === 0) {\n        throw new TypeError('input must not be empty');\n    }\n    let output;\n    if (options.output !== undefined) {\n        if (!isAnyArray(options.output)) {\n            throw new TypeError('output option must be an array if specified');\n        }\n        output = options.output;\n    }\n    else {\n        output = new Array(input.length);\n    }\n    const currentMin = min(input);\n    const currentMax = max(input);\n    if (currentMin === currentMax) {\n        throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');\n    }\n    const { min: minValue = options.autoMinMax ? currentMin : 0, max: maxValue = options.autoMinMax ? currentMax : 1, } = options;\n    if (minValue >= maxValue) {\n        throw new RangeError('min option must be smaller than max option');\n    }\n    const factor = (maxValue - minValue) / (currentMax - currentMin);\n    for (let i = 0; i < input.length; i++) {\n        output[i] = (input[i] - currentMin) * factor + minValue;\n    }\n    return output;\n}\n\nconst indent = ' '.repeat(2);\nconst indentData = ' '.repeat(4);\n\n/**\n * @this {Matrix}\n * @returns {string}\n */\nfunction inspectMatrix() {\n  return inspectMatrixWithOptions(this);\n}\n\nfunction inspectMatrixWithOptions(matrix, options = {}) {\n  const {\n    maxRows = 15,\n    maxColumns = 10,\n    maxNumSize = 8,\n    padMinus = 'auto',\n  } = options;\n  return `${matrix.constructor.name} {\n${indent}[\n${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus)}\n${indent}]\n${indent}rows: ${matrix.rows}\n${indent}columns: ${matrix.columns}\n}`;\n}\n\nfunction inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus) {\n  const { rows, columns } = matrix;\n  const maxI = Math.min(rows, maxRows);\n  const maxJ = Math.min(columns, maxColumns);\n  const result = [];\n\n  if (padMinus === 'auto') {\n    padMinus = false;\n    loop: for (let i = 0; i < maxI; i++) {\n      for (let j = 0; j < maxJ; j++) {\n        if (matrix.get(i, j) < 0) {\n          padMinus = true;\n          break loop;\n        }\n      }\n    }\n  }\n\n  for (let i = 0; i < maxI; i++) {\n    let line = [];\n    for (let j = 0; j < maxJ; j++) {\n      line.push(formatNumber(matrix.get(i, j), maxNumSize, padMinus));\n    }\n    result.push(`${line.join(' ')}`);\n  }\n  if (maxJ !== columns) {\n    result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;\n  }\n  if (maxI !== rows) {\n    result.push(`... ${rows - maxRows} more rows`);\n  }\n  return result.join(`\\n${indentData}`);\n}\n\nfunction formatNumber(num, maxNumSize, padMinus) {\n  return (\n    num >= 0 && padMinus\n      ? ` ${formatNumber2(num, maxNumSize - 1)}`\n      : formatNumber2(num, maxNumSize)\n  ).padEnd(maxNumSize);\n}\n\nfunction formatNumber2(num, len) {\n  // small.length numbers should be as is\n  let str = num.toString();\n  if (str.length <= len) return str;\n\n  // (7)'0.00123' is better then (7)'1.23e-2'\n  // (8)'0.000123' is worse then (7)'1.23e-3',\n  let fix = num.toFixed(len);\n  if (fix.length > len) {\n    fix = num.toFixed(Math.max(0, len - (fix.length - len)));\n  }\n  if (\n    fix.length <= len &&\n    !fix.startsWith('0.000') &&\n    !fix.startsWith('-0.000')\n  ) {\n    return fix;\n  }\n\n  // well, if it's still too long the user should've used longer numbers\n  let exp = num.toExponential(len);\n  if (exp.length > len) {\n    exp = num.toExponential(Math.max(0, len - (exp.length - len)));\n  }\n  return exp.slice(0);\n}\n\nfunction installMathOperations(AbstractMatrix, Matrix) {\n  AbstractMatrix.prototype.add = function add(value) {\n    if (typeof value === 'number') return this.addS(value);\n    return this.addM(value);\n  };\n\n  AbstractMatrix.prototype.addS = function addS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) + value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.addM = function addM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) + matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.add = function add(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.add(value);\n  };\n\n  AbstractMatrix.prototype.sub = function sub(value) {\n    if (typeof value === 'number') return this.subS(value);\n    return this.subM(value);\n  };\n\n  AbstractMatrix.prototype.subS = function subS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) - value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.subM = function subM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) - matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.sub = function sub(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.sub(value);\n  };\n  AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;\n  AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;\n  AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;\n  AbstractMatrix.subtract = AbstractMatrix.sub;\n\n  AbstractMatrix.prototype.mul = function mul(value) {\n    if (typeof value === 'number') return this.mulS(value);\n    return this.mulM(value);\n  };\n\n  AbstractMatrix.prototype.mulS = function mulS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) * value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.mulM = function mulM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) * matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.mul = function mul(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.mul(value);\n  };\n  AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;\n  AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;\n  AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;\n  AbstractMatrix.multiply = AbstractMatrix.mul;\n\n  AbstractMatrix.prototype.div = function div(value) {\n    if (typeof value === 'number') return this.divS(value);\n    return this.divM(value);\n  };\n\n  AbstractMatrix.prototype.divS = function divS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) / value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.divM = function divM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) / matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.div = function div(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.div(value);\n  };\n  AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;\n  AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;\n  AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;\n  AbstractMatrix.divide = AbstractMatrix.div;\n\n  AbstractMatrix.prototype.mod = function mod(value) {\n    if (typeof value === 'number') return this.modS(value);\n    return this.modM(value);\n  };\n\n  AbstractMatrix.prototype.modS = function modS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) % value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.modM = function modM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) % matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.mod = function mod(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.mod(value);\n  };\n  AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;\n  AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;\n  AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;\n  AbstractMatrix.modulus = AbstractMatrix.mod;\n\n  AbstractMatrix.prototype.and = function and(value) {\n    if (typeof value === 'number') return this.andS(value);\n    return this.andM(value);\n  };\n\n  AbstractMatrix.prototype.andS = function andS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) & value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.andM = function andM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) & matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.and = function and(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.and(value);\n  };\n\n  AbstractMatrix.prototype.or = function or(value) {\n    if (typeof value === 'number') return this.orS(value);\n    return this.orM(value);\n  };\n\n  AbstractMatrix.prototype.orS = function orS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) | value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.orM = function orM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) | matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.or = function or(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.or(value);\n  };\n\n  AbstractMatrix.prototype.xor = function xor(value) {\n    if (typeof value === 'number') return this.xorS(value);\n    return this.xorM(value);\n  };\n\n  AbstractMatrix.prototype.xorS = function xorS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) ^ value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.xorM = function xorM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) ^ matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.xor = function xor(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.xor(value);\n  };\n\n  AbstractMatrix.prototype.leftShift = function leftShift(value) {\n    if (typeof value === 'number') return this.leftShiftS(value);\n    return this.leftShiftM(value);\n  };\n\n  AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) << value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) << matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.leftShift = function leftShift(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.leftShift(value);\n  };\n\n  AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {\n    if (typeof value === 'number') return this.signPropagatingRightShiftS(value);\n    return this.signPropagatingRightShiftM(value);\n  };\n\n  AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) >> value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) >> matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.signPropagatingRightShift(value);\n  };\n\n  AbstractMatrix.prototype.rightShift = function rightShift(value) {\n    if (typeof value === 'number') return this.rightShiftS(value);\n    return this.rightShiftM(value);\n  };\n\n  AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) >>> value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) >>> matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.rightShift = function rightShift(matrix, value) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.rightShift(value);\n  };\n  AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;\n  AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;\n  AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;\n  AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;\n\n  AbstractMatrix.prototype.not = function not() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, ~(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.not = function not(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.not();\n  };\n\n  AbstractMatrix.prototype.abs = function abs() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.abs(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.abs = function abs(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.abs();\n  };\n\n  AbstractMatrix.prototype.acos = function acos() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.acos(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.acos = function acos(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.acos();\n  };\n\n  AbstractMatrix.prototype.acosh = function acosh() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.acosh(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.acosh = function acosh(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.acosh();\n  };\n\n  AbstractMatrix.prototype.asin = function asin() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.asin(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.asin = function asin(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.asin();\n  };\n\n  AbstractMatrix.prototype.asinh = function asinh() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.asinh(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.asinh = function asinh(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.asinh();\n  };\n\n  AbstractMatrix.prototype.atan = function atan() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.atan(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.atan = function atan(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.atan();\n  };\n\n  AbstractMatrix.prototype.atanh = function atanh() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.atanh(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.atanh = function atanh(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.atanh();\n  };\n\n  AbstractMatrix.prototype.cbrt = function cbrt() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.cbrt(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.cbrt = function cbrt(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.cbrt();\n  };\n\n  AbstractMatrix.prototype.ceil = function ceil() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.ceil(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.ceil = function ceil(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.ceil();\n  };\n\n  AbstractMatrix.prototype.clz32 = function clz32() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.clz32(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.clz32 = function clz32(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.clz32();\n  };\n\n  AbstractMatrix.prototype.cos = function cos() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.cos(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.cos = function cos(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.cos();\n  };\n\n  AbstractMatrix.prototype.cosh = function cosh() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.cosh(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.cosh = function cosh(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.cosh();\n  };\n\n  AbstractMatrix.prototype.exp = function exp() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.exp(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.exp = function exp(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.exp();\n  };\n\n  AbstractMatrix.prototype.expm1 = function expm1() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.expm1(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.expm1 = function expm1(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.expm1();\n  };\n\n  AbstractMatrix.prototype.floor = function floor() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.floor(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.floor = function floor(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.floor();\n  };\n\n  AbstractMatrix.prototype.fround = function fround() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.fround(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.fround = function fround(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.fround();\n  };\n\n  AbstractMatrix.prototype.log = function log() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.log(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.log = function log(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.log();\n  };\n\n  AbstractMatrix.prototype.log1p = function log1p() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.log1p(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.log1p = function log1p(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.log1p();\n  };\n\n  AbstractMatrix.prototype.log10 = function log10() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.log10(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.log10 = function log10(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.log10();\n  };\n\n  AbstractMatrix.prototype.log2 = function log2() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.log2(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.log2 = function log2(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.log2();\n  };\n\n  AbstractMatrix.prototype.round = function round() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.round(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.round = function round(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.round();\n  };\n\n  AbstractMatrix.prototype.sign = function sign() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.sign(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.sign = function sign(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.sign();\n  };\n\n  AbstractMatrix.prototype.sin = function sin() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.sin(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.sin = function sin(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.sin();\n  };\n\n  AbstractMatrix.prototype.sinh = function sinh() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.sinh(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.sinh = function sinh(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.sinh();\n  };\n\n  AbstractMatrix.prototype.sqrt = function sqrt() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.sqrt(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.sqrt = function sqrt(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.sqrt();\n  };\n\n  AbstractMatrix.prototype.tan = function tan() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.tan(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.tan = function tan(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.tan();\n  };\n\n  AbstractMatrix.prototype.tanh = function tanh() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.tanh(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.tanh = function tanh(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.tanh();\n  };\n\n  AbstractMatrix.prototype.trunc = function trunc() {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, Math.trunc(this.get(i, j)));\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.trunc = function trunc(matrix) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.trunc();\n  };\n\n  AbstractMatrix.pow = function pow(matrix, arg0) {\n    const newMatrix = new Matrix(matrix);\n    return newMatrix.pow(arg0);\n  };\n\n  AbstractMatrix.prototype.pow = function pow(value) {\n    if (typeof value === 'number') return this.powS(value);\n    return this.powM(value);\n  };\n\n  AbstractMatrix.prototype.powS = function powS(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) ** value);\n      }\n    }\n    return this;\n  };\n\n  AbstractMatrix.prototype.powM = function powM(matrix) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (this.rows !== matrix.rows ||\n      this.columns !== matrix.columns) {\n      throw new RangeError('Matrices dimensions must be equal');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) ** matrix.get(i, j));\n      }\n    }\n    return this;\n  };\n}\n\n/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nfunction checkRowIndex(matrix, index, outer) {\n  let max = outer ? matrix.rows : matrix.rows - 1;\n  if (index < 0 || index > max) {\n    throw new RangeError('Row index out of range');\n  }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nfunction checkColumnIndex(matrix, index, outer) {\n  let max = outer ? matrix.columns : matrix.columns - 1;\n  if (index < 0 || index > max) {\n    throw new RangeError('Column index out of range');\n  }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nfunction checkRowVector(matrix, vector) {\n  if (vector.to1DArray) {\n    vector = vector.to1DArray();\n  }\n  if (vector.length !== matrix.columns) {\n    throw new RangeError(\n      'vector size must be the same as the number of columns',\n    );\n  }\n  return vector;\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nfunction checkColumnVector(matrix, vector) {\n  if (vector.to1DArray) {\n    vector = vector.to1DArray();\n  }\n  if (vector.length !== matrix.rows) {\n    throw new RangeError('vector size must be the same as the number of rows');\n  }\n  return vector;\n}\n\nfunction checkRowIndices(matrix, rowIndices) {\n  if (!isAnyArray(rowIndices)) {\n    throw new TypeError('row indices must be an array');\n  }\n\n  for (let i = 0; i < rowIndices.length; i++) {\n    if (rowIndices[i] < 0 || rowIndices[i] >= matrix.rows) {\n      throw new RangeError('row indices are out of range');\n    }\n  }\n}\n\nfunction checkColumnIndices(matrix, columnIndices) {\n  if (!isAnyArray(columnIndices)) {\n    throw new TypeError('column indices must be an array');\n  }\n\n  for (let i = 0; i < columnIndices.length; i++) {\n    if (columnIndices[i] < 0 || columnIndices[i] >= matrix.columns) {\n      throw new RangeError('column indices are out of range');\n    }\n  }\n}\n\nfunction checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n  if (arguments.length !== 5) {\n    throw new RangeError('expected 4 arguments');\n  }\n  checkNumber('startRow', startRow);\n  checkNumber('endRow', endRow);\n  checkNumber('startColumn', startColumn);\n  checkNumber('endColumn', endColumn);\n  if (\n    startRow > endRow ||\n    startColumn > endColumn ||\n    startRow < 0 ||\n    startRow >= matrix.rows ||\n    endRow < 0 ||\n    endRow >= matrix.rows ||\n    startColumn < 0 ||\n    startColumn >= matrix.columns ||\n    endColumn < 0 ||\n    endColumn >= matrix.columns\n  ) {\n    throw new RangeError('Submatrix indices are out of range');\n  }\n}\n\nfunction newArray(length, value = 0) {\n  let array = [];\n  for (let i = 0; i < length; i++) {\n    array.push(value);\n  }\n  return array;\n}\n\nfunction checkNumber(name, value) {\n  if (typeof value !== 'number') {\n    throw new TypeError(`${name} must be a number`);\n  }\n}\n\nfunction checkNonEmpty(matrix) {\n  if (matrix.isEmpty()) {\n    throw new Error('Empty matrix has no elements to index');\n  }\n}\n\nfunction sumByRow(matrix) {\n  let sum = newArray(matrix.rows);\n  for (let i = 0; i < matrix.rows; ++i) {\n    for (let j = 0; j < matrix.columns; ++j) {\n      sum[i] += matrix.get(i, j);\n    }\n  }\n  return sum;\n}\n\nfunction sumByColumn(matrix) {\n  let sum = newArray(matrix.columns);\n  for (let i = 0; i < matrix.rows; ++i) {\n    for (let j = 0; j < matrix.columns; ++j) {\n      sum[j] += matrix.get(i, j);\n    }\n  }\n  return sum;\n}\n\nfunction sumAll(matrix) {\n  let v = 0;\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      v += matrix.get(i, j);\n    }\n  }\n  return v;\n}\n\nfunction productByRow(matrix) {\n  let sum = newArray(matrix.rows, 1);\n  for (let i = 0; i < matrix.rows; ++i) {\n    for (let j = 0; j < matrix.columns; ++j) {\n      sum[i] *= matrix.get(i, j);\n    }\n  }\n  return sum;\n}\n\nfunction productByColumn(matrix) {\n  let sum = newArray(matrix.columns, 1);\n  for (let i = 0; i < matrix.rows; ++i) {\n    for (let j = 0; j < matrix.columns; ++j) {\n      sum[j] *= matrix.get(i, j);\n    }\n  }\n  return sum;\n}\n\nfunction productAll(matrix) {\n  let v = 1;\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      v *= matrix.get(i, j);\n    }\n  }\n  return v;\n}\n\nfunction varianceByRow(matrix, unbiased, mean) {\n  const rows = matrix.rows;\n  const cols = matrix.columns;\n  const variance = [];\n\n  for (let i = 0; i < rows; i++) {\n    let sum1 = 0;\n    let sum2 = 0;\n    let x = 0;\n    for (let j = 0; j < cols; j++) {\n      x = matrix.get(i, j) - mean[i];\n      sum1 += x;\n      sum2 += x * x;\n    }\n    if (unbiased) {\n      variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1));\n    } else {\n      variance.push((sum2 - (sum1 * sum1) / cols) / cols);\n    }\n  }\n  return variance;\n}\n\nfunction varianceByColumn(matrix, unbiased, mean) {\n  const rows = matrix.rows;\n  const cols = matrix.columns;\n  const variance = [];\n\n  for (let j = 0; j < cols; j++) {\n    let sum1 = 0;\n    let sum2 = 0;\n    let x = 0;\n    for (let i = 0; i < rows; i++) {\n      x = matrix.get(i, j) - mean[j];\n      sum1 += x;\n      sum2 += x * x;\n    }\n    if (unbiased) {\n      variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));\n    } else {\n      variance.push((sum2 - (sum1 * sum1) / rows) / rows);\n    }\n  }\n  return variance;\n}\n\nfunction varianceAll(matrix, unbiased, mean) {\n  const rows = matrix.rows;\n  const cols = matrix.columns;\n  const size = rows * cols;\n\n  let sum1 = 0;\n  let sum2 = 0;\n  let x = 0;\n  for (let i = 0; i < rows; i++) {\n    for (let j = 0; j < cols; j++) {\n      x = matrix.get(i, j) - mean;\n      sum1 += x;\n      sum2 += x * x;\n    }\n  }\n  if (unbiased) {\n    return (sum2 - (sum1 * sum1) / size) / (size - 1);\n  } else {\n    return (sum2 - (sum1 * sum1) / size) / size;\n  }\n}\n\nfunction centerByRow(matrix, mean) {\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      matrix.set(i, j, matrix.get(i, j) - mean[i]);\n    }\n  }\n}\n\nfunction centerByColumn(matrix, mean) {\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      matrix.set(i, j, matrix.get(i, j) - mean[j]);\n    }\n  }\n}\n\nfunction centerAll(matrix, mean) {\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      matrix.set(i, j, matrix.get(i, j) - mean);\n    }\n  }\n}\n\nfunction getScaleByRow(matrix) {\n  const scale = [];\n  for (let i = 0; i < matrix.rows; i++) {\n    let sum = 0;\n    for (let j = 0; j < matrix.columns; j++) {\n      sum += matrix.get(i, j) ** 2 / (matrix.columns - 1);\n    }\n    scale.push(Math.sqrt(sum));\n  }\n  return scale;\n}\n\nfunction scaleByRow(matrix, scale) {\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      matrix.set(i, j, matrix.get(i, j) / scale[i]);\n    }\n  }\n}\n\nfunction getScaleByColumn(matrix) {\n  const scale = [];\n  for (let j = 0; j < matrix.columns; j++) {\n    let sum = 0;\n    for (let i = 0; i < matrix.rows; i++) {\n      sum += matrix.get(i, j) ** 2 / (matrix.rows - 1);\n    }\n    scale.push(Math.sqrt(sum));\n  }\n  return scale;\n}\n\nfunction scaleByColumn(matrix, scale) {\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      matrix.set(i, j, matrix.get(i, j) / scale[j]);\n    }\n  }\n}\n\nfunction getScaleAll(matrix) {\n  const divider = matrix.size - 1;\n  let sum = 0;\n  for (let j = 0; j < matrix.columns; j++) {\n    for (let i = 0; i < matrix.rows; i++) {\n      sum += matrix.get(i, j) ** 2 / divider;\n    }\n  }\n  return Math.sqrt(sum);\n}\n\nfunction scaleAll(matrix, scale) {\n  for (let i = 0; i < matrix.rows; i++) {\n    for (let j = 0; j < matrix.columns; j++) {\n      matrix.set(i, j, matrix.get(i, j) / scale);\n    }\n  }\n}\n\nclass AbstractMatrix {\n  static from1DArray(newRows, newColumns, newData) {\n    let length = newRows * newColumns;\n    if (length !== newData.length) {\n      throw new RangeError('data length does not match given dimensions');\n    }\n    let newMatrix = new Matrix(newRows, newColumns);\n    for (let row = 0; row < newRows; row++) {\n      for (let column = 0; column < newColumns; column++) {\n        newMatrix.set(row, column, newData[row * newColumns + column]);\n      }\n    }\n    return newMatrix;\n  }\n\n  static rowVector(newData) {\n    let vector = new Matrix(1, newData.length);\n    for (let i = 0; i < newData.length; i++) {\n      vector.set(0, i, newData[i]);\n    }\n    return vector;\n  }\n\n  static columnVector(newData) {\n    let vector = new Matrix(newData.length, 1);\n    for (let i = 0; i < newData.length; i++) {\n      vector.set(i, 0, newData[i]);\n    }\n    return vector;\n  }\n\n  static zeros(rows, columns) {\n    return new Matrix(rows, columns);\n  }\n\n  static ones(rows, columns) {\n    return new Matrix(rows, columns).fill(1);\n  }\n\n  static rand(rows, columns, options = {}) {\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { random = Math.random } = options;\n    let matrix = new Matrix(rows, columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        matrix.set(i, j, random());\n      }\n    }\n    return matrix;\n  }\n\n  static randInt(rows, columns, options = {}) {\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { min = 0, max = 1000, random = Math.random } = options;\n    if (!Number.isInteger(min)) throw new TypeError('min must be an integer');\n    if (!Number.isInteger(max)) throw new TypeError('max must be an integer');\n    if (min >= max) throw new RangeError('min must be smaller than max');\n    let interval = max - min;\n    let matrix = new Matrix(rows, columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        let value = min + Math.round(random() * interval);\n        matrix.set(i, j, value);\n      }\n    }\n    return matrix;\n  }\n\n  static eye(rows, columns, value) {\n    if (columns === undefined) columns = rows;\n    if (value === undefined) value = 1;\n    let min = Math.min(rows, columns);\n    let matrix = this.zeros(rows, columns);\n    for (let i = 0; i < min; i++) {\n      matrix.set(i, i, value);\n    }\n    return matrix;\n  }\n\n  static diag(data, rows, columns) {\n    let l = data.length;\n    if (rows === undefined) rows = l;\n    if (columns === undefined) columns = rows;\n    let min = Math.min(l, rows, columns);\n    let matrix = this.zeros(rows, columns);\n    for (let i = 0; i < min; i++) {\n      matrix.set(i, i, data[i]);\n    }\n    return matrix;\n  }\n\n  static min(matrix1, matrix2) {\n    matrix1 = this.checkMatrix(matrix1);\n    matrix2 = this.checkMatrix(matrix2);\n    let rows = matrix1.rows;\n    let columns = matrix1.columns;\n    let result = new Matrix(rows, columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n      }\n    }\n    return result;\n  }\n\n  static max(matrix1, matrix2) {\n    matrix1 = this.checkMatrix(matrix1);\n    matrix2 = this.checkMatrix(matrix2);\n    let rows = matrix1.rows;\n    let columns = matrix1.columns;\n    let result = new this(rows, columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n      }\n    }\n    return result;\n  }\n\n  static checkMatrix(value) {\n    return AbstractMatrix.isMatrix(value) ? value : new Matrix(value);\n  }\n\n  static isMatrix(value) {\n    return value != null && value.klass === 'Matrix';\n  }\n\n  get size() {\n    return this.rows * this.columns;\n  }\n\n  apply(callback) {\n    if (typeof callback !== 'function') {\n      throw new TypeError('callback must be a function');\n    }\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        callback.call(this, i, j);\n      }\n    }\n    return this;\n  }\n\n  to1DArray() {\n    let array = [];\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        array.push(this.get(i, j));\n      }\n    }\n    return array;\n  }\n\n  to2DArray() {\n    let copy = [];\n    for (let i = 0; i < this.rows; i++) {\n      copy.push([]);\n      for (let j = 0; j < this.columns; j++) {\n        copy[i].push(this.get(i, j));\n      }\n    }\n    return copy;\n  }\n\n  toJSON() {\n    return this.to2DArray();\n  }\n\n  isRowVector() {\n    return this.rows === 1;\n  }\n\n  isColumnVector() {\n    return this.columns === 1;\n  }\n\n  isVector() {\n    return this.rows === 1 || this.columns === 1;\n  }\n\n  isSquare() {\n    return this.rows === this.columns;\n  }\n\n  isEmpty() {\n    return this.rows === 0 || this.columns === 0;\n  }\n\n  isSymmetric() {\n    if (this.isSquare()) {\n      for (let i = 0; i < this.rows; i++) {\n        for (let j = 0; j <= i; j++) {\n          if (this.get(i, j) !== this.get(j, i)) {\n            return false;\n          }\n        }\n      }\n      return true;\n    }\n    return false;\n  }\n\n  isDistance() {\n    if (!this.isSymmetric()) return false;\n\n    for (let i = 0; i < this.rows; i++) {\n      if (this.get(i, i) !== 0) return false;\n    }\n\n    return true;\n  }\n\n  isEchelonForm() {\n    let i = 0;\n    let j = 0;\n    let previousColumn = -1;\n    let isEchelonForm = true;\n    let checked = false;\n    while (i < this.rows && isEchelonForm) {\n      j = 0;\n      checked = false;\n      while (j < this.columns && checked === false) {\n        if (this.get(i, j) === 0) {\n          j++;\n        } else if (this.get(i, j) === 1 && j > previousColumn) {\n          checked = true;\n          previousColumn = j;\n        } else {\n          isEchelonForm = false;\n          checked = true;\n        }\n      }\n      i++;\n    }\n    return isEchelonForm;\n  }\n\n  isReducedEchelonForm() {\n    let i = 0;\n    let j = 0;\n    let previousColumn = -1;\n    let isReducedEchelonForm = true;\n    let checked = false;\n    while (i < this.rows && isReducedEchelonForm) {\n      j = 0;\n      checked = false;\n      while (j < this.columns && checked === false) {\n        if (this.get(i, j) === 0) {\n          j++;\n        } else if (this.get(i, j) === 1 && j > previousColumn) {\n          checked = true;\n          previousColumn = j;\n        } else {\n          isReducedEchelonForm = false;\n          checked = true;\n        }\n      }\n      for (let k = j + 1; k < this.rows; k++) {\n        if (this.get(i, k) !== 0) {\n          isReducedEchelonForm = false;\n        }\n      }\n      i++;\n    }\n    return isReducedEchelonForm;\n  }\n\n  echelonForm() {\n    let result = this.clone();\n    let h = 0;\n    let k = 0;\n    while (h < result.rows && k < result.columns) {\n      let iMax = h;\n      for (let i = h; i < result.rows; i++) {\n        if (result.get(i, k) > result.get(iMax, k)) {\n          iMax = i;\n        }\n      }\n      if (result.get(iMax, k) === 0) {\n        k++;\n      } else {\n        result.swapRows(h, iMax);\n        let tmp = result.get(h, k);\n        for (let j = k; j < result.columns; j++) {\n          result.set(h, j, result.get(h, j) / tmp);\n        }\n        for (let i = h + 1; i < result.rows; i++) {\n          let factor = result.get(i, k) / result.get(h, k);\n          result.set(i, k, 0);\n          for (let j = k + 1; j < result.columns; j++) {\n            result.set(i, j, result.get(i, j) - result.get(h, j) * factor);\n          }\n        }\n        h++;\n        k++;\n      }\n    }\n    return result;\n  }\n\n  reducedEchelonForm() {\n    let result = this.echelonForm();\n    let m = result.columns;\n    let n = result.rows;\n    let h = n - 1;\n    while (h >= 0) {\n      if (result.maxRow(h) === 0) {\n        h--;\n      } else {\n        let p = 0;\n        let pivot = false;\n        while (p < n && pivot === false) {\n          if (result.get(h, p) === 1) {\n            pivot = true;\n          } else {\n            p++;\n          }\n        }\n        for (let i = 0; i < h; i++) {\n          let factor = result.get(i, p);\n          for (let j = p; j < m; j++) {\n            let tmp = result.get(i, j) - factor * result.get(h, j);\n            result.set(i, j, tmp);\n          }\n        }\n        h--;\n      }\n    }\n    return result;\n  }\n\n  set() {\n    throw new Error('set method is unimplemented');\n  }\n\n  get() {\n    throw new Error('get method is unimplemented');\n  }\n\n  repeat(options = {}) {\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { rows = 1, columns = 1 } = options;\n    if (!Number.isInteger(rows) || rows <= 0) {\n      throw new TypeError('rows must be a positive integer');\n    }\n    if (!Number.isInteger(columns) || columns <= 0) {\n      throw new TypeError('columns must be a positive integer');\n    }\n    let matrix = new Matrix(this.rows * rows, this.columns * columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n      }\n    }\n    return matrix;\n  }\n\n  fill(value) {\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, value);\n      }\n    }\n    return this;\n  }\n\n  neg() {\n    return this.mulS(-1);\n  }\n\n  getRow(index) {\n    checkRowIndex(this, index);\n    let row = [];\n    for (let i = 0; i < this.columns; i++) {\n      row.push(this.get(index, i));\n    }\n    return row;\n  }\n\n  getRowVector(index) {\n    return Matrix.rowVector(this.getRow(index));\n  }\n\n  setRow(index, array) {\n    checkRowIndex(this, index);\n    array = checkRowVector(this, array);\n    for (let i = 0; i < this.columns; i++) {\n      this.set(index, i, array[i]);\n    }\n    return this;\n  }\n\n  swapRows(row1, row2) {\n    checkRowIndex(this, row1);\n    checkRowIndex(this, row2);\n    for (let i = 0; i < this.columns; i++) {\n      let temp = this.get(row1, i);\n      this.set(row1, i, this.get(row2, i));\n      this.set(row2, i, temp);\n    }\n    return this;\n  }\n\n  getColumn(index) {\n    checkColumnIndex(this, index);\n    let column = [];\n    for (let i = 0; i < this.rows; i++) {\n      column.push(this.get(i, index));\n    }\n    return column;\n  }\n\n  getColumnVector(index) {\n    return Matrix.columnVector(this.getColumn(index));\n  }\n\n  setColumn(index, array) {\n    checkColumnIndex(this, index);\n    array = checkColumnVector(this, array);\n    for (let i = 0; i < this.rows; i++) {\n      this.set(i, index, array[i]);\n    }\n    return this;\n  }\n\n  swapColumns(column1, column2) {\n    checkColumnIndex(this, column1);\n    checkColumnIndex(this, column2);\n    for (let i = 0; i < this.rows; i++) {\n      let temp = this.get(i, column1);\n      this.set(i, column1, this.get(i, column2));\n      this.set(i, column2, temp);\n    }\n    return this;\n  }\n\n  addRowVector(vector) {\n    vector = checkRowVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) + vector[j]);\n      }\n    }\n    return this;\n  }\n\n  subRowVector(vector) {\n    vector = checkRowVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) - vector[j]);\n      }\n    }\n    return this;\n  }\n\n  mulRowVector(vector) {\n    vector = checkRowVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) * vector[j]);\n      }\n    }\n    return this;\n  }\n\n  divRowVector(vector) {\n    vector = checkRowVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) / vector[j]);\n      }\n    }\n    return this;\n  }\n\n  addColumnVector(vector) {\n    vector = checkColumnVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) + vector[i]);\n      }\n    }\n    return this;\n  }\n\n  subColumnVector(vector) {\n    vector = checkColumnVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) - vector[i]);\n      }\n    }\n    return this;\n  }\n\n  mulColumnVector(vector) {\n    vector = checkColumnVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) * vector[i]);\n      }\n    }\n    return this;\n  }\n\n  divColumnVector(vector) {\n    vector = checkColumnVector(this, vector);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        this.set(i, j, this.get(i, j) / vector[i]);\n      }\n    }\n    return this;\n  }\n\n  mulRow(index, value) {\n    checkRowIndex(this, index);\n    for (let i = 0; i < this.columns; i++) {\n      this.set(index, i, this.get(index, i) * value);\n    }\n    return this;\n  }\n\n  mulColumn(index, value) {\n    checkColumnIndex(this, index);\n    for (let i = 0; i < this.rows; i++) {\n      this.set(i, index, this.get(i, index) * value);\n    }\n    return this;\n  }\n\n  max(by) {\n    if (this.isEmpty()) {\n      return NaN;\n    }\n    switch (by) {\n      case 'row': {\n        const max = new Array(this.rows).fill(Number.NEGATIVE_INFINITY);\n        for (let row = 0; row < this.rows; row++) {\n          for (let column = 0; column < this.columns; column++) {\n            if (this.get(row, column) > max[row]) {\n              max[row] = this.get(row, column);\n            }\n          }\n        }\n        return max;\n      }\n      case 'column': {\n        const max = new Array(this.columns).fill(Number.NEGATIVE_INFINITY);\n        for (let row = 0; row < this.rows; row++) {\n          for (let column = 0; column < this.columns; column++) {\n            if (this.get(row, column) > max[column]) {\n              max[column] = this.get(row, column);\n            }\n          }\n        }\n        return max;\n      }\n      case undefined: {\n        let max = this.get(0, 0);\n        for (let row = 0; row < this.rows; row++) {\n          for (let column = 0; column < this.columns; column++) {\n            if (this.get(row, column) > max) {\n              max = this.get(row, column);\n            }\n          }\n        }\n        return max;\n      }\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  maxIndex() {\n    checkNonEmpty(this);\n    let v = this.get(0, 0);\n    let idx = [0, 0];\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        if (this.get(i, j) > v) {\n          v = this.get(i, j);\n          idx[0] = i;\n          idx[1] = j;\n        }\n      }\n    }\n    return idx;\n  }\n\n  min(by) {\n    if (this.isEmpty()) {\n      return NaN;\n    }\n\n    switch (by) {\n      case 'row': {\n        const min = new Array(this.rows).fill(Number.POSITIVE_INFINITY);\n        for (let row = 0; row < this.rows; row++) {\n          for (let column = 0; column < this.columns; column++) {\n            if (this.get(row, column) < min[row]) {\n              min[row] = this.get(row, column);\n            }\n          }\n        }\n        return min;\n      }\n      case 'column': {\n        const min = new Array(this.columns).fill(Number.POSITIVE_INFINITY);\n        for (let row = 0; row < this.rows; row++) {\n          for (let column = 0; column < this.columns; column++) {\n            if (this.get(row, column) < min[column]) {\n              min[column] = this.get(row, column);\n            }\n          }\n        }\n        return min;\n      }\n      case undefined: {\n        let min = this.get(0, 0);\n        for (let row = 0; row < this.rows; row++) {\n          for (let column = 0; column < this.columns; column++) {\n            if (this.get(row, column) < min) {\n              min = this.get(row, column);\n            }\n          }\n        }\n        return min;\n      }\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  minIndex() {\n    checkNonEmpty(this);\n    let v = this.get(0, 0);\n    let idx = [0, 0];\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        if (this.get(i, j) < v) {\n          v = this.get(i, j);\n          idx[0] = i;\n          idx[1] = j;\n        }\n      }\n    }\n    return idx;\n  }\n\n  maxRow(row) {\n    checkRowIndex(this, row);\n    if (this.isEmpty()) {\n      return NaN;\n    }\n    let v = this.get(row, 0);\n    for (let i = 1; i < this.columns; i++) {\n      if (this.get(row, i) > v) {\n        v = this.get(row, i);\n      }\n    }\n    return v;\n  }\n\n  maxRowIndex(row) {\n    checkRowIndex(this, row);\n    checkNonEmpty(this);\n    let v = this.get(row, 0);\n    let idx = [row, 0];\n    for (let i = 1; i < this.columns; i++) {\n      if (this.get(row, i) > v) {\n        v = this.get(row, i);\n        idx[1] = i;\n      }\n    }\n    return idx;\n  }\n\n  minRow(row) {\n    checkRowIndex(this, row);\n    if (this.isEmpty()) {\n      return NaN;\n    }\n    let v = this.get(row, 0);\n    for (let i = 1; i < this.columns; i++) {\n      if (this.get(row, i) < v) {\n        v = this.get(row, i);\n      }\n    }\n    return v;\n  }\n\n  minRowIndex(row) {\n    checkRowIndex(this, row);\n    checkNonEmpty(this);\n    let v = this.get(row, 0);\n    let idx = [row, 0];\n    for (let i = 1; i < this.columns; i++) {\n      if (this.get(row, i) < v) {\n        v = this.get(row, i);\n        idx[1] = i;\n      }\n    }\n    return idx;\n  }\n\n  maxColumn(column) {\n    checkColumnIndex(this, column);\n    if (this.isEmpty()) {\n      return NaN;\n    }\n    let v = this.get(0, column);\n    for (let i = 1; i < this.rows; i++) {\n      if (this.get(i, column) > v) {\n        v = this.get(i, column);\n      }\n    }\n    return v;\n  }\n\n  maxColumnIndex(column) {\n    checkColumnIndex(this, column);\n    checkNonEmpty(this);\n    let v = this.get(0, column);\n    let idx = [0, column];\n    for (let i = 1; i < this.rows; i++) {\n      if (this.get(i, column) > v) {\n        v = this.get(i, column);\n        idx[0] = i;\n      }\n    }\n    return idx;\n  }\n\n  minColumn(column) {\n    checkColumnIndex(this, column);\n    if (this.isEmpty()) {\n      return NaN;\n    }\n    let v = this.get(0, column);\n    for (let i = 1; i < this.rows; i++) {\n      if (this.get(i, column) < v) {\n        v = this.get(i, column);\n      }\n    }\n    return v;\n  }\n\n  minColumnIndex(column) {\n    checkColumnIndex(this, column);\n    checkNonEmpty(this);\n    let v = this.get(0, column);\n    let idx = [0, column];\n    for (let i = 1; i < this.rows; i++) {\n      if (this.get(i, column) < v) {\n        v = this.get(i, column);\n        idx[0] = i;\n      }\n    }\n    return idx;\n  }\n\n  diag() {\n    let min = Math.min(this.rows, this.columns);\n    let diag = [];\n    for (let i = 0; i < min; i++) {\n      diag.push(this.get(i, i));\n    }\n    return diag;\n  }\n\n  norm(type = 'frobenius') {\n    switch (type) {\n      case 'max':\n        return this.max();\n      case 'frobenius':\n        return Math.sqrt(this.dot(this));\n      default:\n        throw new RangeError(`unknown norm type: ${type}`);\n    }\n  }\n\n  cumulativeSum() {\n    let sum = 0;\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        sum += this.get(i, j);\n        this.set(i, j, sum);\n      }\n    }\n    return this;\n  }\n\n  dot(vector2) {\n    if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n    let vector1 = this.to1DArray();\n    if (vector1.length !== vector2.length) {\n      throw new RangeError('vectors do not have the same size');\n    }\n    let dot = 0;\n    for (let i = 0; i < vector1.length; i++) {\n      dot += vector1[i] * vector2[i];\n    }\n    return dot;\n  }\n\n  mmul(other) {\n    other = Matrix.checkMatrix(other);\n\n    let m = this.rows;\n    let n = this.columns;\n    let p = other.columns;\n\n    let result = new Matrix(m, p);\n\n    let Bcolj = new Float64Array(n);\n    for (let j = 0; j < p; j++) {\n      for (let k = 0; k < n; k++) {\n        Bcolj[k] = other.get(k, j);\n      }\n\n      for (let i = 0; i < m; i++) {\n        let s = 0;\n        for (let k = 0; k < n; k++) {\n          s += this.get(i, k) * Bcolj[k];\n        }\n\n        result.set(i, j, s);\n      }\n    }\n    return result;\n  }\n\n  gram() {\n    const rows = this.rows;\n    const n = this.columns;\n\n    // The Gram matrix `thisᵀ · this` is symmetric, so only its upper triangle is\n    // accumulated (then mirrored) and the transpose is never materialized.\n    // Row-streaming rank-1 updates read each row of `this` contiguously and skip\n    // zero entries, so the cost scales with the number of non-zeros: it is as\n    // fast as the dense version on dense matrices (the skip never fires) and far\n    // faster on sparse ones.\n    const gramData = new Float64Array(n * n);\n    for (let r = 0; r < rows; r++) {\n      for (let i = 0; i < n; i++) {\n        const value = this.get(r, i);\n        if (value === 0) continue;\n        const offset = i * n;\n        for (let j = i; j < n; j++) {\n          gramData[offset + j] += value * this.get(r, j);\n        }\n      }\n    }\n\n    const result = new Matrix(n, n);\n    for (let i = 0; i < n; i++) {\n      const offset = i * n;\n      for (let j = i; j < n; j++) {\n        const value = gramData[offset + j];\n        result.set(i, j, value);\n        result.set(j, i, value);\n      }\n    }\n    return result;\n  }\n\n  transposeMultiply(other) {\n    other = Matrix.checkMatrix(other);\n    if (this.rows !== other.rows) {\n      throw new RangeError(\n        'the number of rows of the two matrices must be equal',\n      );\n    }\n    const n = this.columns;\n    const p = other.columns;\n\n    const result = new Matrix(n, p);\n    const otherRow = new Float64Array(p);\n    for (let r = 0; r < this.rows; r++) {\n      for (let j = 0; j < p; j++) {\n        otherRow[j] = other.get(r, j);\n      }\n      for (let i = 0; i < n; i++) {\n        const value = this.get(r, i);\n        if (value === 0) continue;\n        const resultRow = result.data[i];\n        for (let j = 0; j < p; j++) {\n          resultRow[j] += value * otherRow[j];\n        }\n      }\n    }\n    return result;\n  }\n\n  mmulByTranspose(scale) {\n    let m = this.rows;\n    let n = this.columns;\n\n    if (scale !== undefined && scale.length !== n) {\n      throw new RangeError('scale must have one value per column');\n    }\n\n    let result = new Matrix(m, m);\n\n    // result = this · diag(scale) · thisᵀ is symmetric, so only the upper\n    // triangle is computed and mirrored, and the transpose is never\n    // materialized. `scale` (one factor per column) is folded into one operand.\n    let rowj = new Float64Array(n);\n    for (let j = 0; j < m; j++) {\n      if (scale === undefined) {\n        for (let k = 0; k < n; k++) {\n          rowj[k] = this.get(j, k);\n        }\n      } else {\n        for (let k = 0; k < n; k++) {\n          rowj[k] = scale[k] * this.get(j, k);\n        }\n      }\n\n      for (let i = j; i < m; i++) {\n        let s = 0;\n        for (let k = 0; k < n; k++) {\n          s += this.get(i, k) * rowj[k];\n        }\n\n        result.set(i, j, s);\n        result.set(j, i, s);\n      }\n    }\n    return result;\n  }\n\n  mpow(scalar) {\n    if (!this.isSquare()) {\n      throw new RangeError('Matrix must be square');\n    }\n    if (!Number.isInteger(scalar) || scalar < 0) {\n      throw new RangeError('Exponent must be a non-negative integer');\n    }\n    // Russian Peasant exponentiation, i.e. exponentiation by squaring\n    let result = Matrix.eye(this.rows);\n    let bb = this;\n    // Note: Don't bit shift. In JS, that would truncate at 32 bits\n    for (let e = scalar; e >= 1; e /= 2) {\n      if ((e & 1) !== 0) {\n        result = result.mmul(bb);\n      }\n      bb = bb.mmul(bb);\n    }\n    return result;\n  }\n\n  strassen2x2(other) {\n    other = Matrix.checkMatrix(other);\n    let result = new Matrix(2, 2);\n    const a11 = this.get(0, 0);\n    const b11 = other.get(0, 0);\n    const a12 = this.get(0, 1);\n    const b12 = other.get(0, 1);\n    const a21 = this.get(1, 0);\n    const b21 = other.get(1, 0);\n    const a22 = this.get(1, 1);\n    const b22 = other.get(1, 1);\n\n    // Compute intermediate values.\n    const m1 = (a11 + a22) * (b11 + b22);\n    const m2 = (a21 + a22) * b11;\n    const m3 = a11 * (b12 - b22);\n    const m4 = a22 * (b21 - b11);\n    const m5 = (a11 + a12) * b22;\n    const m6 = (a21 - a11) * (b11 + b12);\n    const m7 = (a12 - a22) * (b21 + b22);\n\n    // Combine intermediate values into the output.\n    const c00 = m1 + m4 - m5 + m7;\n    const c01 = m3 + m5;\n    const c10 = m2 + m4;\n    const c11 = m1 - m2 + m3 + m6;\n\n    result.set(0, 0, c00);\n    result.set(0, 1, c01);\n    result.set(1, 0, c10);\n    result.set(1, 1, c11);\n    return result;\n  }\n\n  strassen3x3(other) {\n    other = Matrix.checkMatrix(other);\n    let result = new Matrix(3, 3);\n\n    const a00 = this.get(0, 0);\n    const a01 = this.get(0, 1);\n    const a02 = this.get(0, 2);\n    const a10 = this.get(1, 0);\n    const a11 = this.get(1, 1);\n    const a12 = this.get(1, 2);\n    const a20 = this.get(2, 0);\n    const a21 = this.get(2, 1);\n    const a22 = this.get(2, 2);\n\n    const b00 = other.get(0, 0);\n    const b01 = other.get(0, 1);\n    const b02 = other.get(0, 2);\n    const b10 = other.get(1, 0);\n    const b11 = other.get(1, 1);\n    const b12 = other.get(1, 2);\n    const b20 = other.get(2, 0);\n    const b21 = other.get(2, 1);\n    const b22 = other.get(2, 2);\n\n    const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n    const m2 = (a00 - a10) * (-b01 + b11);\n    const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n    const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n    const m5 = (a10 + a11) * (-b00 + b01);\n    const m6 = a00 * b00;\n    const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n    const m8 = (-a00 + a20) * (b02 - b12);\n    const m9 = (a20 + a21) * (-b00 + b02);\n    const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n    const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n    const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n    const m13 = (a02 - a22) * (b11 - b21);\n    const m14 = a02 * b20;\n    const m15 = (a21 + a22) * (-b20 + b21);\n    const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n    const m17 = (a02 - a12) * (b12 - b22);\n    const m18 = (a11 + a12) * (-b20 + b22);\n    const m19 = a01 * b10;\n    const m20 = a12 * b21;\n    const m21 = a10 * b02;\n    const m22 = a20 * b01;\n    const m23 = a22 * b22;\n\n    const c00 = m6 + m14 + m19;\n    const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n    const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n    const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n    const c11 = m2 + m4 + m5 + m6 + m20;\n    const c12 = m14 + m16 + m17 + m18 + m21;\n    const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n    const c21 = m12 + m13 + m14 + m15 + m22;\n    const c22 = m6 + m7 + m8 + m9 + m23;\n\n    result.set(0, 0, c00);\n    result.set(0, 1, c01);\n    result.set(0, 2, c02);\n    result.set(1, 0, c10);\n    result.set(1, 1, c11);\n    result.set(1, 2, c12);\n    result.set(2, 0, c20);\n    result.set(2, 1, c21);\n    result.set(2, 2, c22);\n    return result;\n  }\n\n  mmulStrassen(y) {\n    y = Matrix.checkMatrix(y);\n    let x = this.clone();\n    let r1 = x.rows;\n    let c1 = x.columns;\n    let r2 = y.rows;\n    let c2 = y.columns;\n    if (c1 !== r2) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`,\n      );\n    }\n\n    // Put a matrix into the top left of a matrix of zeros.\n    // `rows` and `cols` are the dimensions of the output matrix.\n    function embed(mat, rows, cols) {\n      let r = mat.rows;\n      let c = mat.columns;\n      if (r === rows && c === cols) {\n        return mat;\n      } else {\n        let resultat = AbstractMatrix.zeros(rows, cols);\n        resultat = resultat.setSubMatrix(mat, 0, 0);\n        return resultat;\n      }\n    }\n\n    // Make sure both matrices are the same size.\n    // This is exclusively for simplicity:\n    // this algorithm can be implemented with matrices of different sizes.\n\n    let r = Math.max(r1, r2);\n    let c = Math.max(c1, c2);\n    x = embed(x, r, c);\n    y = embed(y, r, c);\n\n    // Our recursive multiplication function.\n    function blockMult(a, b, rows, cols) {\n      // For small matrices, resort to naive multiplication.\n      if (rows <= 512 || cols <= 512) {\n        return a.mmul(b); // a is equivalent to this\n      }\n\n      // Apply dynamic padding.\n      if (rows % 2 === 1 && cols % 2 === 1) {\n        a = embed(a, rows + 1, cols + 1);\n        b = embed(b, rows + 1, cols + 1);\n      } else if (rows % 2 === 1) {\n        a = embed(a, rows + 1, cols);\n        b = embed(b, rows + 1, cols);\n      } else if (cols % 2 === 1) {\n        a = embed(a, rows, cols + 1);\n        b = embed(b, rows, cols + 1);\n      }\n\n      let halfRows = parseInt(a.rows / 2, 10);\n      let halfCols = parseInt(a.columns / 2, 10);\n      // Subdivide input matrices.\n      let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n      let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n      let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n      let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n      let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n      let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n      let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n      let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n      // Compute intermediate values.\n      let m1 = blockMult(\n        AbstractMatrix.add(a11, a22),\n        AbstractMatrix.add(b11, b22),\n        halfRows,\n        halfCols,\n      );\n      let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);\n      let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);\n      let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);\n      let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);\n      let m6 = blockMult(\n        AbstractMatrix.sub(a21, a11),\n        AbstractMatrix.add(b11, b12),\n        halfRows,\n        halfCols,\n      );\n      let m7 = blockMult(\n        AbstractMatrix.sub(a12, a22),\n        AbstractMatrix.add(b21, b22),\n        halfRows,\n        halfCols,\n      );\n\n      // Combine intermediate values into the output.\n      let c11 = AbstractMatrix.add(m1, m4);\n      c11.sub(m5);\n      c11.add(m7);\n      let c12 = AbstractMatrix.add(m3, m5);\n      let c21 = AbstractMatrix.add(m2, m4);\n      let c22 = AbstractMatrix.sub(m1, m2);\n      c22.add(m3);\n      c22.add(m6);\n\n      // Crop output to the desired size (undo dynamic padding).\n      let result = AbstractMatrix.zeros(2 * c11.rows, 2 * c11.columns);\n      result = result.setSubMatrix(c11, 0, 0);\n      result = result.setSubMatrix(c12, c11.rows, 0);\n      result = result.setSubMatrix(c21, 0, c11.columns);\n      result = result.setSubMatrix(c22, c11.rows, c11.columns);\n      return result.subMatrix(0, rows - 1, 0, cols - 1);\n    }\n\n    return blockMult(x, y, r, c);\n  }\n\n  scaleRows(options = {}) {\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { min = 0, max = 1 } = options;\n    if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n    if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n    if (min >= max) throw new RangeError('min must be smaller than max');\n    let newMatrix = new Matrix(this.rows, this.columns);\n    for (let i = 0; i < this.rows; i++) {\n      const row = this.getRow(i);\n      if (row.length > 0) {\n        rescale(row, { min, max, output: row });\n      }\n      newMatrix.setRow(i, row);\n    }\n    return newMatrix;\n  }\n\n  scaleColumns(options = {}) {\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { min = 0, max = 1 } = options;\n    if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n    if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n    if (min >= max) throw new RangeError('min must be smaller than max');\n    let newMatrix = new Matrix(this.rows, this.columns);\n    for (let i = 0; i < this.columns; i++) {\n      const column = this.getColumn(i);\n      if (column.length) {\n        rescale(column, {\n          min,\n          max,\n          output: column,\n        });\n      }\n      newMatrix.setColumn(i, column);\n    }\n    return newMatrix;\n  }\n\n  flipRows() {\n    const middle = Math.ceil(this.columns / 2);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < middle; j++) {\n        let first = this.get(i, j);\n        let last = this.get(i, this.columns - 1 - j);\n        this.set(i, j, last);\n        this.set(i, this.columns - 1 - j, first);\n      }\n    }\n    return this;\n  }\n\n  flipColumns() {\n    const middle = Math.ceil(this.rows / 2);\n    for (let j = 0; j < this.columns; j++) {\n      for (let i = 0; i < middle; i++) {\n        let first = this.get(i, j);\n        let last = this.get(this.rows - 1 - i, j);\n        this.set(i, j, last);\n        this.set(this.rows - 1 - i, j, first);\n      }\n    }\n    return this;\n  }\n\n  kroneckerProduct(other) {\n    other = Matrix.checkMatrix(other);\n\n    let m = this.rows;\n    let n = this.columns;\n    let p = other.rows;\n    let q = other.columns;\n\n    let result = new Matrix(m * p, n * q);\n    for (let i = 0; i < m; i++) {\n      for (let j = 0; j < n; j++) {\n        for (let k = 0; k < p; k++) {\n          for (let l = 0; l < q; l++) {\n            result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));\n          }\n        }\n      }\n    }\n    return result;\n  }\n\n  kroneckerSum(other) {\n    other = Matrix.checkMatrix(other);\n    if (!this.isSquare() || !other.isSquare()) {\n      throw new Error('Kronecker Sum needs two Square Matrices');\n    }\n    let m = this.rows;\n    let n = other.rows;\n    let AxI = this.kroneckerProduct(Matrix.eye(n, n));\n    let IxB = Matrix.eye(m, m).kroneckerProduct(other);\n    return AxI.add(IxB);\n  }\n\n  transpose() {\n    let result = new Matrix(this.columns, this.rows);\n    for (let i = 0; i < this.rows; i++) {\n      for (let j = 0; j < this.columns; j++) {\n        result.set(j, i, this.get(i, j));\n      }\n    }\n    return result;\n  }\n\n  sortRows(compareFunction = compareNumbers) {\n    for (let i = 0; i < this.rows; i++) {\n      this.setRow(i, this.getRow(i).sort(compareFunction));\n    }\n    return this;\n  }\n\n  sortColumns(compareFunction = compareNumbers) {\n    for (let i = 0; i < this.columns; i++) {\n      this.setColumn(i, this.getColumn(i).sort(compareFunction));\n    }\n    return this;\n  }\n\n  subMatrix(startRow, endRow, startColumn, endColumn) {\n    checkRange(this, startRow, endRow, startColumn, endColumn);\n    let newMatrix = new Matrix(\n      endRow - startRow + 1,\n      endColumn - startColumn + 1,\n    );\n    for (let i = startRow; i <= endRow; i++) {\n      for (let j = startColumn; j <= endColumn; j++) {\n        newMatrix.set(i - startRow, j - startColumn, this.get(i, j));\n      }\n    }\n    return newMatrix;\n  }\n\n  subMatrixRow(indices, startColumn, endColumn) {\n    if (startColumn === undefined) startColumn = 0;\n    if (endColumn === undefined) endColumn = this.columns - 1;\n    if (\n      startColumn > endColumn ||\n      startColumn < 0 ||\n      startColumn >= this.columns ||\n      endColumn < 0 ||\n      endColumn >= this.columns\n    ) {\n      throw new RangeError('Argument out of range');\n    }\n\n    let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1);\n    for (let i = 0; i < indices.length; i++) {\n      for (let j = startColumn; j <= endColumn; j++) {\n        if (indices[i] < 0 || indices[i] >= this.rows) {\n          throw new RangeError(`Row index out of range: ${indices[i]}`);\n        }\n        newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n      }\n    }\n    return newMatrix;\n  }\n\n  subMatrixColumn(indices, startRow, endRow) {\n    if (startRow === undefined) startRow = 0;\n    if (endRow === undefined) endRow = this.rows - 1;\n    if (\n      startRow > endRow ||\n      startRow < 0 ||\n      startRow >= this.rows ||\n      endRow < 0 ||\n      endRow >= this.rows\n    ) {\n      throw new RangeError('Argument out of range');\n    }\n\n    let newMatrix = new Matrix(endRow - startRow + 1, indices.length);\n    for (let i = 0; i < indices.length; i++) {\n      for (let j = startRow; j <= endRow; j++) {\n        if (indices[i] < 0 || indices[i] >= this.columns) {\n          throw new RangeError(`Column index out of range: ${indices[i]}`);\n        }\n        newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n      }\n    }\n    return newMatrix;\n  }\n\n  setSubMatrix(matrix, startRow, startColumn) {\n    matrix = Matrix.checkMatrix(matrix);\n    if (matrix.isEmpty()) {\n      return this;\n    }\n    let endRow = startRow + matrix.rows - 1;\n    let endColumn = startColumn + matrix.columns - 1;\n    checkRange(this, startRow, endRow, startColumn, endColumn);\n    for (let i = 0; i < matrix.rows; i++) {\n      for (let j = 0; j < matrix.columns; j++) {\n        this.set(startRow + i, startColumn + j, matrix.get(i, j));\n      }\n    }\n    return this;\n  }\n\n  selection(rowIndices, columnIndices) {\n    checkRowIndices(this, rowIndices);\n    checkColumnIndices(this, columnIndices);\n    let newMatrix = new Matrix(rowIndices.length, columnIndices.length);\n    for (let i = 0; i < rowIndices.length; i++) {\n      let rowIndex = rowIndices[i];\n      for (let j = 0; j < columnIndices.length; j++) {\n        let columnIndex = columnIndices[j];\n        newMatrix.set(i, j, this.get(rowIndex, columnIndex));\n      }\n    }\n    return newMatrix;\n  }\n\n  trace() {\n    let min = Math.min(this.rows, this.columns);\n    let trace = 0;\n    for (let i = 0; i < min; i++) {\n      trace += this.get(i, i);\n    }\n    return trace;\n  }\n\n  clone() {\n    return this.constructor.copy(this, new Matrix(this.rows, this.columns));\n  }\n\n  /**\n   * @template {AbstractMatrix} M\n   * @param {AbstractMatrix} from\n   * @param {M} to\n   * @return {M}\n   */\n  static copy(from, to) {\n    for (const [row, column, value] of from.entries()) {\n      to.set(row, column, value);\n    }\n\n    return to;\n  }\n\n  sum(by) {\n    switch (by) {\n      case 'row':\n        return sumByRow(this);\n      case 'column':\n        return sumByColumn(this);\n      case undefined:\n        return sumAll(this);\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  product(by) {\n    switch (by) {\n      case 'row':\n        return productByRow(this);\n      case 'column':\n        return productByColumn(this);\n      case undefined:\n        return productAll(this);\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  mean(by) {\n    const sum = this.sum(by);\n    switch (by) {\n      case 'row': {\n        for (let i = 0; i < this.rows; i++) {\n          sum[i] /= this.columns;\n        }\n        return sum;\n      }\n      case 'column': {\n        for (let i = 0; i < this.columns; i++) {\n          sum[i] /= this.rows;\n        }\n        return sum;\n      }\n      case undefined:\n        return sum / this.size;\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  variance(by, options = {}) {\n    if (typeof by === 'object') {\n      options = by;\n      by = undefined;\n    }\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { unbiased = true, mean = this.mean(by) } = options;\n    if (typeof unbiased !== 'boolean') {\n      throw new TypeError('unbiased must be a boolean');\n    }\n    switch (by) {\n      case 'row': {\n        if (!isAnyArray(mean)) {\n          throw new TypeError('mean must be an array');\n        }\n        return varianceByRow(this, unbiased, mean);\n      }\n      case 'column': {\n        if (!isAnyArray(mean)) {\n          throw new TypeError('mean must be an array');\n        }\n        return varianceByColumn(this, unbiased, mean);\n      }\n      case undefined: {\n        if (typeof mean !== 'number') {\n          throw new TypeError('mean must be a number');\n        }\n        return varianceAll(this, unbiased, mean);\n      }\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  standardDeviation(by, options) {\n    if (typeof by === 'object') {\n      options = by;\n      by = undefined;\n    }\n    const variance = this.variance(by, options);\n    if (by === undefined) {\n      return Math.sqrt(variance);\n    } else {\n      for (let i = 0; i < variance.length; i++) {\n        variance[i] = Math.sqrt(variance[i]);\n      }\n      return variance;\n    }\n  }\n\n  center(by, options = {}) {\n    if (typeof by === 'object') {\n      options = by;\n      by = undefined;\n    }\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    const { center = this.mean(by) } = options;\n    switch (by) {\n      case 'row': {\n        if (!isAnyArray(center)) {\n          throw new TypeError('center must be an array');\n        }\n        centerByRow(this, center);\n        return this;\n      }\n      case 'column': {\n        if (!isAnyArray(center)) {\n          throw new TypeError('center must be an array');\n        }\n        centerByColumn(this, center);\n        return this;\n      }\n      case undefined: {\n        if (typeof center !== 'number') {\n          throw new TypeError('center must be a number');\n        }\n        centerAll(this, center);\n        return this;\n      }\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  scale(by, options = {}) {\n    if (typeof by === 'object') {\n      options = by;\n      by = undefined;\n    }\n    if (typeof options !== 'object') {\n      throw new TypeError('options must be an object');\n    }\n    let scale = options.scale;\n    switch (by) {\n      case 'row': {\n        if (scale === undefined) {\n          scale = getScaleByRow(this);\n        } else if (!isAnyArray(scale)) {\n          throw new TypeError('scale must be an array');\n        }\n        scaleByRow(this, scale);\n        return this;\n      }\n      case 'column': {\n        if (scale === undefined) {\n          scale = getScaleByColumn(this);\n        } else if (!isAnyArray(scale)) {\n          throw new TypeError('scale must be an array');\n        }\n        scaleByColumn(this, scale);\n        return this;\n      }\n      case undefined: {\n        if (scale === undefined) {\n          scale = getScaleAll(this);\n        } else if (typeof scale !== 'number') {\n          throw new TypeError('scale must be a number');\n        }\n        scaleAll(this, scale);\n        return this;\n      }\n      default:\n        throw new Error(`invalid option: ${by}`);\n    }\n  }\n\n  toString(options) {\n    return inspectMatrixWithOptions(this, options);\n  }\n\n  [Symbol.iterator]() {\n    return this.entries();\n  }\n\n  /**\n   * iterator from left to right, from top to bottom\n   * yield [row, column, value]\n   * @returns {Generator<[number, number, number], void, void>}\n   */\n  *entries() {\n    for (let row = 0; row < this.rows; row++) {\n      for (let col = 0; col < this.columns; col++) {\n        yield [row, col, this.get(row, col)];\n      }\n    }\n  }\n\n  /**\n   * iterator from left to right, from top to bottom\n   * yield value\n   * @returns {Generator<number, void, void>}\n   */\n  *values() {\n    for (let row = 0; row < this.rows; row++) {\n      for (let col = 0; col < this.columns; col++) {\n        yield this.get(row, col);\n      }\n    }\n  }\n}\n\nAbstractMatrix.prototype.klass = 'Matrix';\nif (typeof Symbol !== 'undefined') {\n  AbstractMatrix.prototype[Symbol.for('nodejs.util.inspect.custom')] =\n    inspectMatrix;\n}\n\nfunction compareNumbers(a, b) {\n  return a - b;\n}\n\nfunction isArrayOfNumbers(array) {\n  return array.every((element) => {\n    return typeof element === 'number';\n  });\n}\n\n// Synonyms\nAbstractMatrix.random = AbstractMatrix.rand;\nAbstractMatrix.randomInt = AbstractMatrix.randInt;\nAbstractMatrix.diagonal = AbstractMatrix.diag;\nAbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;\nAbstractMatrix.identity = AbstractMatrix.eye;\nAbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;\nAbstractMatrix.prototype.tensorProduct =\n  AbstractMatrix.prototype.kroneckerProduct;\n\nclass Matrix extends AbstractMatrix {\n  /**\n   * @type {Float64Array[]}\n   */\n  data;\n\n  /**\n   * Init an empty matrix\n   * @param {number} nRows\n   * @param {number} nColumns\n   */\n  #initData(nRows, nColumns) {\n    this.data = [];\n\n    if (Number.isInteger(nColumns) && nColumns >= 0) {\n      for (let i = 0; i < nRows; i++) {\n        this.data.push(new Float64Array(nColumns));\n      }\n    } else {\n      throw new TypeError('nColumns must be a positive integer');\n    }\n\n    this.rows = nRows;\n    this.columns = nColumns;\n  }\n\n  constructor(nRows, nColumns) {\n    super();\n    if (Matrix.isMatrix(nRows)) {\n      this.#initData(nRows.rows, nRows.columns);\n      Matrix.copy(nRows, this);\n    } else if (Number.isInteger(nRows) && nRows >= 0) {\n      this.#initData(nRows, nColumns);\n    } else if (isAnyArray(nRows)) {\n      // Copy the values from the 2D array\n      const arrayData = nRows;\n      nRows = arrayData.length;\n      nColumns = nRows ? arrayData[0].length : 0;\n      if (typeof nColumns !== 'number') {\n        throw new TypeError(\n          'Data must be a 2D array with at least one element',\n        );\n      }\n      this.data = [];\n\n      for (let i = 0; i < nRows; i++) {\n        if (arrayData[i].length !== nColumns) {\n          throw new RangeError('Inconsistent array dimensions');\n        }\n        if (!isArrayOfNumbers(arrayData[i])) {\n          throw new TypeError('Input data contains non-numeric values');\n        }\n        this.data.push(Float64Array.from(arrayData[i]));\n      }\n\n      this.rows = nRows;\n      this.columns = nColumns;\n    } else {\n      throw new TypeError(\n        'First argument must be a positive number or an array',\n      );\n    }\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.data[rowIndex][columnIndex] = value;\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.data[rowIndex][columnIndex];\n  }\n\n  removeRow(index) {\n    checkRowIndex(this, index);\n    this.data.splice(index, 1);\n    this.rows -= 1;\n    return this;\n  }\n\n  addRow(index, array) {\n    if (array === undefined) {\n      array = index;\n      index = this.rows;\n    }\n    checkRowIndex(this, index, true);\n    array = Float64Array.from(checkRowVector(this, array));\n    this.data.splice(index, 0, array);\n    this.rows += 1;\n    return this;\n  }\n\n  removeColumn(index) {\n    checkColumnIndex(this, index);\n    for (let i = 0; i < this.rows; i++) {\n      const newRow = new Float64Array(this.columns - 1);\n      for (let j = 0; j < index; j++) {\n        newRow[j] = this.data[i][j];\n      }\n      for (let j = index + 1; j < this.columns; j++) {\n        newRow[j - 1] = this.data[i][j];\n      }\n      this.data[i] = newRow;\n    }\n    this.columns -= 1;\n    return this;\n  }\n\n  addColumn(index, array) {\n    if (typeof array === 'undefined') {\n      array = index;\n      index = this.columns;\n    }\n    checkColumnIndex(this, index, true);\n    array = checkColumnVector(this, array);\n    for (let i = 0; i < this.rows; i++) {\n      const newRow = new Float64Array(this.columns + 1);\n      let j = 0;\n      for (; j < index; j++) {\n        newRow[j] = this.data[i][j];\n      }\n      newRow[j++] = array[i];\n      for (; j < this.columns + 1; j++) {\n        newRow[j] = this.data[i][j - 1];\n      }\n      this.data[i] = newRow;\n    }\n    this.columns += 1;\n    return this;\n  }\n}\n\ninstallMathOperations(AbstractMatrix, Matrix);\n\n/**\n * @typedef {0 | 1 | number | boolean} Mask\n */\n\nclass SymmetricMatrix extends AbstractMatrix {\n  /** @type {Matrix} */\n  #matrix;\n\n  get size() {\n    return this.#matrix.size;\n  }\n\n  get rows() {\n    return this.#matrix.rows;\n  }\n\n  get columns() {\n    return this.#matrix.columns;\n  }\n\n  get diagonalSize() {\n    return this.rows;\n  }\n\n  /**\n   * not the same as matrix.isSymmetric()\n   * Here is to check if it's instanceof SymmetricMatrix without bundling issues\n   *\n   * @param value\n   * @returns {boolean}\n   */\n  static isSymmetricMatrix(value) {\n    return Matrix.isMatrix(value) && value.klassType === 'SymmetricMatrix';\n  }\n\n  /**\n   * @param diagonalSize\n   * @return {SymmetricMatrix}\n   */\n  static zeros(diagonalSize) {\n    return new this(diagonalSize);\n  }\n\n  /**\n   * @param diagonalSize\n   * @return {SymmetricMatrix}\n   */\n  static ones(diagonalSize) {\n    return new this(diagonalSize).fill(1);\n  }\n\n  /**\n   * @param {number | AbstractMatrix | ArrayLike<ArrayLike<number>>} diagonalSize\n   * @return {this}\n   */\n  constructor(diagonalSize) {\n    super();\n\n    if (Matrix.isMatrix(diagonalSize)) {\n      if (!diagonalSize.isSymmetric()) {\n        throw new TypeError('not symmetric data');\n      }\n\n      this.#matrix = Matrix.copy(\n        diagonalSize,\n        new Matrix(diagonalSize.rows, diagonalSize.rows),\n      );\n    } else if (Number.isInteger(diagonalSize) && diagonalSize >= 0) {\n      this.#matrix = new Matrix(diagonalSize, diagonalSize);\n    } else {\n      this.#matrix = new Matrix(diagonalSize);\n\n      if (!this.isSymmetric()) {\n        throw new TypeError('not symmetric data');\n      }\n    }\n  }\n\n  clone() {\n    const matrix = new SymmetricMatrix(this.diagonalSize);\n\n    for (const [row, col, value] of this.upperRightEntries()) {\n      matrix.set(row, col, value);\n    }\n\n    return matrix;\n  }\n\n  toMatrix() {\n    return new Matrix(this);\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.#matrix.get(rowIndex, columnIndex);\n  }\n  set(rowIndex, columnIndex, value) {\n    // symmetric set\n    this.#matrix.set(rowIndex, columnIndex, value);\n    this.#matrix.set(columnIndex, rowIndex, value);\n\n    return this;\n  }\n\n  removeCross(index) {\n    // symmetric remove side\n    this.#matrix.removeRow(index);\n    this.#matrix.removeColumn(index);\n\n    return this;\n  }\n\n  addCross(index, array) {\n    if (array === undefined) {\n      array = index;\n      index = this.diagonalSize;\n    }\n\n    const row = array.slice();\n    row.splice(index, 1);\n\n    this.#matrix.addRow(index, row);\n    this.#matrix.addColumn(index, array);\n\n    return this;\n  }\n\n  /**\n   * @param {Mask[]} mask\n   */\n  applyMask(mask) {\n    if (mask.length !== this.diagonalSize) {\n      throw new RangeError('Mask size do not match with matrix size');\n    }\n\n    // prepare sides to remove from matrix from mask\n    /** @type {number[]} */\n    const sidesToRemove = [];\n    for (const [index, passthroughs] of mask.entries()) {\n      if (passthroughs) continue;\n      sidesToRemove.push(index);\n    }\n    // to remove from highest to lowest for no mutation shifting\n    sidesToRemove.reverse();\n\n    // remove sides\n    for (const sideIndex of sidesToRemove) {\n      this.removeCross(sideIndex);\n    }\n\n    return this;\n  }\n\n  /**\n   * Compact format upper-right corner of matrix\n   * iterate from left to right, from top to bottom.\n   *\n   * ```\n   *   A B C D\n   * A 1 2 3 4\n   * B 2 5 6 7\n   * C 3 6 8 9\n   * D 4 7 9 10\n   * ```\n   *\n   * will return compact 1D array `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`\n   *\n   * length is S(i=0, n=sideSize) => 10 for a 4 sideSized matrix\n   *\n   * @returns {number[]}\n   */\n  toCompact() {\n    const { diagonalSize } = this;\n\n    /** @type {number[]} */\n    const compact = new Array((diagonalSize * (diagonalSize + 1)) / 2);\n    for (let col = 0, row = 0, index = 0; index < compact.length; index++) {\n      compact[index] = this.get(row, col);\n\n      if (++col >= diagonalSize) col = ++row;\n    }\n\n    return compact;\n  }\n\n  /**\n   * @param {number[]} compact\n   * @return {SymmetricMatrix}\n   */\n  static fromCompact(compact) {\n    const compactSize = compact.length;\n    // compactSize = (sideSize * (sideSize + 1)) / 2\n    // 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\n    // sideSize = (Sqrt(8 × compactSize + 1) - 1) / 2\n    const diagonalSize = (Math.sqrt(8 * compactSize + 1) - 1) / 2;\n\n    if (!Number.isInteger(diagonalSize)) {\n      throw new TypeError(\n        `This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(\n          compact,\n        )}`,\n      );\n    }\n\n    const matrix = new SymmetricMatrix(diagonalSize);\n    for (let col = 0, row = 0, index = 0; index < compactSize; index++) {\n      matrix.set(col, row, compact[index]);\n      if (++col >= diagonalSize) col = ++row;\n    }\n\n    return matrix;\n  }\n\n  /**\n   * half iterator upper-right-corner from left to right, from top to bottom\n   * yield [row, column, value]\n   *\n   * @returns {Generator<[number, number, number], void, void>}\n   */\n  *upperRightEntries() {\n    for (let row = 0, col = 0; row < this.diagonalSize; void 0) {\n      const value = this.get(row, col);\n\n      yield [row, col, value];\n\n      // at the end of row, move cursor to next row at diagonal position\n      if (++col >= this.diagonalSize) col = ++row;\n    }\n  }\n\n  /**\n   * half iterator upper-right-corner from left to right, from top to bottom\n   * yield value\n   *\n   * @returns {Generator<[number, number, number], void, void>}\n   */\n  *upperRightValues() {\n    for (let row = 0, col = 0; row < this.diagonalSize; void 0) {\n      const value = this.get(row, col);\n\n      yield value;\n\n      // at the end of row, move cursor to next row at diagonal position\n      if (++col >= this.diagonalSize) col = ++row;\n    }\n  }\n}\nSymmetricMatrix.prototype.klassType = 'SymmetricMatrix';\n\nclass DistanceMatrix extends SymmetricMatrix {\n  /**\n   * not the same as matrix.isSymmetric()\n   * Here is to check if it's instanceof SymmetricMatrix without bundling issues\n   *\n   * @param value\n   * @returns {boolean}\n   */\n  static isDistanceMatrix(value) {\n    return (\n      SymmetricMatrix.isSymmetricMatrix(value) &&\n      value.klassSubType === 'DistanceMatrix'\n    );\n  }\n\n  constructor(sideSize) {\n    super(sideSize);\n\n    if (!this.isDistance()) {\n      throw new TypeError('Provided arguments do no produce a distance matrix');\n    }\n  }\n\n  set(rowIndex, columnIndex, value) {\n    // distance matrix diagonal is 0\n    if (rowIndex === columnIndex) value = 0;\n\n    return super.set(rowIndex, columnIndex, value);\n  }\n\n  addCross(index, array) {\n    if (array === undefined) {\n      array = index;\n      index = this.diagonalSize;\n    }\n\n    // ensure distance\n    array = array.slice();\n    array[index] = 0;\n\n    return super.addCross(index, array);\n  }\n\n  toSymmetricMatrix() {\n    return new SymmetricMatrix(this);\n  }\n\n  clone() {\n    const matrix = new DistanceMatrix(this.diagonalSize);\n\n    for (const [row, col, value] of this.upperRightEntries()) {\n      if (row === col) continue;\n      matrix.set(row, col, value);\n    }\n\n    return matrix;\n  }\n\n  /**\n   * Compact format upper-right corner of matrix\n   * no diagonal (only zeros)\n   * iterable from left to right, from top to bottom.\n   *\n   * ```\n   *   A B C D\n   * A 0 1 2 3\n   * B 1 0 4 5\n   * C 2 4 0 6\n   * D 3 5 6 0\n   * ```\n   *\n   * will return compact 1D array `[1, 2, 3, 4, 5, 6]`\n   *\n   * length is S(i=0, n=sideSize-1) => 6 for a 4 side sized matrix\n   *\n   * @returns {number[]}\n   */\n  toCompact() {\n    const { diagonalSize } = this;\n    const compactLength = ((diagonalSize - 1) * diagonalSize) / 2;\n\n    /** @type {number[]} */\n    const compact = new Array(compactLength);\n    for (let col = 1, row = 0, index = 0; index < compact.length; index++) {\n      compact[index] = this.get(row, col);\n\n      if (++col >= diagonalSize) col = ++row + 1;\n    }\n\n    return compact;\n  }\n\n  /**\n   * @param {number[]} compact\n   */\n  static fromCompact(compact) {\n    const compactSize = compact.length;\n\n    if (compactSize === 0) {\n      return new this(0);\n    }\n\n    // compactSize in Natural integer range ]0;∞]\n    // compactSize = (sideSize * (sideSize - 1)) / 2\n    // sideSize = (Sqrt(8 × compactSize + 1) + 1) / 2\n    const diagonalSize = (Math.sqrt(8 * compactSize + 1) + 1) / 2;\n\n    if (!Number.isInteger(diagonalSize)) {\n      throw new TypeError(\n        `This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(\n          compact,\n        )}`,\n      );\n    }\n\n    const matrix = new this(diagonalSize);\n    for (let col = 1, row = 0, index = 0; index < compactSize; index++) {\n      matrix.set(col, row, compact[index]);\n      if (++col >= diagonalSize) col = ++row + 1;\n    }\n\n    return matrix;\n  }\n}\nDistanceMatrix.prototype.klassSubType = 'DistanceMatrix';\n\nclass BaseView extends AbstractMatrix {\n  constructor(matrix, rows, columns) {\n    super();\n    this.matrix = matrix;\n    this.rows = rows;\n    this.columns = columns;\n  }\n}\n\nclass MatrixColumnView extends BaseView {\n  constructor(matrix, column) {\n    checkColumnIndex(matrix, column);\n    super(matrix, matrix.rows, 1);\n    this.column = column;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(rowIndex, this.column, value);\n    return this;\n  }\n\n  get(rowIndex) {\n    return this.matrix.get(rowIndex, this.column);\n  }\n}\n\nclass MatrixColumnSelectionView extends BaseView {\n  constructor(matrix, columnIndices) {\n    checkColumnIndices(matrix, columnIndices);\n    super(matrix, matrix.rows, columnIndices.length);\n    this.columnIndices = columnIndices;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);\n  }\n}\n\nclass MatrixFlipColumnView extends BaseView {\n  constructor(matrix) {\n    super(matrix, matrix.rows, matrix.columns);\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n  }\n}\n\nclass MatrixFlipRowView extends BaseView {\n  constructor(matrix) {\n    super(matrix, matrix.rows, matrix.columns);\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n  }\n}\n\nclass MatrixRowView extends BaseView {\n  constructor(matrix, row) {\n    checkRowIndex(matrix, row);\n    super(matrix, 1, matrix.columns);\n    this.row = row;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(this.row, columnIndex, value);\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(this.row, columnIndex);\n  }\n}\n\nclass MatrixRowSelectionView extends BaseView {\n  constructor(matrix, rowIndices) {\n    checkRowIndices(matrix, rowIndices);\n    super(matrix, rowIndices.length, matrix.columns);\n    this.rowIndices = rowIndices;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(this.rowIndices[rowIndex], columnIndex);\n  }\n}\n\nclass MatrixSelectionView extends BaseView {\n  constructor(matrix, rowIndices, columnIndices) {\n    checkRowIndices(matrix, rowIndices);\n    checkColumnIndices(matrix, columnIndices);\n    super(matrix, rowIndices.length, columnIndices.length);\n    this.rowIndices = rowIndices;\n    this.columnIndices = columnIndices;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(\n      this.rowIndices[rowIndex],\n      this.columnIndices[columnIndex],\n      value,\n    );\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(\n      this.rowIndices[rowIndex],\n      this.columnIndices[columnIndex],\n    );\n  }\n}\n\nclass MatrixSubView extends BaseView {\n  constructor(matrix, startRow, endRow, startColumn, endColumn) {\n    checkRange(matrix, startRow, endRow, startColumn, endColumn);\n    super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);\n    this.startRow = startRow;\n    this.startColumn = startColumn;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(\n      this.startRow + rowIndex,\n      this.startColumn + columnIndex,\n      value,\n    );\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(\n      this.startRow + rowIndex,\n      this.startColumn + columnIndex,\n    );\n  }\n}\n\nclass MatrixTransposeView extends BaseView {\n  constructor(matrix) {\n    super(matrix, matrix.columns, matrix.rows);\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.matrix.set(columnIndex, rowIndex, value);\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.matrix.get(columnIndex, rowIndex);\n  }\n}\n\nclass WrapperMatrix1D extends AbstractMatrix {\n  constructor(data, options = {}) {\n    const { rows = 1 } = options;\n\n    if (data.length % rows !== 0) {\n      throw new Error('the data length is not divisible by the number of rows');\n    }\n    super();\n    this.rows = rows;\n    this.columns = data.length / rows;\n    this.data = data;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    let index = this._calculateIndex(rowIndex, columnIndex);\n    this.data[index] = value;\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    let index = this._calculateIndex(rowIndex, columnIndex);\n    return this.data[index];\n  }\n\n  _calculateIndex(row, column) {\n    return row * this.columns + column;\n  }\n}\n\nclass WrapperMatrix2D extends AbstractMatrix {\n  constructor(data) {\n    super();\n    this.data = data;\n    this.rows = data.length;\n    this.columns = data[0].length;\n  }\n\n  set(rowIndex, columnIndex, value) {\n    this.data[rowIndex][columnIndex] = value;\n    return this;\n  }\n\n  get(rowIndex, columnIndex) {\n    return this.data[rowIndex][columnIndex];\n  }\n}\n\nfunction wrap(array, options) {\n  if (isAnyArray(array)) {\n    if (array[0] && isAnyArray(array[0])) {\n      return new WrapperMatrix2D(array);\n    } else {\n      return new WrapperMatrix1D(array, options);\n    }\n  } else {\n    throw new Error('the argument is not an array');\n  }\n}\n\nclass LuDecomposition {\n  constructor(matrix) {\n    matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n    let lu = matrix.clone();\n    let rows = lu.rows;\n    let columns = lu.columns;\n    let pivotVector = new Float64Array(rows);\n    let pivotSign = 1;\n    let i, j, k, p, s, t, v;\n    let LUcolj, kmax;\n\n    for (i = 0; i < rows; i++) {\n      pivotVector[i] = i;\n    }\n\n    LUcolj = new Float64Array(rows);\n\n    for (j = 0; j < columns; j++) {\n      for (i = 0; i < rows; i++) {\n        LUcolj[i] = lu.get(i, j);\n      }\n\n      for (i = 0; i < rows; i++) {\n        kmax = Math.min(i, j);\n        s = 0;\n        for (k = 0; k < kmax; k++) {\n          s += lu.get(i, k) * LUcolj[k];\n        }\n        LUcolj[i] -= s;\n        lu.set(i, j, LUcolj[i]);\n      }\n\n      p = j;\n      for (i = j + 1; i < rows; i++) {\n        if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {\n          p = i;\n        }\n      }\n\n      if (p !== j) {\n        for (k = 0; k < columns; k++) {\n          t = lu.get(p, k);\n          lu.set(p, k, lu.get(j, k));\n          lu.set(j, k, t);\n        }\n\n        v = pivotVector[p];\n        pivotVector[p] = pivotVector[j];\n        pivotVector[j] = v;\n\n        pivotSign = -pivotSign;\n      }\n\n      if (j < rows && lu.get(j, j) !== 0) {\n        for (i = j + 1; i < rows; i++) {\n          lu.set(i, j, lu.get(i, j) / lu.get(j, j));\n        }\n      }\n    }\n\n    this.LU = lu;\n    this.pivotVector = pivotVector;\n    this.pivotSign = pivotSign;\n  }\n\n  isSingular() {\n    let data = this.LU;\n    let col = data.columns;\n    for (let j = 0; j < col; j++) {\n      if (data.get(j, j) === 0) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  solve(value) {\n    value = Matrix.checkMatrix(value);\n\n    let lu = this.LU;\n    let rows = lu.rows;\n\n    if (rows !== value.rows) {\n      throw new Error('Invalid matrix dimensions');\n    }\n    if (this.isSingular()) {\n      throw new Error('LU matrix is singular');\n    }\n\n    let count = value.columns;\n    let X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n    let columns = lu.columns;\n    let i, j, k;\n\n    for (k = 0; k < columns; k++) {\n      for (i = k + 1; i < columns; i++) {\n        for (j = 0; j < count; j++) {\n          X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n        }\n      }\n    }\n    for (k = columns - 1; k >= 0; k--) {\n      for (j = 0; j < count; j++) {\n        X.set(k, j, X.get(k, j) / lu.get(k, k));\n      }\n      for (i = 0; i < k; i++) {\n        for (j = 0; j < count; j++) {\n          X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n        }\n      }\n    }\n    return X;\n  }\n\n  get determinant() {\n    let data = this.LU;\n    if (!data.isSquare()) {\n      throw new Error('Matrix must be square');\n    }\n    let determinant = this.pivotSign;\n    let col = data.columns;\n    for (let j = 0; j < col; j++) {\n      determinant *= data.get(j, j);\n    }\n    return determinant;\n  }\n\n  get lowerTriangularMatrix() {\n    let data = this.LU;\n    let rows = data.rows;\n    let columns = data.columns;\n    let X = new Matrix(rows, columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        if (i > j) {\n          X.set(i, j, data.get(i, j));\n        } else if (i === j) {\n          X.set(i, j, 1);\n        } else {\n          X.set(i, j, 0);\n        }\n      }\n    }\n    return X;\n  }\n\n  get upperTriangularMatrix() {\n    let data = this.LU;\n    let rows = data.rows;\n    let columns = data.columns;\n    let X = new Matrix(rows, columns);\n    for (let i = 0; i < rows; i++) {\n      for (let j = 0; j < columns; j++) {\n        if (i <= j) {\n          X.set(i, j, data.get(i, j));\n        } else {\n          X.set(i, j, 0);\n        }\n      }\n    }\n    return X;\n  }\n\n  get pivotPermutationVector() {\n    return Array.from(this.pivotVector);\n  }\n}\n\n/**\n * Transpose a square matrix in place, without allocating a copy.\n * Used to restore the logical layout of decomposition outputs that were\n * accumulated in transposed storage for cache-sequential inner loops.\n * @param {import('../matrix').default} matrix - square matrix, mutated in place\n * @returns {import('../matrix').default} the same matrix\n */\nfunction transposeSquareInPlace(matrix) {\n  const data = matrix.data;\n  const n = matrix.rows;\n  for (let i = 0; i < n; i++) {\n    const rowI = data[i];\n    for (let j = i + 1; j < n; j++) {\n      const tmp = rowI[j];\n      rowI[j] = data[j][i];\n      data[j][i] = tmp;\n    }\n  }\n  return matrix;\n}\n\nfunction hypotenuse(a, b) {\n  let r = 0;\n  if (Math.abs(a) > Math.abs(b)) {\n    r = b / a;\n    return Math.abs(a) * Math.sqrt(1 + r * r);\n  }\n  if (b !== 0) {\n    r = a / b;\n    return Math.abs(b) * Math.sqrt(1 + r * r);\n  }\n  return 0;\n}\n\nclass QrDecomposition {\n  constructor(value) {\n    value = WrapperMatrix2D.checkMatrix(value);\n\n    let qr = value.clone();\n    let m = value.rows;\n    let n = value.columns;\n    let rdiag = new Float64Array(n);\n    let i, j, k, s;\n\n    for (k = 0; k < n; k++) {\n      let nrm = 0;\n      for (i = k; i < m; i++) {\n        nrm = hypotenuse(nrm, qr.get(i, k));\n      }\n      if (nrm !== 0) {\n        if (qr.get(k, k) < 0) {\n          nrm = -nrm;\n        }\n        for (i = k; i < m; i++) {\n          qr.set(i, k, qr.get(i, k) / nrm);\n        }\n        qr.set(k, k, qr.get(k, k) + 1);\n        for (j = k + 1; j < n; j++) {\n          s = 0;\n          for (i = k; i < m; i++) {\n            s += qr.get(i, k) * qr.get(i, j);\n          }\n          s = -s / qr.get(k, k);\n          for (i = k; i < m; i++) {\n            qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));\n          }\n        }\n      }\n      rdiag[k] = -nrm;\n    }\n\n    this.QR = qr;\n    this.Rdiag = rdiag;\n  }\n\n  solve(value) {\n    value = Matrix.checkMatrix(value);\n\n    let qr = this.QR;\n    let m = qr.rows;\n\n    if (value.rows !== m) {\n      throw new Error('Matrix row dimensions must agree');\n    }\n    if (!this.isFullRank()) {\n      throw new Error('Matrix is rank deficient');\n    }\n\n    let count = value.columns;\n    let X = value.clone();\n    let n = qr.columns;\n    let i, j, k, s;\n\n    for (k = 0; k < n; k++) {\n      for (j = 0; j < count; j++) {\n        s = 0;\n        for (i = k; i < m; i++) {\n          s += qr.get(i, k) * X.get(i, j);\n        }\n        s = -s / qr.get(k, k);\n        for (i = k; i < m; i++) {\n          X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n        }\n      }\n    }\n    for (k = n - 1; k >= 0; k--) {\n      for (j = 0; j < count; j++) {\n        X.set(k, j, X.get(k, j) / this.Rdiag[k]);\n      }\n      for (i = 0; i < k; i++) {\n        for (j = 0; j < count; j++) {\n          X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));\n        }\n      }\n    }\n\n    return X.subMatrix(0, n - 1, 0, count - 1);\n  }\n\n  isFullRank() {\n    let columns = this.QR.columns;\n    for (let i = 0; i < columns; i++) {\n      if (this.Rdiag[i] === 0) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  get upperTriangularMatrix() {\n    let qr = this.QR;\n    let n = qr.columns;\n    let X = new Matrix(n, n);\n    let i, j;\n    for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) {\n        if (i < j) {\n          X.set(i, j, qr.get(i, j));\n        } else if (i === j) {\n          X.set(i, j, this.Rdiag[i]);\n        } else {\n          X.set(i, j, 0);\n        }\n      }\n    }\n    return X;\n  }\n\n  get orthogonalMatrix() {\n    let qr = this.QR;\n    let rows = qr.rows;\n    let columns = qr.columns;\n    let X = new Matrix(rows, columns);\n    let i, j, k, s;\n\n    for (k = columns - 1; k >= 0; k--) {\n      for (i = 0; i < rows; i++) {\n        X.set(i, k, 0);\n      }\n      X.set(k, k, 1);\n      for (j = k; j < columns; j++) {\n        if (qr.get(k, k) !== 0) {\n          s = 0;\n          for (i = k; i < rows; i++) {\n            s += qr.get(i, k) * X.get(i, j);\n          }\n\n          s = -s / qr.get(k, k);\n\n          for (i = k; i < rows; i++) {\n            X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n          }\n        }\n      }\n    }\n    return X;\n  }\n}\n\nclass SingularValueDecomposition {\n  constructor(value, options = {}) {\n    value = WrapperMatrix2D.checkMatrix(value);\n\n    if (value.isEmpty()) {\n      throw new Error('Matrix must be non-empty');\n    }\n\n    let m = value.rows;\n    let n = value.columns;\n\n    const {\n      computeLeftSingularVectors = true,\n      computeRightSingularVectors = true,\n      autoTranspose = false,\n    } = options;\n\n    let wantu = Boolean(computeLeftSingularVectors);\n    let wantv = Boolean(computeRightSingularVectors);\n\n    // Work on the transpose of the input so the hot inner loops (which iterate\n    // over rows for a fixed column) scan memory sequentially in the row-major\n    // backing store. `at` holds the transpose: at.get(j, i) === a.get(i, j)\n    // where `a` is the logical m x n working matrix.\n    let swapped = false;\n    let at;\n    if (m < n) {\n      if (!autoTranspose) {\n        // eslint-disable-next-line no-console\n        console.warn(\n          'Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose',\n        );\n        at = value.transpose();\n      } else {\n        at = value.clone();\n        m = value.columns;\n        n = value.rows;\n        swapped = true;\n        let aux = wantu;\n        wantu = wantv;\n        wantv = aux;\n      }\n    } else {\n      at = value.transpose();\n    }\n\n    let nu = Math.min(m, n);\n    let ni = Math.min(m + 1, n);\n    let s = new Float64Array(ni);\n    // U and V are stored transposed during the computation so the inner loops\n    // (which always vary the row index) scan memory sequentially. They are\n    // transposed back to their logical layout before being returned.\n    // Ut.get(j, i) === U.get(i, j) and Vt.get(j, i) === V.get(i, j).\n    let U = new Matrix(nu, m);\n    let V = new Matrix(n, n);\n\n    let e = new Float64Array(n);\n    let work = new Float64Array(m);\n\n    let si = new Float64Array(ni);\n    for (let i = 0; i < ni; i++) si[i] = i;\n\n    let nct = Math.min(m - 1, n);\n    let nrt = Math.max(0, Math.min(n - 2, m));\n    let mrc = Math.max(nct, nrt);\n\n    for (let k = 0; k < mrc; k++) {\n      if (k < nct) {\n        s[k] = 0;\n        for (let i = k; i < m; i++) {\n          s[k] = hypotenuse(s[k], at.get(k, i));\n        }\n        if (s[k] !== 0) {\n          if (at.get(k, k) < 0) {\n            s[k] = -s[k];\n          }\n          for (let i = k; i < m; i++) {\n            at.set(k, i, at.get(k, i) / s[k]);\n          }\n          at.set(k, k, at.get(k, k) + 1);\n        }\n        s[k] = -s[k];\n      }\n\n      for (let j = k + 1; j < n; j++) {\n        if (k < nct && s[k] !== 0) {\n          let t = 0;\n          for (let i = k; i < m; i++) {\n            t += at.get(k, i) * at.get(j, i);\n          }\n          t = -t / at.get(k, k);\n          for (let i = k; i < m; i++) {\n            at.set(j, i, at.get(j, i) + t * at.get(k, i));\n          }\n        }\n        e[j] = at.get(j, k);\n      }\n\n      if (wantu && k < nct) {\n        for (let i = k; i < m; i++) {\n          U.set(k, i, at.get(k, i));\n        }\n      }\n\n      if (k < nrt) {\n        e[k] = 0;\n        for (let i = k + 1; i < n; i++) {\n          e[k] = hypotenuse(e[k], e[i]);\n        }\n        if (e[k] !== 0) {\n          if (e[k + 1] < 0) {\n            e[k] = 0 - e[k];\n          }\n          for (let i = k + 1; i < n; i++) {\n            e[i] /= e[k];\n          }\n          e[k + 1] += 1;\n        }\n        e[k] = -e[k];\n        if (k + 1 < m && e[k] !== 0) {\n          for (let i = k + 1; i < m; i++) {\n            work[i] = 0;\n          }\n          for (let i = k + 1; i < m; i++) {\n            for (let j = k + 1; j < n; j++) {\n              work[i] += e[j] * at.get(j, i);\n            }\n          }\n          for (let j = k + 1; j < n; j++) {\n            let t = -e[j] / e[k + 1];\n            for (let i = k + 1; i < m; i++) {\n              at.set(j, i, at.get(j, i) + t * work[i]);\n            }\n          }\n        }\n        if (wantv) {\n          for (let i = k + 1; i < n; i++) {\n            V.set(k, i, e[i]);\n          }\n        }\n      }\n    }\n\n    let p = Math.min(n, m + 1);\n    if (nct < n) {\n      s[nct] = at.get(nct, nct);\n    }\n    if (m < p) {\n      s[p - 1] = 0;\n    }\n    if (nrt + 1 < p) {\n      e[nrt] = at.get(p - 1, nrt);\n    }\n    e[p - 1] = 0;\n\n    if (wantu) {\n      for (let j = nct; j < nu; j++) {\n        for (let i = 0; i < m; i++) {\n          U.set(j, i, 0);\n        }\n        U.set(j, j, 1);\n      }\n      for (let k = nct - 1; k >= 0; k--) {\n        if (s[k] !== 0) {\n          for (let j = k + 1; j < nu; j++) {\n            let t = 0;\n            for (let i = k; i < m; i++) {\n              t += U.get(k, i) * U.get(j, i);\n            }\n            t = -t / U.get(k, k);\n            for (let i = k; i < m; i++) {\n              U.set(j, i, U.get(j, i) + t * U.get(k, i));\n            }\n          }\n          for (let i = k; i < m; i++) {\n            U.set(k, i, -U.get(k, i));\n          }\n          U.set(k, k, 1 + U.get(k, k));\n          for (let i = 0; i < k - 1; i++) {\n            U.set(k, i, 0);\n          }\n        } else {\n          for (let i = 0; i < m; i++) {\n            U.set(k, i, 0);\n          }\n          U.set(k, k, 1);\n        }\n      }\n    }\n\n    if (wantv) {\n      for (let k = n - 1; k >= 0; k--) {\n        if (k < nrt && e[k] !== 0) {\n          for (let j = k + 1; j < n; j++) {\n            let t = 0;\n            for (let i = k + 1; i < n; i++) {\n              t += V.get(k, i) * V.get(j, i);\n            }\n            t = -t / V.get(k, k + 1);\n            for (let i = k + 1; i < n; i++) {\n              V.set(j, i, V.get(j, i) + t * V.get(k, i));\n            }\n          }\n        }\n        for (let i = 0; i < n; i++) {\n          V.set(k, i, 0);\n        }\n        V.set(k, k, 1);\n      }\n    }\n\n    let pp = p - 1;\n    let eps = Number.EPSILON;\n    while (p > 0) {\n      let k, kase;\n      for (k = p - 2; k >= -1; k--) {\n        if (k === -1) {\n          break;\n        }\n        const alpha =\n          Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));\n        if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {\n          e[k] = 0;\n          break;\n        }\n      }\n      if (k === p - 2) {\n        kase = 4;\n      } else {\n        let ks;\n        for (ks = p - 1; ks >= k; ks--) {\n          if (ks === k) {\n            break;\n          }\n          let t =\n            (ks !== p ? Math.abs(e[ks]) : 0) +\n            (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);\n          if (Math.abs(s[ks]) <= eps * t) {\n            s[ks] = 0;\n            break;\n          }\n        }\n        if (ks === k) {\n          kase = 3;\n        } else if (ks === p - 1) {\n          kase = 1;\n        } else {\n          kase = 2;\n          k = ks;\n        }\n      }\n\n      k++;\n\n      switch (kase) {\n        case 1: {\n          let f = e[p - 2];\n          e[p - 2] = 0;\n          for (let j = p - 2; j >= k; j--) {\n            let t = hypotenuse(s[j], f);\n            let cs = s[j] / t;\n            let sn = f / t;\n            s[j] = t;\n            if (j !== k) {\n              f = -sn * e[j - 1];\n              e[j - 1] = cs * e[j - 1];\n            }\n            if (wantv) {\n              for (let i = 0; i < n; i++) {\n                t = cs * V.get(j, i) + sn * V.get(p - 1, i);\n                V.set(p - 1, i, -sn * V.get(j, i) + cs * V.get(p - 1, i));\n                V.set(j, i, t);\n              }\n            }\n          }\n          break;\n        }\n        case 2: {\n          let f = e[k - 1];\n          e[k - 1] = 0;\n          for (let j = k; j < p; j++) {\n            let t = hypotenuse(s[j], f);\n            let cs = s[j] / t;\n            let sn = f / t;\n            s[j] = t;\n            f = -sn * e[j];\n            e[j] = cs * e[j];\n            if (wantu) {\n              for (let i = 0; i < m; i++) {\n                t = cs * U.get(j, i) + sn * U.get(k - 1, i);\n                U.set(k - 1, i, -sn * U.get(j, i) + cs * U.get(k - 1, i));\n                U.set(j, i, t);\n              }\n            }\n          }\n          break;\n        }\n        case 3: {\n          const scale = Math.max(\n            Math.abs(s[p - 1]),\n            Math.abs(s[p - 2]),\n            Math.abs(e[p - 2]),\n            Math.abs(s[k]),\n            Math.abs(e[k]),\n          );\n          const sp = s[p - 1] / scale;\n          const spm1 = s[p - 2] / scale;\n          const epm1 = e[p - 2] / scale;\n          const sk = s[k] / scale;\n          const ek = e[k] / scale;\n          const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n          const c = sp * epm1 * (sp * epm1);\n          let shift = 0;\n          if (b !== 0 || c !== 0) {\n            if (b < 0) {\n              shift = 0 - Math.sqrt(b * b + c);\n            } else {\n              shift = Math.sqrt(b * b + c);\n            }\n            shift = c / (b + shift);\n          }\n          let f = (sk + sp) * (sk - sp) + shift;\n          let g = sk * ek;\n          for (let j = k; j < p - 1; j++) {\n            let t = hypotenuse(f, g);\n            if (t === 0) t = Number.MIN_VALUE;\n            let cs = f / t;\n            let sn = g / t;\n            if (j !== k) {\n              e[j - 1] = t;\n            }\n            f = cs * s[j] + sn * e[j];\n            e[j] = cs * e[j] - sn * s[j];\n            g = sn * s[j + 1];\n            s[j + 1] = cs * s[j + 1];\n            if (wantv) {\n              for (let i = 0; i < n; i++) {\n                t = cs * V.get(j, i) + sn * V.get(j + 1, i);\n                V.set(j + 1, i, -sn * V.get(j, i) + cs * V.get(j + 1, i));\n                V.set(j, i, t);\n              }\n            }\n            t = hypotenuse(f, g);\n            if (t === 0) t = Number.MIN_VALUE;\n            cs = f / t;\n            sn = g / t;\n            s[j] = t;\n            f = cs * e[j] + sn * s[j + 1];\n            s[j + 1] = -sn * e[j] + cs * s[j + 1];\n            g = sn * e[j + 1];\n            e[j + 1] = cs * e[j + 1];\n            if (wantu && j < m - 1) {\n              for (let i = 0; i < m; i++) {\n                t = cs * U.get(j, i) + sn * U.get(j + 1, i);\n                U.set(j + 1, i, -sn * U.get(j, i) + cs * U.get(j + 1, i));\n                U.set(j, i, t);\n              }\n            }\n          }\n          e[p - 2] = f;\n          break;\n        }\n        case 4: {\n          if (s[k] <= 0) {\n            s[k] = s[k] < 0 ? -s[k] : 0;\n            if (wantv) {\n              for (let i = 0; i <= pp; i++) {\n                V.set(k, i, -V.get(k, i));\n              }\n            }\n          }\n          while (k < pp) {\n            if (s[k] >= s[k + 1]) {\n              break;\n            }\n            let t = s[k];\n            s[k] = s[k + 1];\n            s[k + 1] = t;\n            if (wantv && k < n - 1) {\n              for (let i = 0; i < n; i++) {\n                t = V.get(k + 1, i);\n                V.set(k + 1, i, V.get(k, i));\n                V.set(k, i, t);\n              }\n            }\n            if (wantu && k < m - 1) {\n              for (let i = 0; i < m; i++) {\n                t = U.get(k + 1, i);\n                U.set(k + 1, i, U.get(k, i));\n                U.set(k, i, t);\n              }\n            }\n            k++;\n          }\n          p--;\n          break;\n        }\n        // no default\n      }\n    }\n\n    // Restore the logical (row-major) layout of the singular vectors, which were\n    // accumulated in transposed storage for cache-sequential inner loops. V is\n    // always square and U is square whenever the input is, so this is done in\n    // place (no allocation) in the common case.\n    U = U.isSquare() ? transposeSquareInPlace(U) : U.transpose();\n    V = transposeSquareInPlace(V);\n\n    if (swapped) {\n      let tmp = V;\n      V = U;\n      U = tmp;\n    }\n\n    this.m = m;\n    this.n = n;\n    this.s = s;\n    this.U = U;\n    this.V = V;\n  }\n\n  solve(value) {\n    let Y = value;\n    let e = this.threshold;\n    let scols = this.s.length;\n    let Ls = Matrix.zeros(scols, scols);\n\n    for (let i = 0; i < scols; i++) {\n      if (Math.abs(this.s[i]) <= e) {\n        Ls.set(i, i, 0);\n      } else {\n        Ls.set(i, i, 1 / this.s[i]);\n      }\n    }\n\n    let U = this.U;\n    let V = this.rightSingularVectors;\n\n    let VL = V.mmul(Ls);\n    let vrows = V.rows;\n    let urows = U.rows;\n    let VLU = Matrix.zeros(vrows, urows);\n\n    for (let i = 0; i < vrows; i++) {\n      for (let j = 0; j < urows; j++) {\n        let sum = 0;\n        for (let k = 0; k < scols; k++) {\n          sum += VL.get(i, k) * U.get(j, k);\n        }\n        VLU.set(i, j, sum);\n      }\n    }\n\n    return VLU.mmul(Y);\n  }\n\n  solveForDiagonal(value) {\n    return this.solve(Matrix.diag(value));\n  }\n\n  inverse() {\n    let V = this.V;\n    let e = this.threshold;\n    let vrows = V.rows;\n    let vcols = V.columns;\n    let X = new Matrix(vrows, this.s.length);\n\n    for (let i = 0; i < vrows; i++) {\n      for (let j = 0; j < vcols; j++) {\n        if (Math.abs(this.s[j]) > e) {\n          X.set(i, j, V.get(i, j) / this.s[j]);\n        }\n      }\n    }\n\n    let U = this.U;\n\n    let urows = U.rows;\n    let ucols = U.columns;\n    let Y = new Matrix(vrows, urows);\n\n    for (let i = 0; i < vrows; i++) {\n      for (let j = 0; j < urows; j++) {\n        let sum = 0;\n        for (let k = 0; k < ucols; k++) {\n          sum += X.get(i, k) * U.get(j, k);\n        }\n        Y.set(i, j, sum);\n      }\n    }\n\n    return Y;\n  }\n\n  get condition() {\n    return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n  }\n\n  get norm2() {\n    return this.s[0];\n  }\n\n  get rank() {\n    let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n    let r = 0;\n    let s = this.s;\n    for (let i = 0, ii = s.length; i < ii; i++) {\n      if (s[i] > tol) {\n        r++;\n      }\n    }\n    return r;\n  }\n\n  get diagonal() {\n    return Array.from(this.s);\n  }\n\n  get threshold() {\n    return (Number.EPSILON / 2) * Math.max(this.m, this.n) * this.s[0];\n  }\n\n  get leftSingularVectors() {\n    return this.U;\n  }\n\n  get rightSingularVectors() {\n    return this.V;\n  }\n\n  get diagonalMatrix() {\n    return Matrix.diag(this.s);\n  }\n}\n\nfunction inverse(matrix, useSVD = false) {\n  matrix = WrapperMatrix2D.checkMatrix(matrix);\n  if (useSVD) {\n    return new SingularValueDecomposition(matrix).inverse();\n  } else {\n    return solve(matrix, Matrix.eye(matrix.rows));\n  }\n}\n\nfunction solve(leftHandSide, rightHandSide, useSVD = false) {\n  leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);\n  rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);\n  if (useSVD) {\n    return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);\n  } else {\n    return leftHandSide.isSquare()\n      ? new LuDecomposition(leftHandSide).solve(rightHandSide)\n      : new QrDecomposition(leftHandSide).solve(rightHandSide);\n  }\n}\n\nfunction determinant(matrix) {\n  matrix = Matrix.checkMatrix(matrix);\n  if (matrix.isSquare()) {\n    if (matrix.columns === 0) {\n      return 1;\n    }\n\n    let a, b, c, d;\n    if (matrix.columns === 2) {\n      // 2 x 2 matrix\n      a = matrix.get(0, 0);\n      b = matrix.get(0, 1);\n      c = matrix.get(1, 0);\n      d = matrix.get(1, 1);\n\n      return a * d - b * c;\n    } else if (matrix.columns === 3) {\n      // 3 x 3 matrix\n      let subMatrix0, subMatrix1, subMatrix2;\n      subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);\n      subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);\n      subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);\n      a = matrix.get(0, 0);\n      b = matrix.get(0, 1);\n      c = matrix.get(0, 2);\n\n      return (\n        a * determinant(subMatrix0) -\n        b * determinant(subMatrix1) +\n        c * determinant(subMatrix2)\n      );\n    } else {\n      // general purpose determinant using the LU decomposition\n      return new LuDecomposition(matrix).determinant;\n    }\n  } else {\n    throw Error('determinant can only be calculated for a square matrix');\n  }\n}\n\nfunction xrange(n, exception) {\n  let range = [];\n  for (let i = 0; i < n; i++) {\n    if (i !== exception) {\n      range.push(i);\n    }\n  }\n  return range;\n}\n\nfunction dependenciesOneRow(\n  error,\n  matrix,\n  index,\n  thresholdValue = 10e-10,\n  thresholdError = 10e-10,\n) {\n  if (error > thresholdError) {\n    return new Array(matrix.rows + 1).fill(0);\n  } else {\n    let returnArray = matrix.addRow(index, [0]);\n    for (let i = 0; i < returnArray.rows; i++) {\n      if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {\n        returnArray.set(i, 0, 0);\n      }\n    }\n    return returnArray.to1DArray();\n  }\n}\n\nfunction linearDependencies(matrix, options = {}) {\n  const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n  matrix = Matrix.checkMatrix(matrix);\n\n  let n = matrix.rows;\n  let results = new Matrix(n, n);\n\n  for (let i = 0; i < n; i++) {\n    let b = Matrix.columnVector(matrix.getRow(i));\n    let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();\n    let svd = new SingularValueDecomposition(Abis);\n    let x = svd.solve(b);\n    let error = Matrix.sub(b, Abis.mmul(x)).abs().max();\n    results.setRow(\n      i,\n      dependenciesOneRow(error, x, i, thresholdValue, thresholdError),\n    );\n  }\n  return results;\n}\n\nfunction pseudoInverse(matrix, threshold = Number.EPSILON) {\n  matrix = Matrix.checkMatrix(matrix);\n  if (matrix.isEmpty()) {\n    // with a zero dimension, the pseudo-inverse is the transpose, since all 0xn and nx0 matrices are singular\n    // (0xn)*(nx0)*(0xn) = 0xn\n    // (nx0)*(0xn)*(nx0) = nx0\n    return matrix.transpose();\n  }\n  let svdSolution = new SingularValueDecomposition(matrix, { autoTranspose: true });\n\n  let U = svdSolution.leftSingularVectors;\n  let V = svdSolution.rightSingularVectors;\n  let s = svdSolution.diagonal;\n\n  for (let i = 0; i < s.length; i++) {\n    if (Math.abs(s[i]) > threshold) {\n      s[i] = 1.0 / s[i];\n    } else {\n      s[i] = 0.0;\n    }\n  }\n\n  return V.mmul(Matrix.diag(s).mmul(U.transpose()));\n}\n\nfunction covariance(xMatrix, yMatrix = xMatrix, options = {}) {\n  xMatrix = new Matrix(xMatrix);\n  let yIsSame = false;\n  if (\n    typeof yMatrix === 'object' &&\n    !Matrix.isMatrix(yMatrix) &&\n    !isAnyArray(yMatrix)\n  ) {\n    options = yMatrix;\n    yMatrix = xMatrix;\n    yIsSame = true;\n  } else {\n    yMatrix = new Matrix(yMatrix);\n  }\n  if (xMatrix.rows !== yMatrix.rows) {\n    throw new TypeError('Both matrices must have the same number of rows');\n  }\n  const { center = true } = options;\n  if (center) {\n    xMatrix = xMatrix.center('column');\n    if (!yIsSame) {\n      yMatrix = yMatrix.center('column');\n    }\n  }\n  const cov = xMatrix.transposeMultiply(yMatrix);\n  for (let i = 0; i < cov.rows; i++) {\n    for (let j = 0; j < cov.columns; j++) {\n      cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));\n    }\n  }\n  return cov;\n}\n\nfunction correlation(xMatrix, yMatrix = xMatrix, options = {}) {\n  xMatrix = new Matrix(xMatrix);\n  let yIsSame = false;\n  if (\n    typeof yMatrix === 'object' &&\n    !Matrix.isMatrix(yMatrix) &&\n    !isAnyArray(yMatrix)\n  ) {\n    options = yMatrix;\n    yMatrix = xMatrix;\n    yIsSame = true;\n  } else {\n    yMatrix = new Matrix(yMatrix);\n  }\n  if (xMatrix.rows !== yMatrix.rows) {\n    throw new TypeError('Both matrices must have the same number of rows');\n  }\n\n  const { center = true, scale = true } = options;\n  if (center) {\n    xMatrix.center('column');\n    if (!yIsSame) {\n      yMatrix.center('column');\n    }\n  }\n  if (scale) {\n    xMatrix.scale('column');\n    if (!yIsSame) {\n      yMatrix.scale('column');\n    }\n  }\n\n  const sdx = xMatrix.standardDeviation('column', { unbiased: true });\n  const sdy = yIsSame\n    ? sdx\n    : yMatrix.standardDeviation('column', { unbiased: true });\n\n  const corr = xMatrix.transposeMultiply(yMatrix);\n  for (let i = 0; i < corr.rows; i++) {\n    for (let j = 0; j < corr.columns; j++) {\n      corr.set(\n        i,\n        j,\n        corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),\n      );\n    }\n  }\n  return corr;\n}\n\nclass EigenvalueDecomposition {\n  constructor(matrix, options = {}) {\n    const { assumeSymmetric = false } = options;\n\n    matrix = WrapperMatrix2D.checkMatrix(matrix);\n    if (!matrix.isSquare()) {\n      throw new Error('Matrix is not a square matrix');\n    }\n\n    if (matrix.isEmpty()) {\n      throw new Error('Matrix must be non-empty');\n    }\n\n    let n = matrix.columns;\n    let V = new Matrix(n, n);\n    let d = new Float64Array(n);\n    let e = new Float64Array(n);\n    let value = matrix;\n    let i, j;\n\n    let isSymmetric = false;\n    if (assumeSymmetric) {\n      isSymmetric = true;\n    } else {\n      isSymmetric = matrix.isSymmetric();\n    }\n\n    if (isSymmetric) {\n      // tred2/tql2 access V almost exclusively down columns (the row index\n      // varies in the hot loops). Storing V transposed turns those into\n      // sequential row scans of the row-major backing store; we transpose it\n      // back to the logical layout before returning. V.get(j, i) holds the\n      // logical V(i, j).\n      for (i = 0; i < n; i++) {\n        for (j = 0; j < n; j++) {\n          V.set(j, i, value.get(i, j));\n        }\n      }\n      tred2(n, e, d, V);\n      tql2(n, e, d, V);\n      // V is square; restore the logical layout in place (no allocation).\n      transposeSquareInPlace(V);\n    } else {\n      // The non-symmetric path (orthes/hqr2) has two O(n^3) phases with opposite\n      // memory-layout preferences (the QR sweep favours column-major eigenvectors\n      // while the back-transform favours row-major), so a single transposed\n      // storage cannot help both. It is left in the original row-major layout.\n      let H = new Matrix(n, n);\n      let ort = new Float64Array(n);\n      for (j = 0; j < n; j++) {\n        for (i = 0; i < n; i++) {\n          H.set(i, j, value.get(i, j));\n        }\n      }\n      orthes(n, H, ort, V);\n      hqr2(n, e, d, V, H);\n    }\n\n    this.n = n;\n    this.e = e;\n    this.d = d;\n    this.V = V;\n  }\n\n  get realEigenvalues() {\n    return Array.from(this.d);\n  }\n\n  get imaginaryEigenvalues() {\n    return Array.from(this.e);\n  }\n\n  get eigenvectorMatrix() {\n    return this.V;\n  }\n\n  get diagonalMatrix() {\n    let n = this.n;\n    let e = this.e;\n    let d = this.d;\n    let X = new Matrix(n, n);\n    let i, j;\n    for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) {\n        X.set(i, j, 0);\n      }\n      X.set(i, i, d[i]);\n      if (e[i] > 0) {\n        X.set(i, i + 1, e[i]);\n      } else if (e[i] < 0) {\n        X.set(i, i - 1, e[i]);\n      }\n    }\n    return X;\n  }\n}\n\nfunction tred2(n, e, d, V) {\n  let f, g, h, i, j, k, hh, scale;\n\n  for (j = 0; j < n; j++) {\n    d[j] = V.get(j, n - 1);\n  }\n\n  for (i = n - 1; i > 0; i--) {\n    scale = 0;\n    h = 0;\n    for (k = 0; k < i; k++) {\n      scale = scale + Math.abs(d[k]);\n    }\n\n    if (scale === 0) {\n      e[i] = d[i - 1];\n      for (j = 0; j < i; j++) {\n        d[j] = V.get(j, i - 1);\n        V.set(j, i, 0);\n        V.set(i, j, 0);\n      }\n    } else {\n      for (k = 0; k < i; k++) {\n        d[k] /= scale;\n        h += d[k] * d[k];\n      }\n\n      f = d[i - 1];\n      g = Math.sqrt(h);\n      if (f > 0) {\n        g = -g;\n      }\n\n      e[i] = scale * g;\n      h = h - f * g;\n      d[i - 1] = f - g;\n      for (j = 0; j < i; j++) {\n        e[j] = 0;\n      }\n\n      for (j = 0; j < i; j++) {\n        f = d[j];\n        V.set(i, j, f);\n        g = e[j] + V.get(j, j) * f;\n        for (k = j + 1; k <= i - 1; k++) {\n          g += V.get(j, k) * d[k];\n          e[k] += V.get(j, k) * f;\n        }\n        e[j] = g;\n      }\n\n      f = 0;\n      for (j = 0; j < i; j++) {\n        e[j] /= h;\n        f += e[j] * d[j];\n      }\n\n      hh = f / (h + h);\n      for (j = 0; j < i; j++) {\n        e[j] -= hh * d[j];\n      }\n\n      for (j = 0; j < i; j++) {\n        f = d[j];\n        g = e[j];\n        for (k = j; k <= i - 1; k++) {\n          V.set(j, k, V.get(j, k) - (f * e[k] + g * d[k]));\n        }\n        d[j] = V.get(j, i - 1);\n        V.set(j, i, 0);\n      }\n    }\n    d[i] = h;\n  }\n\n  for (i = 0; i < n - 1; i++) {\n    V.set(i, n - 1, V.get(i, i));\n    V.set(i, i, 1);\n    h = d[i + 1];\n    if (h !== 0) {\n      for (k = 0; k <= i; k++) {\n        d[k] = V.get(i + 1, k) / h;\n      }\n\n      for (j = 0; j <= i; j++) {\n        g = 0;\n        for (k = 0; k <= i; k++) {\n          g += V.get(i + 1, k) * V.get(j, k);\n        }\n        for (k = 0; k <= i; k++) {\n          V.set(j, k, V.get(j, k) - g * d[k]);\n        }\n      }\n    }\n\n    for (k = 0; k <= i; k++) {\n      V.set(i + 1, k, 0);\n    }\n  }\n\n  for (j = 0; j < n; j++) {\n    d[j] = V.get(j, n - 1);\n    V.set(j, n - 1, 0);\n  }\n\n  V.set(n - 1, n - 1, 1);\n  e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n  let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2;\n\n  for (i = 1; i < n; i++) {\n    e[i - 1] = e[i];\n  }\n\n  e[n - 1] = 0;\n\n  let f = 0;\n  let tst1 = 0;\n  let eps = Number.EPSILON;\n\n  for (l = 0; l < n; l++) {\n    tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n    m = l;\n    while (m < n) {\n      if (Math.abs(e[m]) <= eps * tst1) {\n        break;\n      }\n      m++;\n    }\n\n    if (m > l) {\n      do {\n\n        g = d[l];\n        p = (d[l + 1] - g) / (2 * e[l]);\n        r = hypotenuse(p, 1);\n        if (p < 0) {\n          r = -r;\n        }\n\n        d[l] = e[l] / (p + r);\n        d[l + 1] = e[l] * (p + r);\n        dl1 = d[l + 1];\n        h = g - d[l];\n        for (i = l + 2; i < n; i++) {\n          d[i] -= h;\n        }\n\n        f = f + h;\n\n        p = d[m];\n        c = 1;\n        c2 = c;\n        c3 = c;\n        el1 = e[l + 1];\n        s = 0;\n        s2 = 0;\n        for (i = m - 1; i >= l; i--) {\n          c3 = c2;\n          c2 = c;\n          s2 = s;\n          g = c * e[i];\n          h = c * p;\n          r = hypotenuse(p, e[i]);\n          e[i + 1] = s * r;\n          s = e[i] / r;\n          c = p / r;\n          p = c * d[i] - s * g;\n          d[i + 1] = h + s * (c * g + s * d[i]);\n\n          for (k = 0; k < n; k++) {\n            h = V.get(i + 1, k);\n            V.set(i + 1, k, s * V.get(i, k) + c * h);\n            V.set(i, k, c * V.get(i, k) - s * h);\n          }\n        }\n\n        p = (-s * s2 * c3 * el1 * e[l]) / dl1;\n        e[l] = s * p;\n        d[l] = c * p;\n      } while (Math.abs(e[l]) > eps * tst1);\n    }\n    d[l] = d[l] + f;\n    e[l] = 0;\n  }\n\n  for (i = 0; i < n - 1; i++) {\n    k = i;\n    p = d[i];\n    for (j = i + 1; j < n; j++) {\n      if (d[j] < p) {\n        k = j;\n        p = d[j];\n      }\n    }\n\n    if (k !== i) {\n      d[k] = d[i];\n      d[i] = p;\n      for (j = 0; j < n; j++) {\n        p = V.get(i, j);\n        V.set(i, j, V.get(k, j));\n        V.set(k, j, p);\n      }\n    }\n  }\n}\n\nfunction orthes(n, H, ort, V) {\n  let low = 0;\n  let high = n - 1;\n  let f, g, h, i, j, m;\n  let scale;\n\n  for (m = low + 1; m <= high - 1; m++) {\n    scale = 0;\n    for (i = m; i <= high; i++) {\n      scale = scale + Math.abs(H.get(i, m - 1));\n    }\n\n    if (scale !== 0) {\n      h = 0;\n      for (i = high; i >= m; i--) {\n        ort[i] = H.get(i, m - 1) / scale;\n        h += ort[i] * ort[i];\n      }\n\n      g = Math.sqrt(h);\n      if (ort[m] > 0) {\n        g = -g;\n      }\n\n      h = h - ort[m] * g;\n      ort[m] = ort[m] - g;\n\n      for (j = m; j < n; j++) {\n        f = 0;\n        for (i = high; i >= m; i--) {\n          f += ort[i] * H.get(i, j);\n        }\n\n        f = f / h;\n        for (i = m; i <= high; i++) {\n          H.set(i, j, H.get(i, j) - f * ort[i]);\n        }\n      }\n\n      for (i = 0; i <= high; i++) {\n        f = 0;\n        for (j = high; j >= m; j--) {\n          f += ort[j] * H.get(i, j);\n        }\n\n        f = f / h;\n        for (j = m; j <= high; j++) {\n          H.set(i, j, H.get(i, j) - f * ort[j]);\n        }\n      }\n\n      ort[m] = scale * ort[m];\n      H.set(m, m - 1, scale * g);\n    }\n  }\n\n  for (i = 0; i < n; i++) {\n    for (j = 0; j < n; j++) {\n      V.set(i, j, i === j ? 1 : 0);\n    }\n  }\n\n  for (m = high - 1; m >= low + 1; m--) {\n    if (H.get(m, m - 1) !== 0) {\n      for (i = m + 1; i <= high; i++) {\n        ort[i] = H.get(i, m - 1);\n      }\n\n      for (j = m; j <= high; j++) {\n        g = 0;\n        for (i = m; i <= high; i++) {\n          g += ort[i] * V.get(i, j);\n        }\n\n        g = g / ort[m] / H.get(m, m - 1);\n        for (i = m; i <= high; i++) {\n          V.set(i, j, V.get(i, j) + g * ort[i]);\n        }\n      }\n    }\n  }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n  let n = nn - 1;\n  let low = 0;\n  let high = nn - 1;\n  let eps = Number.EPSILON;\n  let exshift = 0;\n  let norm = 0;\n  let p = 0;\n  let q = 0;\n  let r = 0;\n  let s = 0;\n  let z = 0;\n  let iter = 0;\n  let i, j, k, l, m, t, w, x, y;\n  let ra, sa, vr, vi;\n  let notlast, cdivres;\n\n  for (i = 0; i < nn; i++) {\n    if (i < low || i > high) {\n      d[i] = H.get(i, i);\n      e[i] = 0;\n    }\n\n    for (j = Math.max(i - 1, 0); j < nn; j++) {\n      norm = norm + Math.abs(H.get(i, j));\n    }\n  }\n\n  while (n >= low) {\n    l = n;\n    while (l > low) {\n      s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));\n      if (s === 0) {\n        s = norm;\n      }\n      if (Math.abs(H.get(l, l - 1)) < eps * s) {\n        break;\n      }\n      l--;\n    }\n\n    if (l === n) {\n      H.set(n, n, H.get(n, n) + exshift);\n      d[n] = H.get(n, n);\n      e[n] = 0;\n      n--;\n      iter = 0;\n    } else if (l === n - 1) {\n      w = H.get(n, n - 1) * H.get(n - 1, n);\n      p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;\n      q = p * p + w;\n      z = Math.sqrt(Math.abs(q));\n      H.set(n, n, H.get(n, n) + exshift);\n      H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);\n      x = H.get(n, n);\n\n      if (q >= 0) {\n        z = p >= 0 ? p + z : p - z;\n        d[n - 1] = x + z;\n        d[n] = d[n - 1];\n        if (z !== 0) {\n          d[n] = x - w / z;\n        }\n        e[n - 1] = 0;\n        e[n] = 0;\n        x = H.get(n, n - 1);\n        s = Math.abs(x) + Math.abs(z);\n        p = x / s;\n        q = z / s;\n        r = Math.sqrt(p * p + q * q);\n        p = p / r;\n        q = q / r;\n\n        for (j = n - 1; j < nn; j++) {\n          z = H.get(n - 1, j);\n          H.set(n - 1, j, q * z + p * H.get(n, j));\n          H.set(n, j, q * H.get(n, j) - p * z);\n        }\n\n        for (i = 0; i <= n; i++) {\n          z = H.get(i, n - 1);\n          H.set(i, n - 1, q * z + p * H.get(i, n));\n          H.set(i, n, q * H.get(i, n) - p * z);\n        }\n\n        for (i = low; i <= high; i++) {\n          z = V.get(i, n - 1);\n          V.set(i, n - 1, q * z + p * V.get(i, n));\n          V.set(i, n, q * V.get(i, n) - p * z);\n        }\n      } else {\n        d[n - 1] = x + p;\n        d[n] = x + p;\n        e[n - 1] = z;\n        e[n] = -z;\n      }\n\n      n = n - 2;\n      iter = 0;\n    } else {\n      x = H.get(n, n);\n      y = 0;\n      w = 0;\n      if (l < n) {\n        y = H.get(n - 1, n - 1);\n        w = H.get(n, n - 1) * H.get(n - 1, n);\n      }\n\n      if (iter === 10) {\n        exshift += x;\n        for (i = low; i <= n; i++) {\n          H.set(i, i, H.get(i, i) - x);\n        }\n        s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(n - 1, n - 2));\n        // eslint-disable-next-line no-multi-assign\n        x = y = 0.75 * s;\n        w = -0.4375 * s * s;\n      }\n\n      if (iter === 30) {\n        s = (y - x) / 2;\n        s = s * s + w;\n        if (s > 0) {\n          s = Math.sqrt(s);\n          if (y < x) {\n            s = -s;\n          }\n          s = x - w / ((y - x) / 2 + s);\n          for (i = low; i <= n; i++) {\n            H.set(i, i, H.get(i, i) - s);\n          }\n          exshift += s;\n          // eslint-disable-next-line no-multi-assign\n          x = y = w = 0.964;\n        }\n      }\n\n      iter = iter + 1;\n\n      m = n - 2;\n      while (m >= l) {\n        z = H.get(m, m);\n        r = x - z;\n        s = y - z;\n        p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);\n        q = H.get(m + 1, m + 1) - z - r - s;\n        r = H.get(m + 2, m + 1);\n        s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n        p = p / s;\n        q = q / s;\n        r = r / s;\n        if (m === l) {\n          break;\n        }\n        if (\n          Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) <\n          eps *\n            (Math.abs(p) *\n              (Math.abs(H.get(m - 1, m - 1)) +\n                Math.abs(z) +\n                Math.abs(H.get(m + 1, m + 1))))\n        ) {\n          break;\n        }\n        m--;\n      }\n\n      for (i = m + 2; i <= n; i++) {\n        H.set(i, i - 2, 0);\n        if (i > m + 2) {\n          H.set(i, i - 3, 0);\n        }\n      }\n\n      for (k = m; k <= n - 1; k++) {\n        notlast = k !== n - 1;\n        if (k !== m) {\n          p = H.get(k, k - 1);\n          q = H.get(k + 1, k - 1);\n          r = notlast ? H.get(k + 2, k - 1) : 0;\n          x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n          if (x !== 0) {\n            p = p / x;\n            q = q / x;\n            r = r / x;\n          }\n        }\n\n        if (x === 0) {\n          break;\n        }\n\n        s = Math.sqrt(p * p + q * q + r * r);\n        if (p < 0) {\n          s = -s;\n        }\n\n        if (s !== 0) {\n          if (k !== m) {\n            H.set(k, k - 1, -s * x);\n          } else if (l !== m) {\n            H.set(k, k - 1, -H.get(k, k - 1));\n          }\n\n          p = p + s;\n          x = p / s;\n          y = q / s;\n          z = r / s;\n          q = q / p;\n          r = r / p;\n\n          for (j = k; j < nn; j++) {\n            p = H.get(k, j) + q * H.get(k + 1, j);\n            if (notlast) {\n              p = p + r * H.get(k + 2, j);\n              H.set(k + 2, j, H.get(k + 2, j) - p * z);\n            }\n\n            H.set(k, j, H.get(k, j) - p * x);\n            H.set(k + 1, j, H.get(k + 1, j) - p * y);\n          }\n\n          for (i = 0; i <= Math.min(n, k + 3); i++) {\n            p = x * H.get(i, k) + y * H.get(i, k + 1);\n            if (notlast) {\n              p = p + z * H.get(i, k + 2);\n              H.set(i, k + 2, H.get(i, k + 2) - p * r);\n            }\n\n            H.set(i, k, H.get(i, k) - p);\n            H.set(i, k + 1, H.get(i, k + 1) - p * q);\n          }\n\n          for (i = low; i <= high; i++) {\n            p = x * V.get(i, k) + y * V.get(i, k + 1);\n            if (notlast) {\n              p = p + z * V.get(i, k + 2);\n              V.set(i, k + 2, V.get(i, k + 2) - p * r);\n            }\n\n            V.set(i, k, V.get(i, k) - p);\n            V.set(i, k + 1, V.get(i, k + 1) - p * q);\n          }\n        }\n      }\n    }\n  }\n\n  if (norm === 0) {\n    return;\n  }\n\n  for (n = nn - 1; n >= 0; n--) {\n    p = d[n];\n    q = e[n];\n\n    if (q === 0) {\n      l = n;\n      H.set(n, n, 1);\n      for (i = n - 1; i >= 0; i--) {\n        w = H.get(i, i) - p;\n        r = 0;\n        for (j = l; j <= n; j++) {\n          r = r + H.get(i, j) * H.get(j, n);\n        }\n\n        if (e[i] < 0) {\n          z = w;\n          s = r;\n        } else {\n          l = i;\n          if (e[i] === 0) {\n            H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));\n          } else {\n            x = H.get(i, i + 1);\n            y = H.get(i + 1, i);\n            q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n            t = (x * s - z * r) / q;\n            H.set(i, n, t);\n            H.set(\n              i + 1,\n              n,\n              Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z,\n            );\n          }\n\n          t = Math.abs(H.get(i, n));\n          if (eps * t * t > 1) {\n            for (j = i; j <= n; j++) {\n              H.set(j, n, H.get(j, n) / t);\n            }\n          }\n        }\n      }\n    } else if (q < 0) {\n      l = n - 1;\n\n      if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {\n        H.set(n - 1, n - 1, q / H.get(n, n - 1));\n        H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));\n      } else {\n        cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);\n        H.set(n - 1, n - 1, cdivres[0]);\n        H.set(n - 1, n, cdivres[1]);\n      }\n\n      H.set(n, n - 1, 0);\n      H.set(n, n, 1);\n      for (i = n - 2; i >= 0; i--) {\n        ra = 0;\n        sa = 0;\n        for (j = l; j <= n; j++) {\n          ra = ra + H.get(i, j) * H.get(j, n - 1);\n          sa = sa + H.get(i, j) * H.get(j, n);\n        }\n\n        w = H.get(i, i) - p;\n\n        if (e[i] < 0) {\n          z = w;\n          r = ra;\n          s = sa;\n        } else {\n          l = i;\n          if (e[i] === 0) {\n            cdivres = cdiv(-ra, -sa, w, q);\n            H.set(i, n - 1, cdivres[0]);\n            H.set(i, n, cdivres[1]);\n          } else {\n            x = H.get(i, i + 1);\n            y = H.get(i + 1, i);\n            vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n            vi = (d[i] - p) * 2 * q;\n            if (vr === 0 && vi === 0) {\n              vr =\n                eps *\n                norm *\n                (Math.abs(w) +\n                  Math.abs(q) +\n                  Math.abs(x) +\n                  Math.abs(y) +\n                  Math.abs(z));\n            }\n            cdivres = cdiv(\n              x * r - z * ra + q * sa,\n              x * s - z * sa - q * ra,\n              vr,\n              vi,\n            );\n            H.set(i, n - 1, cdivres[0]);\n            H.set(i, n, cdivres[1]);\n            if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n              H.set(\n                i + 1,\n                n - 1,\n                (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x,\n              );\n              H.set(\n                i + 1,\n                n,\n                (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x,\n              );\n            } else {\n              cdivres = cdiv(\n                -r - y * H.get(i, n - 1),\n                -s - y * H.get(i, n),\n                z,\n                q,\n              );\n              H.set(i + 1, n - 1, cdivres[0]);\n              H.set(i + 1, n, cdivres[1]);\n            }\n          }\n\n          t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));\n          if (eps * t * t > 1) {\n            for (j = i; j <= n; j++) {\n              H.set(j, n - 1, H.get(j, n - 1) / t);\n              H.set(j, n, H.get(j, n) / t);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  for (i = 0; i < nn; i++) {\n    if (i < low || i > high) {\n      for (j = i; j < nn; j++) {\n        V.set(i, j, H.get(i, j));\n      }\n    }\n  }\n\n  for (j = nn - 1; j >= low; j--) {\n    for (i = low; i <= high; i++) {\n      z = 0;\n      for (k = low; k <= Math.min(j, high); k++) {\n        z = z + V.get(i, k) * H.get(k, j);\n      }\n      V.set(i, j, z);\n    }\n  }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n  let r, d;\n  if (Math.abs(yr) > Math.abs(yi)) {\n    r = yi / yr;\n    d = yr + r * yi;\n    return [(xr + r * xi) / d, (xi - r * xr) / d];\n  } else {\n    r = yr / yi;\n    d = yi + r * yr;\n    return [(r * xr + xi) / d, (r * xi - xr) / d];\n  }\n}\n\nclass CholeskyDecomposition {\n  constructor(value) {\n    value = WrapperMatrix2D.checkMatrix(value);\n    if (!value.isSymmetric()) {\n      throw new Error('Matrix is not symmetric');\n    }\n\n    let a = value;\n    let dimension = a.rows;\n    let l = new Matrix(dimension, dimension);\n    let positiveDefinite = true;\n    let i, j, k;\n\n    for (j = 0; j < dimension; j++) {\n      let d = 0;\n      for (k = 0; k < j; k++) {\n        let s = 0;\n        for (i = 0; i < k; i++) {\n          s += l.get(k, i) * l.get(j, i);\n        }\n        s = (a.get(j, k) - s) / l.get(k, k);\n        l.set(j, k, s);\n        d = d + s * s;\n      }\n\n      d = a.get(j, j) - d;\n\n      positiveDefinite &&= d > 0;\n      l.set(j, j, Math.sqrt(Math.max(d, 0)));\n      for (k = j + 1; k < dimension; k++) {\n        l.set(j, k, 0);\n      }\n    }\n\n    this.L = l;\n    this.positiveDefinite = positiveDefinite;\n  }\n\n  isPositiveDefinite() {\n    return this.positiveDefinite;\n  }\n\n  solve(value) {\n    value = WrapperMatrix2D.checkMatrix(value);\n\n    let l = this.L;\n    let dimension = l.rows;\n\n    if (value.rows !== dimension) {\n      throw new Error('Matrix dimensions do not match');\n    }\n    if (this.isPositiveDefinite() === false) {\n      throw new Error('Matrix is not positive definite');\n    }\n\n    let count = value.columns;\n    let B = value.clone();\n    let i, j, k;\n\n    for (k = 0; k < dimension; k++) {\n      for (j = 0; j < count; j++) {\n        for (i = 0; i < k; i++) {\n          B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));\n        }\n        B.set(k, j, B.get(k, j) / l.get(k, k));\n      }\n    }\n\n    for (k = dimension - 1; k >= 0; k--) {\n      for (j = 0; j < count; j++) {\n        for (i = k + 1; i < dimension; i++) {\n          B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));\n        }\n        B.set(k, j, B.get(k, j) / l.get(k, k));\n      }\n    }\n\n    return B;\n  }\n\n  get lowerTriangularMatrix() {\n    return this.L;\n  }\n}\n\nclass nipals {\n  constructor(X, options = {}) {\n    X = WrapperMatrix2D.checkMatrix(X);\n    let { Y } = options;\n    const {\n      scaleScores = false,\n      maxIterations = 1000,\n      terminationCriteria = 1e-10,\n    } = options;\n\n    let u;\n    if (Y) {\n      if (isAnyArray(Y) && typeof Y[0] === 'number') {\n        Y = Matrix.columnVector(Y);\n      } else {\n        Y = WrapperMatrix2D.checkMatrix(Y);\n      }\n      if (Y.rows !== X.rows) {\n        throw new Error('Y should have the same number of rows as X');\n      }\n      u = Y.getColumnVector(0);\n    } else {\n      u = X.getColumnVector(0);\n    }\n\n    let diff = 1;\n    let t, q, w, tOld;\n\n    for (\n      let counter = 0;\n      counter < maxIterations && diff > terminationCriteria;\n      counter++\n    ) {\n      w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));\n      w = w.div(w.norm());\n\n      t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));\n\n      if (counter > 0) {\n        diff = t.clone().sub(tOld).pow(2).sum();\n      }\n      tOld = t.clone();\n\n      if (Y) {\n        q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n        q = q.div(q.norm());\n\n        u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));\n      } else {\n        u = t;\n      }\n    }\n\n    if (Y) {\n      let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n      p = p.div(p.norm());\n      let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));\n      let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n      let yResidual = Y.clone().sub(\n        t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()),\n      );\n\n      this.t = t;\n      this.p = p.transpose();\n      this.w = w.transpose();\n      this.q = q;\n      this.u = u;\n      this.s = t.transpose().mmul(t);\n      this.xResidual = xResidual;\n      this.yResidual = yResidual;\n      this.betas = residual;\n    } else {\n      this.w = w.transpose();\n      this.s = t.transpose().mmul(t).sqrt();\n      if (scaleScores) {\n        this.t = t.clone().div(this.s.get(0, 0));\n      } else {\n        this.t = t;\n      }\n      this.xResidual = X.sub(t.mmul(w.transpose()));\n    }\n  }\n}\n\nexports.AbstractMatrix = AbstractMatrix;\nexports.CHO = CholeskyDecomposition;\nexports.CholeskyDecomposition = CholeskyDecomposition;\nexports.DistanceMatrix = DistanceMatrix;\nexports.EVD = EigenvalueDecomposition;\nexports.EigenvalueDecomposition = EigenvalueDecomposition;\nexports.LU = LuDecomposition;\nexports.LuDecomposition = LuDecomposition;\nexports.Matrix = Matrix;\nexports.MatrixColumnSelectionView = MatrixColumnSelectionView;\nexports.MatrixColumnView = MatrixColumnView;\nexports.MatrixFlipColumnView = MatrixFlipColumnView;\nexports.MatrixFlipRowView = MatrixFlipRowView;\nexports.MatrixRowSelectionView = MatrixRowSelectionView;\nexports.MatrixRowView = MatrixRowView;\nexports.MatrixSelectionView = MatrixSelectionView;\nexports.MatrixSubView = MatrixSubView;\nexports.MatrixTransposeView = MatrixTransposeView;\nexports.NIPALS = nipals;\nexports.Nipals = nipals;\nexports.QR = QrDecomposition;\nexports.QrDecomposition = QrDecomposition;\nexports.SVD = SingularValueDecomposition;\nexports.SingularValueDecomposition = SingularValueDecomposition;\nexports.SymmetricMatrix = SymmetricMatrix;\nexports.WrapperMatrix1D = WrapperMatrix1D;\nexports.WrapperMatrix2D = WrapperMatrix2D;\nexports.correlation = correlation;\nexports.covariance = covariance;\nexports.default = Matrix;\nexports.determinant = determinant;\nexports.inverse = inverse;\nexports.linearDependencies = linearDependencies;\nexports.pseudoInverse = pseudoInverse;\nexports.solve = solve;\nexports.wrap = wrap;\n//# sourceMappingURL=matrix.js.map\n","import * as matrix from './matrix.js';\n\nexport const AbstractMatrix = matrix.AbstractMatrix;\nexport const CHO = matrix.CHO;\nexport const CholeskyDecomposition = matrix.CholeskyDecomposition;\nexport const DistanceMatrix = matrix.DistanceMatrix;\nexport const EVD = matrix.EVD;\nexport const EigenvalueDecomposition = matrix.EigenvalueDecomposition;\nexport const LU = matrix.LU;\nexport const LuDecomposition = matrix.LuDecomposition;\nexport const Matrix = matrix.Matrix;\nexport const MatrixColumnSelectionView = matrix.MatrixColumnSelectionView;\nexport const MatrixColumnView = matrix.MatrixColumnView;\nexport const MatrixFlipColumnView = matrix.MatrixFlipColumnView;\nexport const MatrixFlipRowView = matrix.MatrixFlipRowView;\nexport const MatrixRowSelectionView = matrix.MatrixRowSelectionView;\nexport const MatrixRowView = matrix.MatrixRowView;\nexport const MatrixSelectionView = matrix.MatrixSelectionView;\nexport const MatrixSubView = matrix.MatrixSubView;\nexport const MatrixTransposeView = matrix.MatrixTransposeView;\nexport const NIPALS = matrix.NIPALS;\nexport const Nipals = matrix.Nipals;\nexport const QR = matrix.QR;\nexport const QrDecomposition = matrix.QrDecomposition;\nexport const SVD = matrix.SVD;\nexport const SingularValueDecomposition = matrix.SingularValueDecomposition;\nexport const SymmetricMatrix = matrix.SymmetricMatrix;\nexport const WrapperMatrix1D = matrix.WrapperMatrix1D;\nexport const WrapperMatrix2D = matrix.WrapperMatrix2D;\nexport const correlation = matrix.correlation;\nexport const covariance = matrix.covariance;\nexport default matrix.default.Matrix ? matrix.default.Matrix : matrix.Matrix;\nexport const determinant = matrix.determinant;\nexport const inverse = matrix.inverse;\nexport const linearDependencies = matrix.linearDependencies;\nexport const pseudoInverse = matrix.pseudoInverse;\nexport const solve = matrix.solve;\nexport const wrap = matrix.wrap;\n","import { xCheck } from \"./xCheck.js\";\nimport { xGetFromToIndex } from \"./xGetFromToIndex.js\";\n/**\n * Computes the mean value of an array of values.\n * @param array - array of numbers\n * @param options - options\n */\nexport function xMean(array, options = {}) {\n    xCheck(array);\n    const { fromIndex, toIndex } = xGetFromToIndex(array, options);\n    let sumValue = array[fromIndex];\n    for (let i = fromIndex + 1; i <= toIndex; i++) {\n        sumValue += array[i];\n    }\n    return sumValue / (toIndex - fromIndex + 1);\n}\n//# sourceMappingURL=xMean.js.map","import { xCheck } from \"./xCheck.js\";\nimport { xGetFromToIndex } from \"./xGetFromToIndex.js\";\n/**\n * Computes the maximal value of an array of values\n * @param array - array of numbers\n * @param options - options\n */\nexport function xMaxValue(array, options = {}) {\n    xCheck(array);\n    const { fromIndex, toIndex } = xGetFromToIndex(array, options);\n    let maxValue = array[fromIndex];\n    for (let i = fromIndex + 1; i <= toIndex; i++) {\n        if (array[i] > maxValue) {\n            maxValue = array[i];\n        }\n    }\n    return maxValue;\n}\n//# sourceMappingURL=xMaxValue.js.map","import { xCheck } from \"./xCheck.js\";\nimport { xGetFromToIndex } from \"./xGetFromToIndex.js\";\n/**\n * Computes the minimal value of an array of values.\n * @param array - array of numbers\n * @param options - options\n */\nexport function xMinValue(array, options = {}) {\n    xCheck(array);\n    const { fromIndex, toIndex } = xGetFromToIndex(array, options);\n    let minValue = array[fromIndex];\n    for (let i = fromIndex + 1; i <= toIndex; i++) {\n        if (array[i] < minValue) {\n            minValue = array[i];\n        }\n    }\n    return minValue;\n}\n//# sourceMappingURL=xMinValue.js.map","/**\n * This function calculate the norm of a vector.\n * @example xNorm([3, 4]) -> 5\n * @param array - array\n * @returns - calculated norm\n */\nexport function xNorm(array) {\n    let result = 0;\n    for (const element of array) {\n        result += element ** 2;\n    }\n    return Math.sqrt(result);\n}\n//# sourceMappingURL=xNorm.js.map","/**\n * Asserts that value is truthy.\n * @param value - Value to check.\n * @param message - Optional error message to throw.\n */\nexport function assert(value, message) {\n    if (!value) {\n        throw new Error(message || 'unreachable');\n    }\n}\n//# sourceMappingURL=assert.js.map","import { xMean } from 'ml-spectra-processing';\nimport { assert } from \"./assert.js\";\n/**\n * Build an optimization layout mapping actual per-peak parameter slots\n * to optimizer variables. The layout describes slots, grouped/shared\n * variables, variable bounds/initials, and provides a helper to\n * materialize actual peak parameter values from a variable vector.\n * @param internalPeaks - normalized internal peaks with parameter indices\n * @param peaks - original peak objects (for per-peak optimize flags)\n * @param options - user `OptimizeOptions`, may contain `linkedParameters`\n * @param yScale - y normalization factor (used when converting offsets)\n * @returns an `OptimizationLayout` describing variables and slots\n */\nexport function buildOptimizationLayout(internalPeaks, peaks, options, yScale = 1) {\n    const slots = buildParameterSlots(internalPeaks, peaks, options);\n    const variables = buildOptimizationVariables(slots, options.linkedParameters, yScale);\n    const variableMin = new Float64Array(variables.length);\n    const variableMax = new Float64Array(variables.length);\n    const variableInit = new Float64Array(variables.length);\n    const variableGrad = new Float64Array(variables.length);\n    const freeIndices = [];\n    for (let i = 0; i < variables.length; i++) {\n        const variable = variables[i];\n        variableMin[i] = variable.min;\n        variableMax[i] = variable.max;\n        variableInit[i] = variable.init;\n        variableGrad[i] = variable.gradientDifference;\n        if (variable.optimize) {\n            freeIndices.push(i);\n        }\n    }\n    return {\n        slots,\n        variables,\n        freeIndices,\n        variableMin,\n        variableMax,\n        variableInit,\n        variableGrad,\n        variableToPeakValues(variableValues) {\n            const actualValues = new Array(slots.length);\n            for (let i = 0; i < variables.length; i++) {\n                const variableValue = variableValues[i];\n                const members = variables[i].members;\n                for (const member of members) {\n                    actualValues[member.actualIndex] =\n                        variableValue * member.factor + member.offset;\n                }\n            }\n            return actualValues;\n        },\n    };\n}\n/**\n * Builds concrete parameter slots for each peak parameter.\n * @param internalPeaks - normalized peaks containing parameter metadata\n * @param peaks - original peaks used to resolve optimize flags\n * @param options - optimization options with parameter settings\n * @returns flattened parameter slots across all peaks\n */\nfunction buildParameterSlots(internalPeaks, peaks, options) {\n    const slots = [];\n    for (let peakIndex = 0; peakIndex < internalPeaks.length; peakIndex++) {\n        const internalPeak = internalPeaks[peakIndex];\n        for (let i = 0; i < internalPeak.parameters.length; i++) {\n            const parameter = internalPeak.parameters[i];\n            slots.push({\n                actualIndex: internalPeak.fromIndex + i,\n                peakIndex,\n                peakId: internalPeak.id,\n                parameter,\n                init: internalPeak.propertiesValues.init[i],\n                min: internalPeak.propertiesValues.min[i],\n                max: internalPeak.propertiesValues.max[i],\n                gradientDifference: internalPeak.propertiesValues.gradientDifference[i],\n                optimize: getOptimizeFlag(peaks[peakIndex], parameter, options),\n            });\n        }\n    }\n    return slots;\n}\n/**\n * Builds optimization variables from concrete parameter slots.\n * @param slots - flattened per-peak parameter slots\n * @param linkedParameters - optional linked parameter groups\n * @param yScale - y normalization factor for y-offset conversion\n * @returns sorted optimization variables ready for the optimizer\n */\nfunction buildOptimizationVariables(slots, linkedParameters, yScale) {\n    const groupedActualIndices = new Set();\n    const variables = [];\n    const slotLookup = new Map();\n    const idToIndices = new Map();\n    for (const slot of slots) {\n        slotLookup.set(getSlotKey(slot.peakIndex, slot.parameter), slot);\n        if (slot.peakId) {\n            const indices = idToIndices.get(slot.peakId) ?? [];\n            if (!indices.includes(slot.peakIndex)) {\n                indices.push(slot.peakIndex);\n            }\n            idToIndices.set(slot.peakId, indices);\n        }\n    }\n    for (const linkedParameter of linkedParameters ?? []) {\n        variables.push(buildLinkedVariable(linkedParameter, slotLookup, groupedActualIndices, idToIndices, yScale));\n    }\n    for (const slot of slots) {\n        if (groupedActualIndices.has(slot.actualIndex)) {\n            continue;\n        }\n        variables.push({\n            sortKey: slot.actualIndex,\n            parameter: slot.parameter,\n            init: slot.init,\n            min: slot.min,\n            max: slot.max,\n            gradientDifference: slot.gradientDifference,\n            optimize: slot.optimize,\n            members: [\n                {\n                    actualIndex: slot.actualIndex,\n                    peakIndex: slot.peakIndex,\n                    parameter: slot.parameter,\n                    factor: 1,\n                    offset: 0,\n                },\n            ],\n        });\n    }\n    variables.sort((a, b) => a.sortKey - b.sortKey);\n    return variables.map(({ sortKey: _sortKey, ...variable }) => variable);\n}\nfunction buildLinkedVariable(linkedParameter, slotLookup, groupedActualIndices, idToIndices, yScale) {\n    if (linkedParameter.peaks.length === 0) {\n        throw new Error(`Linked parameter for ${linkedParameter.parameter} must contain at least one peak`);\n    }\n    const resolvedMembers = linkedParameter.peaks.map((peak) => {\n        const slot = resolveLinkedSlot(peak, linkedParameter.parameter, slotLookup, idToIndices);\n        if (groupedActualIndices.has(slot.actualIndex)) {\n            throw new Error(`Peak ${String(peak.id)} parameter ${linkedParameter.parameter} is already linked`);\n        }\n        return {\n            slot,\n            factor: getFactor(peak, linkedParameter.parameter),\n            offset: getOffset(peak, linkedParameter.parameter, yScale),\n        };\n    });\n    const memberActualIndices = new Set();\n    for (const member of resolvedMembers) {\n        if (memberActualIndices.has(member.slot.actualIndex)) {\n            throw new Error(`Linked parameter for ${linkedParameter.parameter} contains the same peak more than once`);\n        }\n        memberActualIndices.add(member.slot.actualIndex);\n    }\n    const firstMember = resolvedMembers[0];\n    let sharedMin = Number.NEGATIVE_INFINITY;\n    let sharedMax = Number.POSITIVE_INFINITY;\n    const optimize = firstMember.slot.optimize;\n    const sharedInitCandidates = [];\n    for (const member of resolvedMembers) {\n        if (member.slot.optimize !== optimize) {\n            throw new Error(`Linked parameter ${linkedParameter.parameter} must use a consistent optimize flag across all members`);\n        }\n        if (member.slot.min > member.slot.max) {\n            throw new Error(`Linked parameter ${linkedParameter.parameter} has incompatible bounds across its members`);\n        }\n        const variableBounds = getMemberVariableBounds(member);\n        sharedMin = Math.max(sharedMin, variableBounds.min);\n        sharedMax = Math.min(sharedMax, variableBounds.max);\n        sharedInitCandidates.push((member.slot.init - member.offset) / member.factor);\n    }\n    if (sharedMin > sharedMax) {\n        throw new Error(`Linked parameter ${linkedParameter.parameter} has incompatible bounds across its members`);\n    }\n    for (const member of resolvedMembers) {\n        groupedActualIndices.add(member.slot.actualIndex);\n    }\n    return {\n        sortKey: Math.min(...resolvedMembers.map((member) => member.slot.actualIndex)),\n        parameter: linkedParameter.parameter,\n        init: xMean(sharedInitCandidates),\n        min: sharedMin,\n        max: sharedMax,\n        gradientDifference: Math.min(...resolvedMembers.map((m) => Math.abs(m.slot.gradientDifference))),\n        optimize,\n        members: resolvedMembers.map((member) => ({\n            actualIndex: member.slot.actualIndex,\n            peakIndex: member.slot.peakIndex,\n            parameter: member.slot.parameter,\n            factor: member.factor,\n            offset: member.offset,\n        })),\n    };\n}\nfunction resolveLinkedSlot(peak, parameter, slotLookup, idToIndices) {\n    const peakIndex = typeof peak.id === 'number'\n        ? peak.id\n        : resolvePeakIndexById(peak.id, idToIndices);\n    if (!Number.isInteger(peakIndex) || peakIndex < 0) {\n        throw new Error(`Invalid peak reference ${String(peak.id)}`);\n    }\n    const slot = slotLookup.get(getSlotKey(peakIndex, parameter));\n    if (!slot) {\n        throw new Error(`Unknown parameter ${parameter} for peak ${String(peak.id)}`);\n    }\n    return slot;\n}\nfunction resolvePeakIndexById(peakId, idToIndices) {\n    const indices = idToIndices.get(peakId);\n    if (!indices || indices.length === 0) {\n        throw new Error(`Unknown peak id ${peakId}`);\n    }\n    if (new Set(indices).size > 1) {\n        throw new Error(`Peak id ${peakId} is ambiguous because it is used by multiple peaks`);\n    }\n    return indices[0];\n}\nfunction getFactor(peak, parameter) {\n    const factor = peak.factor ?? 1;\n    if (!Number.isFinite(factor) || factor === 0) {\n        throw new Error(`Linked parameter ${parameter} must use a non-zero finite factor`);\n    }\n    return factor;\n}\nfunction getOffset(peak, parameter, yScale) {\n    const offset = peak.offset ?? 0;\n    if (!Number.isFinite(offset)) {\n        throw new Error(`Linked parameter ${parameter} must use a finite offset`);\n    }\n    if (parameter === 'y') {\n        return offset / yScale;\n    }\n    return offset;\n}\nfunction getMemberVariableBounds(member) {\n    const transformedMin = (member.slot.min - member.offset) / member.factor;\n    const transformedMax = (member.slot.max - member.offset) / member.factor;\n    return {\n        min: Math.min(transformedMin, transformedMax),\n        max: Math.max(transformedMin, transformedMax),\n    };\n}\nfunction getOptimizeFlag(peak, parameter, options) {\n    assert(peak);\n    let optimizeFlag = true;\n    const perPeakParam = peak.parameters?.[parameter];\n    const globalParam = options.parameters?.[parameter];\n    if (perPeakParam?.optimize !== undefined) {\n        if (typeof perPeakParam.optimize === 'function') {\n            optimizeFlag = perPeakParam.optimize(peak);\n        }\n        else {\n            const { optimize = true } = perPeakParam;\n            optimizeFlag = optimize;\n        }\n    }\n    else if (globalParam?.optimize !== undefined) {\n        if (typeof globalParam.optimize === 'function') {\n            optimizeFlag = globalParam.optimize(peak);\n        }\n        else {\n            const { optimize = true } = globalParam;\n            optimizeFlag = optimize;\n        }\n    }\n    return optimizeFlag;\n}\nfunction getSlotKey(peakIndex, parameter) {\n    return `${peakIndex}:${parameter}`;\n}\n//# sourceMappingURL=buildOptimizationLayout.js.map","/**\n * Reconstruct user-facing peak objects from internal peaks and a full\n * actual-parameter vector.\n * @template T - original Peak type\n * @param internalPeaks - internal peaks produced by `getInternalPeaks`\n * @param actualValues - flattened actual parameter values (not normalized for Y)\n * @param yScale - normalization factor previously applied to Y values\n * @returns array of optimized peaks with reconstructed shapes and ids\n */\nexport function reconstructPeaks(internalPeaks, actualValues, yScale) {\n    const newPeaks = [];\n    for (const peak of internalPeaks) {\n        const { id, shape, parameters, fromIndex } = peak;\n        let newPeak = { x: 0, y: 0, shape };\n        if (id) {\n            newPeak = { ...newPeak, id };\n        }\n        newPeak.x = actualValues[fromIndex];\n        newPeak.y = actualValues[fromIndex + 1] * yScale;\n        for (let i = 2; i < parameters.length; i++) {\n            //@ts-expect-error should be fixed once\n            newPeak.shape[parameters[i]] = actualValues[fromIndex + i];\n        }\n        newPeaks.push(newPeak);\n    }\n    return newPeaks;\n}\n//# sourceMappingURL=reconstructPeaks.js.map","export const GAUSSIAN_EXP_FACTOR = -4 * Math.LN2;\n/**\n * A pseudo-Voigt is a gaussian plus a lorentzian. Beyond 3.74 fwhm from the\n * centre the gaussian part is down to 1.4e-17 — too small to change a shape of\n * height one — while the lorentzian part is still 1.8e-2 and fades much more\n * slowly. Past that distance the gaussian is skipped: the `Math.exp` it costs\n * cannot change the result, and most points of a wide window lie out there.\n *\n * The limit is stored squared, so the test is `(x / fwhm)² > 14`, which saves a\n * square root. The same value works for every mixing ratio `mu`, except `mu = 1`\n * where the shape is a pure gaussian: with no lorentzian part left, skipping\n * would return zero instead of a very small number, so that case is never\n * skipped.\n */\nexport const GAUSSIAN_CUTOFF = 14;\nexport const ROOT_PI_OVER_LN2 = Math.sqrt(Math.PI / Math.LN2);\nexport const ROOT_LN2 = Math.sqrt(Math.LN2);\nexport const ROOT_THREE = Math.sqrt(3);\nexport const ROOT_2LN2 = Math.sqrt(2 * Math.LN2);\nexport const ROOT_2LN2_MINUS_ONE = Math.sqrt(2 * Math.LN2) - 1;\n//# sourceMappingURL=constants.js.map","import { GAUSSIAN_EXP_FACTOR, ROOT_2LN2, ROOT_LN2, ROOT_PI_OVER_LN2, } from \"../../../util/constants.js\";\nimport erfinv from \"../../../util/erfinv.js\";\nexport class Gaussian {\n    kind = 'gaussian';\n    /**\n     * Full width at half maximum.\n     * @default 500\n     */\n    fwhm;\n    constructor(options = {}) {\n        const { fwhm = 500, sd } = options;\n        this.fwhm = sd ? gaussianWidthToFWHM(2 * sd) : fwhm;\n    }\n    fwhmToWidth(fwhm = this.fwhm) {\n        return gaussianFwhmToWidth(fwhm);\n    }\n    widthToFWHM(width) {\n        return gaussianWidthToFWHM(width);\n    }\n    fct(x) {\n        return gaussianFct(x, this.fwhm);\n    }\n    getArea(height = calculateGaussianHeight({ fwhm: this.fwhm })) {\n        return getGaussianArea({ fwhm: this.fwhm, height });\n    }\n    getFactor(area) {\n        return getGaussianFactor(area);\n    }\n    getData(options = {}) {\n        return getGaussianData(this, options);\n    }\n    calculateHeight(area = 1) {\n        return calculateGaussianHeight({ fwhm: this.fwhm, area });\n    }\n    getParameters() {\n        return ['fwhm'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return { kind: this.kind, fwhm: this.fwhm };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhm } = gaussianDerivative(x, this.fwhm);\n        return { fct, dx, parameters: [dFwhm] };\n    }\n}\n/**\n * Calculate the peak height for a given area and fwhm.\n * @param options - fwhm, area, and optional sd.\n * @returns the peak height.\n */\nexport function calculateGaussianHeight(options) {\n    const { area = 1, sd } = options;\n    let { fwhm = 500 } = options;\n    if (sd)\n        fwhm = gaussianWidthToFWHM(2 * sd);\n    return (2 * area) / ROOT_PI_OVER_LN2 / fwhm;\n}\n/**\n * Evaluate the gaussian function centered at x=0.\n * @param x - position at which to evaluate.\n * @param fwhm - full width at half maximum.\n * @returns the intensity at x.\n */\nexport function gaussianFct(x, fwhm) {\n    return Math.exp(GAUSSIAN_EXP_FACTOR * (x / fwhm) ** 2);\n}\n/**\n * Analytical value and partial derivatives of the gaussian function centered at x=0.\n * @param x - position at which to evaluate.\n * @param fwhm - full width at half maximum.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`) and `fwhm` (`dFwhm`).\n */\nexport function gaussianDerivative(x, fwhm) {\n    const fct = gaussianFct(x, fwhm);\n    const dx = ((2 * GAUSSIAN_EXP_FACTOR * x) / (fwhm * fwhm)) * fct;\n    const dFwhm = ((-2 * GAUSSIAN_EXP_FACTOR * x * x) / (fwhm * fwhm * fwhm)) * fct;\n    return { fct, dx, dFwhm };\n}\n/**\n * Convert inflection-point width to full width at half maximum.\n * @param width - width between inflection points.\n * @returns full width at half maximum.\n */\nexport function gaussianWidthToFWHM(width) {\n    return width * ROOT_2LN2;\n}\n/**\n * Convert full width at half maximum to inflection-point width.\n * @param fwhm - full width at half maximum.\n * @returns width between inflection points.\n */\nexport function gaussianFwhmToWidth(fwhm) {\n    return fwhm / ROOT_2LN2;\n}\n/**\n * Calculate the area under a gaussian peak.\n * @param options - fwhm, height, and optional sd.\n * @returns the area.\n */\nexport function getGaussianArea(options) {\n    const { sd, height = 1 } = options;\n    let { fwhm = 500 } = options;\n    if (sd)\n        fwhm = gaussianWidthToFWHM(2 * sd);\n    return (height * ROOT_PI_OVER_LN2 * fwhm) / 2;\n}\n/**\n * Calculate the width factor corresponding to a given area coverage fraction.\n * @param area - target area fraction (0–1). Defaults to `0.9999`.\n * @returns the factor by which to multiply fwhm to cover the given area.\n */\nexport function getGaussianFactor(area = 0.9999) {\n    if (area >= 1) {\n        throw new Error('area should be (0 - 1)');\n    }\n    return erfinv(area) / ROOT_LN2;\n}\n/**\n * Generate an intensity array for a gaussian shape.\n * @param shape - gaussian shape parameters (fwhm, sd).\n * @param options - sampling options (length, factor, height).\n * @returns Float64Array of intensity values.\n */\nexport function getGaussianData(shape = {}, options = {}) {\n    const { sd } = shape;\n    let { fwhm = 500 } = shape;\n    if (sd)\n        fwhm = gaussianWidthToFWHM(2 * sd);\n    const { factor = getGaussianFactor(), height = calculateGaussianHeight({ fwhm }), } = options;\n    let { length } = options;\n    if (!length) {\n        length = Math.min(Math.ceil(fwhm * factor), 2 ** 25 - 1);\n        if (length % 2 === 0)\n            length++;\n    }\n    const center = (length - 1) / 2;\n    const data = new Float64Array(length);\n    for (let i = 0; i <= center; i++) {\n        const value = gaussianFct(i - center, fwhm) * height;\n        data[i] = value;\n        data[length - 1 - i] = value;\n    }\n    return data;\n}\n//# sourceMappingURL=Gaussian.js.map","// https://en.wikipedia.org/wiki/Error_function#Inverse_functions\n// This code yields to a good approximation\n// If needed a better implementation using polynomial can be found on https://en.wikipedia.org/wiki/Error_function#Inverse_functions\n/**\n * Approximate inverse error function.\n * @param x - value in the range (-1, 1).\n * @returns erfinv(x).\n * @see https://en.wikipedia.org/wiki/Error_function#Inverse_functions\n */\nexport default function erfinv(x) {\n    const a = 0.147;\n    if (x === 0)\n        return 0;\n    const ln1MinusXSqrd = Math.log(1 - x * x);\n    const lnEtcBy2Plus2 = ln1MinusXSqrd / 2 + 2 / (Math.PI * a);\n    const firstSqrt = Math.sqrt(lnEtcBy2Plus2 ** 2 - ln1MinusXSqrd / a);\n    const secondSqrt = Math.sqrt(firstSqrt - lnEtcBy2Plus2);\n    return secondSqrt * (x > 0 ? 1 : -1);\n}\n//# sourceMappingURL=erfinv.js.map","import { ROOT_THREE } from \"../../../util/constants.js\";\nexport class Lorentzian {\n    kind = 'lorentzian';\n    /**\n     * Full width at half maximum.\n     * @default 500\n     */\n    fwhm;\n    constructor(options = {}) {\n        const { fwhm = 500 } = options;\n        this.fwhm = fwhm;\n    }\n    fwhmToWidth(fwhm = this.fwhm) {\n        return lorentzianFwhmToWidth(fwhm);\n    }\n    widthToFWHM(width) {\n        return lorentzianWidthToFWHM(width);\n    }\n    fct(x) {\n        return lorentzianFct(x, this.fwhm);\n    }\n    getArea(height = 1) {\n        return getLorentzianArea({ fwhm: this.fwhm, height });\n    }\n    getFactor(area) {\n        return getLorentzianFactor(area);\n    }\n    getData(options = {}) {\n        return getLorentzianData(this, options);\n    }\n    calculateHeight(area = 1) {\n        return calculateLorentzianHeight({ fwhm: this.fwhm, area });\n    }\n    getParameters() {\n        return ['fwhm'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return { kind: this.kind, fwhm: this.fwhm };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhm } = lorentzianDerivative(x, this.fwhm);\n        return { fct, dx, parameters: [dFwhm] };\n    }\n}\nexport const calculateLorentzianHeight = ({ fwhm = 1, area = 1 }) => {\n    return (2 * area) / Math.PI / fwhm;\n};\nexport const getLorentzianArea = (options) => {\n    const { fwhm = 500, height = 1 } = options;\n    return (height * Math.PI * fwhm) / 2;\n};\nexport const lorentzianFct = (x, fwhm) => {\n    return fwhm ** 2 / (4 * x ** 2 + fwhm ** 2);\n};\n/**\n * Analytical value and partial derivatives of the lorentzian function centered at x=0.\n * @param x - position at which to evaluate.\n * @param fwhm - full width at half maximum.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`) and `fwhm` (`dFwhm`).\n */\nexport function lorentzianDerivative(x, fwhm) {\n    const denominator = 4 * x * x + fwhm * fwhm;\n    const fct = (fwhm * fwhm) / denominator;\n    const dx = (-8 * x * fwhm * fwhm) / (denominator * denominator);\n    const dFwhm = (8 * fwhm * x * x) / (denominator * denominator);\n    return { fct, dx, dFwhm };\n}\nexport const lorentzianWidthToFWHM = (width) => {\n    return width * ROOT_THREE;\n};\nexport const lorentzianFwhmToWidth = (fwhm) => {\n    return fwhm / ROOT_THREE;\n};\nconst lorentzianQuantile = (p) => Math.tan(Math.PI * (p - 0.5));\nexport const getLorentzianFactor = (area = 0.9999) => {\n    if (area >= 1) {\n        throw new Error('area should be (0 - 1)');\n    }\n    const halfResidual = (1 - area) * 0.5;\n    return ((lorentzianQuantile(1 - halfResidual) - lorentzianQuantile(halfResidual)) /\n        2);\n};\nexport const getLorentzianData = (shape = {}, options = {}) => {\n    const { fwhm = 500 } = shape;\n    const { factor = getLorentzianFactor(), height = calculateLorentzianHeight({ fwhm, area: 1 }), } = options;\n    let { length } = options;\n    if (!length) {\n        length = Math.min(Math.ceil(fwhm * factor), 2 ** 25 - 1);\n        if (length % 2 === 0)\n            length++;\n    }\n    const center = (length - 1) / 2;\n    const data = new Float64Array(length);\n    for (let i = 0; i <= center; i++) {\n        const value = lorentzianFct(i - center, fwhm) * height;\n        data[i] = value;\n        data[length - 1 - i] = value;\n    }\n    return data;\n};\n//# sourceMappingURL=Lorentzian.js.map","import { calculateLorentzianHeight, getLorentzianFactor, lorentzianFwhmToWidth, lorentzianWidthToFWHM, } from \"../lorentzian/Lorentzian.js\";\nexport class LorentzianDispersive {\n    kind = 'lorentzianDispersive';\n    /**\n     * Full width at half maximum.\n     * @default 500\n     */\n    fwhm;\n    constructor(options = {}) {\n        const { fwhm = 500 } = options;\n        this.fwhm = fwhm;\n    }\n    fwhmToWidth(fwhm = this.fwhm) {\n        return lorentzianFwhmToWidth(fwhm);\n    }\n    widthToFWHM(width) {\n        return lorentzianWidthToFWHM(width);\n    }\n    fct(x) {\n        return lorentzianDispersiveFct(x, this.fwhm);\n    }\n    getArea() {\n        return 0;\n    }\n    getFactor(area) {\n        return getLorentzianFactor(area);\n    }\n    getData(options = {}) {\n        return getLorentzianDispersiveData(this, options);\n    }\n    calculateHeight(area = 1) {\n        return calculateLorentzianHeight({ fwhm: this.fwhm, area });\n    }\n    getParameters() {\n        return ['fwhm'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return { kind: this.kind, fwhm: this.fwhm };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhm } = lorentzianDispersiveDerivative(x, this.fwhm);\n        return { fct, dx, parameters: [dFwhm] };\n    }\n}\nexport const lorentzianDispersiveFct = (x, fwhm) => {\n    return (2 * fwhm * x) / (4 * x ** 2 + fwhm ** 2);\n};\n/**\n * Analytical value and partial derivatives of the dispersive lorentzian function centered at x=0.\n * @param x - position at which to evaluate.\n * @param fwhm - full width at half maximum.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`) and `fwhm` (`dFwhm`).\n */\nexport function lorentzianDispersiveDerivative(x, fwhm) {\n    const denominator = 4 * x * x + fwhm * fwhm;\n    const fct = (2 * fwhm * x) / denominator;\n    const dx = (2 * fwhm * (fwhm * fwhm - 4 * x * x)) / (denominator * denominator);\n    const dFwhm = (2 * x * (4 * x * x - fwhm * fwhm)) / (denominator * denominator);\n    return { fct, dx, dFwhm };\n}\nexport const getLorentzianDispersiveData = (shape = {}, options = {}) => {\n    const { fwhm = 500 } = shape;\n    const { factor = getLorentzianFactor(), height = calculateLorentzianHeight({ fwhm, area: 1 }), } = options;\n    let { length } = options;\n    if (!length) {\n        length = Math.min(Math.ceil(fwhm * factor), 2 ** 25 - 1);\n        if (length % 2 === 0)\n            length++;\n    }\n    const center = (length - 1) / 2;\n    const data = new Float64Array(length);\n    for (let i = 0; i <= center; i++) {\n        const value = lorentzianDispersiveFct(i - center, fwhm) * height;\n        data[i] = value;\n        data[length - 1 - i] = -value;\n    }\n    return data;\n};\n//# sourceMappingURL=LorentzianDispersive.js.map","import { getGaussianFactor } from \"../gaussian/Gaussian.js\";\nimport { getLorentzianFactor } from \"../lorentzian/Lorentzian.js\";\n/**\n * Find the k factor for a pseudo-Voigt distribution such that the\n * cumulative probability pPseudoVoigt(k, mu) equals `pTarget`.\n *\n * Uses a simple bisection search (with exponential bracketing) to\n * invert the pseudo-Voigt cumulative function. Special cases:\n * - mu === 1 -> reduces to the gaussian case\n * - mu === 0 -> reduces to the lorentzian case\n * @param pTarget - Target cumulative probability in (0,1)\n * @param mu - Gaussian fraction in [0,1]\n * @param tol - Convergence tolerance\n * @param maxIter - Maximum number of bisection iterations\n * @returns the factor k such that pPseudoVoigt(k, mu) ~= pTarget\n */\nexport function pseudoVoigtFindFactor(pTarget, mu, tol = 1e-9, maxIter = 200) {\n    if (pTarget <= 0 || pTarget >= 1) {\n        throw new RangeError('pTarget must be in (0,1)');\n    }\n    if (mu === 1) {\n        return getGaussianFactor(pTarget);\n    }\n    else if (mu === 0) {\n        return getLorentzianFactor(pTarget);\n    }\n    // bisection\n    let lo = 0;\n    let hi = 10;\n    let it = 0;\n    while (pPseudoVoigt(hi, mu) < pTarget && it++ < 200)\n        hi *= 2;\n    for (let i = 0; i < maxIter; i++) {\n        const mid = 0.5 * (lo + hi);\n        const val = pPseudoVoigt(mid, mu);\n        if (Math.abs(val - pTarget) < tol)\n            return mid;\n        if (val < pTarget) {\n            lo = mid;\n        }\n        else {\n            hi = mid;\n        }\n    }\n    return 0.5 * (lo + hi);\n}\nfunction erf(x) {\n    const sign = x < 0 ? -1 : 1;\n    x = Math.abs(x);\n    const a1 = 0.254829592;\n    const a2 = -0.284496736;\n    const a3 = 1.421413741;\n    const a4 = -1.453152027;\n    const a5 = 1.061405429;\n    const p = 0.3275911;\n    const t = 1 / (1 + p * x);\n    const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x);\n    return sign * y;\n}\nconst sqrtLn2 = Math.sqrt(Math.log(2));\nfunction pGaussian(k) {\n    return erf(k * sqrtLn2);\n}\nfunction pLorentz(k) {\n    return (2 / Math.PI) * Math.atan(k);\n}\nfunction pPseudoVoigt(k, mu) {\n    return (1 - mu) * pLorentz(k) + mu * pGaussian(k);\n}\n//# sourceMappingURL=computeFactor.js.map","import { GAUSSIAN_CUTOFF, GAUSSIAN_EXP_FACTOR, ROOT_2LN2_MINUS_ONE, ROOT_PI_OVER_LN2, } from \"../../../util/constants.js\";\nimport { gaussianFct } from \"../gaussian/Gaussian.js\";\nimport { lorentzianFct } from \"../lorentzian/Lorentzian.js\";\nimport { pseudoVoigtFindFactor } from \"./computeFactor.js\";\nexport class PseudoVoigt {\n    kind = 'pseudoVoigt';\n    fwhm;\n    /**\n     * Ratio of gaussian contribution in the shape\n     * @default 0.5\n     */\n    mu;\n    constructor(options = {}) {\n        const { fwhm = 500, mu = 0.5 } = options;\n        this.mu = mu;\n        this.fwhm = fwhm;\n    }\n    fwhmToWidth(fwhm = this.fwhm, mu = this.mu) {\n        return pseudoVoigtFwhmToWidth(fwhm, mu);\n    }\n    widthToFWHM(width, mu = this.mu) {\n        return pseudoVoigtWidthToFWHM(width, mu);\n    }\n    fct(x) {\n        return pseudoVoigtFct(x, this.fwhm, this.mu);\n    }\n    getArea(height = 1) {\n        return getPseudoVoigtArea({ fwhm: this.fwhm, height, mu: this.mu });\n    }\n    getFactor(area) {\n        return getPseudoVoigtFactor(area, this.mu);\n    }\n    getData(options = {}) {\n        const { length, factor, height = calculatePseudoVoigtHeight({\n            fwhm: this.fwhm,\n            mu: this.mu,\n            area: 1,\n        }), } = options;\n        return getPseudoVoigtData(this, { factor, length, height });\n    }\n    calculateHeight(area = 1) {\n        return calculatePseudoVoigtHeight({ fwhm: this.fwhm, mu: this.mu, area });\n    }\n    getParameters() {\n        return ['fwhm', 'mu'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return { kind: this.kind, fwhm: this.fwhm, mu: this.mu };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhm, dMu } = pseudoVoigtDerivative(x, this.fwhm, this.mu);\n        return { fct, dx, parameters: [dFwhm, dMu] };\n    }\n}\nexport const calculatePseudoVoigtHeight = (options = {}) => {\n    const { fwhm = 1, mu = 0.5, area = 1 } = options;\n    return (2 * area) / (fwhm * (mu * ROOT_PI_OVER_LN2 + (1 - mu) * Math.PI));\n};\nexport const pseudoVoigtFct = (x, fwhm, mu) => {\n    // at mu = 1 the shape *is* the gaussian: there is no lorentzian half left to\n    // carry the tail, so the gaussian is evaluated however far out it is asked for\n    if (mu === 1)\n        return gaussianFct(x, fwhm);\n    const lorentzian = (1 - mu) * lorentzianFct(x, fwhm);\n    const z = x / fwhm;\n    if (z * z > GAUSSIAN_CUTOFF)\n        return lorentzian;\n    return lorentzian + mu * gaussianFct(x, fwhm);\n};\n/**\n * Analytical value and partial derivatives of the pseudo-Voigt function centered at x=0.\n * @param x - position at which to evaluate.\n * @param fwhm - full width at half maximum.\n * @param mu - ratio of gaussian contribution in the shape.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`), `fwhm` (`dFwhm`) and `mu` (`dMu`).\n */\nexport function pseudoVoigtDerivative(x, fwhm, mu) {\n    // gaussian and lorentzian derivative math is inlined (rather than calling\n    // gaussianDerivative / lorentzianDerivative) to allocate a single object on\n    // this hot path; the sub-calls would allocate three.\n    //\n    // Past {@link GAUSSIAN_CUTOFF} the gaussian half has underflowed, so it is\n    // dropped here under the same condition as in `pseudoVoigtFct` — including its\n    // mu = 1 exemption, so the two stay consistent — which also settles what the\n    // derivatives are out there: `dx` and `dFwhm` keep only their lorentzian\n    // halves, and `dMu` becomes `-lorentz`, the value the shape loses by trading\n    // its lorentzian half for a gaussian one that contributes nothing.\n    const z = x / fwhm;\n    const e = mu !== 1 && z * z > GAUSSIAN_CUTOFF\n        ? 0\n        : Math.exp(GAUSSIAN_EXP_FACTOR * z * z);\n    const denominator = 4 * x * x + fwhm * fwhm;\n    const lorentz = (fwhm * fwhm) / denominator;\n    const dEdt = ((2 * GAUSSIAN_EXP_FACTOR * x) / (fwhm * fwhm)) * e;\n    const dLdt = (-8 * x * fwhm * fwhm) / (denominator * denominator);\n    const dEdfwhm = ((-2 * GAUSSIAN_EXP_FACTOR * x * x) / (fwhm * fwhm * fwhm)) * e;\n    const dLdfwhm = (8 * fwhm * x * x) / (denominator * denominator);\n    return {\n        fct: (1 - mu) * lorentz + mu * e,\n        dx: (1 - mu) * dLdt + mu * dEdt,\n        dFwhm: (1 - mu) * dLdfwhm + mu * dEdfwhm,\n        dMu: e - lorentz,\n    };\n}\nexport const pseudoVoigtWidthToFWHM = (width, mu = 0.5) => {\n    return width * (mu * ROOT_2LN2_MINUS_ONE + 1);\n};\nexport const pseudoVoigtFwhmToWidth = (fwhm, mu = 0.5) => {\n    return fwhm / (mu * ROOT_2LN2_MINUS_ONE + 1);\n};\nexport const getPseudoVoigtArea = (options) => {\n    const { fwhm = 500, height = 1, mu = 0.5 } = options;\n    return (fwhm * height * (mu * ROOT_PI_OVER_LN2 + (1 - mu) * Math.PI)) / 2;\n};\nexport const getPseudoVoigtFactor = (area = 0.9999, mu = 0.5) => {\n    return pseudoVoigtFindFactor(area, mu);\n};\nexport const getPseudoVoigtData = (shape = {}, options = {}) => {\n    const { fwhm = 500, mu = 0.5 } = shape;\n    const { factor = getPseudoVoigtFactor(0.999, mu) } = options;\n    let { length, height = calculatePseudoVoigtHeight({ fwhm, mu, area: 1 }) } = options;\n    if (!height) {\n        height =\n            1 /\n                ((mu / Math.sqrt(-GAUSSIAN_EXP_FACTOR / Math.PI)) * fwhm +\n                    ((1 - mu) * fwhm * Math.PI) / 2);\n    }\n    if (!length) {\n        length = Math.min(Math.ceil(fwhm * factor), 2 ** 25 - 1);\n        if (length % 2 === 0)\n            length++;\n    }\n    const center = (length - 1) / 2;\n    const data = new Float64Array(length);\n    for (let i = 0; i <= center; i++) {\n        const value = pseudoVoigtFct(i - center, fwhm, mu) * height;\n        data[i] = value;\n        data[length - 1 - i] = value;\n    }\n    return data;\n};\n//# sourceMappingURL=PseudoVoigt.js.map","import { GAUSSIAN_CUTOFF, GAUSSIAN_EXP_FACTOR, } from \"../../../util/constants.js\";\nimport { calculatePseudoVoigtHeight, getPseudoVoigtArea, getPseudoVoigtData, getPseudoVoigtFactor, pseudoVoigtFct, pseudoVoigtFwhmToWidth, pseudoVoigtWidthToFWHM, } from \"../pseudoVoigt/PseudoVoigt.js\";\n/**\n * TCH-style pseudo-Voigt where gaussian and lorentzian widths are independent.\n * The effective fwhm and mixing parameter mu are derived from fwhmG and fwhmL\n * via the Thompson–Cox–Hastings approximation.\n */\nexport class PseudoVoigtTCH {\n    kind = 'pseudoVoigtTCH';\n    _fwhmG;\n    _fwhmL;\n    _fwhm;\n    _mu;\n    _lorentzianWidthFraction;\n    constructor(options = {}) {\n        const { fwhmG, fwhmL, fwhm, mu = 0.5 } = options;\n        this._mu = mu;\n        this._fwhm = 0;\n        this._fwhmG = 0;\n        this._fwhmL = 0;\n        this._lorentzianWidthFraction = lorentzianWidthFraction(1 - mu);\n        if (fwhmG !== undefined && fwhmL !== undefined) {\n            this._fwhmG = fwhmG;\n            this.fwhmL = fwhmL;\n        }\n        else if (fwhm !== undefined) {\n            this.fwhm = fwhm;\n        }\n    }\n    set fwhmG(value) {\n        const effectiveFwhm = computeEffectiveWidth(value, this._fwhmL);\n        const lorentzianFraction = this._fwhmL / effectiveFwhm;\n        this._fwhm = effectiveFwhm;\n        this._mu =\n            1 -\n                (1.36603 * lorentzianFraction -\n                    0.47719 * lorentzianFraction * lorentzianFraction +\n                    0.11116 * lorentzianFraction * lorentzianFraction * lorentzianFraction);\n        this._fwhmG = value;\n        this._lorentzianWidthFraction = lorentzianFraction;\n    }\n    get fwhmG() {\n        return this._fwhmG;\n    }\n    set fwhmL(value) {\n        const effectiveFwhm = computeEffectiveWidth(this._fwhmG, value);\n        const lorentzianFraction = value / effectiveFwhm;\n        this._fwhm = effectiveFwhm;\n        this._mu =\n            1 -\n                (1.36603 * lorentzianFraction -\n                    0.47719 * lorentzianFraction * lorentzianFraction +\n                    0.11116 * lorentzianFraction * lorentzianFraction * lorentzianFraction);\n        this._fwhmL = value;\n        this._lorentzianWidthFraction = lorentzianFraction;\n    }\n    get fwhmL() {\n        return this._fwhmL;\n    }\n    set mu(value) {\n        const lorentzianFraction = lorentzianWidthFraction(1 - value);\n        this._lorentzianWidthFraction = lorentzianFraction;\n        this._fwhmL = this._fwhm * lorentzianFraction;\n        this._fwhmG = this._fwhm * gaussianWidthFraction(lorentzianFraction);\n        this._mu = value;\n    }\n    get mu() {\n        return this._mu;\n    }\n    set fwhm(value) {\n        const lorentzianFraction = this._lorentzianWidthFraction || lorentzianWidthFraction(1 - this._mu);\n        this._fwhmL = value * lorentzianFraction;\n        this._fwhmG = value * gaussianWidthFraction(lorentzianFraction);\n        this._fwhm = value;\n    }\n    get fwhm() {\n        return this._fwhm;\n    }\n    fwhmToWidth(fwhm = this._fwhm, mu = this._mu) {\n        return pseudoVoigtFwhmToWidth(fwhm, mu);\n    }\n    widthToFWHM(width, mu = this._mu) {\n        return pseudoVoigtWidthToFWHM(width, mu);\n    }\n    fct(x) {\n        return pseudoVoigtFct(x, this._fwhm, this._mu);\n    }\n    getArea(height = 1) {\n        return getPseudoVoigtArea({ fwhm: this._fwhm, height, mu: this._mu });\n    }\n    getFactor(area) {\n        return getPseudoVoigtFactor(area, this._mu);\n    }\n    getData(options = {}) {\n        const { length, factor, height = calculatePseudoVoigtHeight({\n            fwhm: this._fwhm,\n            mu: this._mu,\n            area: 1,\n        }), } = options;\n        return getPseudoVoigtData(this, { factor, length, height });\n    }\n    calculateHeight(area = 1) {\n        return calculatePseudoVoigtHeight({\n            fwhm: this._fwhm,\n            mu: this._mu,\n            area,\n        });\n    }\n    getParameters() {\n        return ['fwhmG', 'fwhmL'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * The component widths are emitted rather than `fwhm`/`mu`, because they are\n     * the state this shape is defined by: `getParameters` reports them and\n     * `derivative` differentiates with respect to them. The effective width and\n     * the mixing ratio are re-derived from them exactly.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return { kind: this.kind, fwhmG: this._fwhmG, fwhmL: this._fwhmL };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhmG, dFwhmL } = pseudoVoigtTCHDerivative(x, this._fwhmG, this._fwhmL);\n        return { fct, dx, parameters: [dFwhmG, dFwhmL] };\n    }\n}\n/**\n * Analytical value and partial derivatives of the TCH pseudo-Voigt function centered at x=0.\n * The effective fwhm `F` and mixing `mu` are functions of `fwhmG` and `fwhmL`, so the\n * derivatives chain `∂fct/∂F` and `∂fct/∂mu` through `∂F/∂·` and `∂mu/∂·`.\n * @param x - position at which to evaluate.\n * @param fwhmG - full width at half maximum of the gaussian component.\n * @param fwhmL - full width at half maximum of the lorentzian component.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`), `fwhmG` (`dFwhmG`) and `fwhmL` (`dFwhmL`).\n */\nexport function pseudoVoigtTCHDerivative(x, fwhmG, fwhmL) {\n    const effectiveFwhm = computeEffectiveWidth(fwhmG, fwhmL);\n    const w = effectiveFwhm ** 5; // the polynomial under the 1/5 power\n    // ∂w/∂fwhmG and ∂w/∂fwhmL (derivatives of the TCH width polynomial).\n    const dwDfwhmG = 5 * fwhmG ** 4 +\n        10.77076 * fwhmG ** 3 * fwhmL +\n        7.28529 * fwhmG ** 2 * fwhmL ** 2 +\n        8.94326 * fwhmG * fwhmL ** 3 +\n        0.07842 * fwhmL ** 4;\n    const dwDfwhmL = 2.69269 * fwhmG ** 4 +\n        4.85686 * fwhmG ** 3 * fwhmL +\n        13.41489 * fwhmG ** 2 * fwhmL ** 2 +\n        0.31368 * fwhmG * fwhmL ** 3 +\n        5 * fwhmL ** 4;\n    // F = w^0.2  =>  ∂F/∂· = 0.2 * F / w * ∂w/∂·\n    const dFwhmDfwhmG = (0.2 * effectiveFwhm * dwDfwhmG) / w;\n    const dFwhmDfwhmL = (0.2 * effectiveFwhm * dwDfwhmL) / w;\n    // lorentzian width fraction L = fwhmL / F\n    const lorentzianFraction = fwhmL / effectiveFwhm;\n    const dLorentzianFractionDfwhmG = (-fwhmL / (effectiveFwhm * effectiveFwhm)) * dFwhmDfwhmG;\n    const dLorentzianFractionDfwhmL = 1 / effectiveFwhm - (fwhmL / (effectiveFwhm * effectiveFwhm)) * dFwhmDfwhmL;\n    // mu = 1 - (1.36603 L - 0.47719 L^2 + 0.11116 L^3)\n    const dPolyDfraction = 1.36603 -\n        0.95438 * lorentzianFraction +\n        0.33348 * lorentzianFraction * lorentzianFraction;\n    const dMuDfwhmG = -dPolyDfraction * dLorentzianFractionDfwhmG;\n    const dMuDfwhmL = -dPolyDfraction * dLorentzianFractionDfwhmL;\n    const mu = 1 -\n        (1.36603 * lorentzianFraction -\n            0.47719 * lorentzianFraction * lorentzianFraction +\n            0.11116 * lorentzianFraction * lorentzianFraction * lorentzianFraction);\n    // pseudoVoigt value and its ∂/∂x, ∂/∂F (dFwhm), ∂/∂mu (dMu) at the effective\n    // fwhm, inlined to allocate a single object on this hot path.\n    //\n    // Past {@link GAUSSIAN_CUTOFF} the gaussian half has underflowed and is\n    // dropped under the same condition as in `pseudoVoigtFct` — which this shape's\n    // own `fct` delegates to, so the value and its derivatives stay consistent out\n    // there. `fwhmL = 0` gives `mu = 1`, the pure gaussian that is never dropped.\n    const z = x / effectiveFwhm;\n    const e = mu !== 1 && z * z > GAUSSIAN_CUTOFF\n        ? 0\n        : Math.exp(GAUSSIAN_EXP_FACTOR * z * z);\n    const denominator2 = 4 * x * x + effectiveFwhm * effectiveFwhm;\n    const lorentz = (effectiveFwhm * effectiveFwhm) / denominator2;\n    const dEdt = ((2 * GAUSSIAN_EXP_FACTOR * x) / (effectiveFwhm * effectiveFwhm)) * e;\n    const dLdt = (-8 * x * effectiveFwhm * effectiveFwhm) / (denominator2 * denominator2);\n    const dEdfwhm = ((-2 * GAUSSIAN_EXP_FACTOR * x * x) /\n        (effectiveFwhm * effectiveFwhm * effectiveFwhm)) *\n        e;\n    const dLdfwhm = (8 * effectiveFwhm * x * x) / (denominator2 * denominator2);\n    const dFwhm = (1 - mu) * dLdfwhm + mu * dEdfwhm;\n    const dMu = e - lorentz;\n    return {\n        fct: (1 - mu) * lorentz + mu * e,\n        dx: (1 - mu) * dLdt + mu * dEdt,\n        dFwhmG: dFwhm * dFwhmDfwhmG + dMu * dMuDfwhmG,\n        dFwhmL: dFwhm * dFwhmDfwhmL + dMu * dMuDfwhmL,\n    };\n}\n/**\n * Compute the effective FWHM from gaussian and lorentzian component widths\n * using the Thompson–Cox–Hastings approximation.\n * @param fwhmG - gaussian component FWHM.\n * @param fwhmL - lorentzian component FWHM.\n * @returns effective combined FWHM.\n */\nfunction computeEffectiveWidth(fwhmG, fwhmL) {\n    return ((fwhmG ** 5 +\n        2.69269 * fwhmG ** 4 * fwhmL +\n        2.42843 * fwhmG ** 3 * fwhmL ** 2 +\n        4.47163 * fwhmG ** 2 * fwhmL ** 3 +\n        0.07842 * fwhmG * fwhmL ** 4 +\n        fwhmL ** 5) **\n        0.2);\n}\n/**\n * Solve for the lorentzian width fraction fwhmL/fwhm given lorentzianFraction = 1 - mu,\n * using Newton's method on: 1.36603·x - 0.47719·x² + 0.11116·x³ = lorentzianFraction.\n * @param lorentzianFraction - TCH lorentzian mixing parameter (= 1 - mu).\n * @returns the lorentzian width fraction fwhmL/fwhm.\n */\nfunction lorentzianWidthFraction(lorentzianFraction) {\n    let fraction = lorentzianFraction;\n    for (let i = 0; i < 6; i++) {\n        const f = 1.36603 * fraction -\n            0.47719 * fraction * fraction +\n            0.11116 * fraction * fraction * fraction -\n            lorentzianFraction;\n        const df = 1.36603 - 2 * 0.47719 * fraction + 3 * 0.11116 * fraction * fraction;\n        fraction -= f / df;\n    }\n    return fraction;\n}\n/**\n * Solve for the gaussian width fraction fwhmG/fwhm that pairs with a given\n * lorentzian width fraction fwhmL/fwhm. Writing fwhmG = g·fwhm and\n * fwhmL = q·fwhm in {@link computeEffectiveWidth} makes fwhm cancel, so `g` is\n * the root of the TCH width polynomial evaluated at 1. Solving it — rather than\n * taking `1 - q` — is what keeps `computeEffectiveWidth(fwhmG, fwhmL)` equal to\n * `fwhm`, and therefore keeps `fct` and `derivative` describing one same curve.\n * @param lorentzianFraction - the lorentzian width fraction fwhmL/fwhm.\n * @returns the gaussian width fraction fwhmG/fwhm.\n */\nfunction gaussianWidthFraction(lorentzianFraction) {\n    const q = lorentzianFraction;\n    let g = 1 - q;\n    for (let i = 0; i < 8; i++) {\n        const f = g ** 5 +\n            2.69269 * g ** 4 * q +\n            2.42843 * g ** 3 * q ** 2 +\n            4.47163 * g ** 2 * q ** 3 +\n            0.07842 * g * q ** 4 +\n            q ** 5 -\n            1;\n        const df = 5 * g ** 4 +\n            10.77076 * g ** 3 * q +\n            7.28529 * g ** 2 * q ** 2 +\n            8.94326 * g * q ** 3 +\n            0.07842 * q ** 4;\n        if (df === 0)\n            break;\n        g -= f / df;\n    }\n    return g;\n}\n//# sourceMappingURL=PseudoVoigtTCH.js.map","import { ROOT_THREE } from \"../../../util/constants.js\";\n/**\n * This shape is a linear combination of rational function (n|n+2), for n = 0 (lorentzian function) and n = 2\n * the parameter that combines those two functions is `gamma` and it is called the kurtosis parameter, it is an\n * implementation of generalized lorentzian shape published by Stanislav Sykora in the SMASH 2010. DOI:10.3247/SL3nmr10.006\n * {@link https://www.ebyte.it/stan/Talk_ML_UserMeeting_SMASH_2010_GeneralizedLorentzian.html}\n */\nexport class GeneralizedLorentzian {\n    kind = 'generalizedLorentzian';\n    /**\n     * Full width at half maximum.\n     * @default 500\n     */\n    fwhm;\n    /**\n     * kurtosis parameter of the shape, between -1 to 2\n     * @default 1\n     */\n    gamma;\n    constructor(options = {}) {\n        const { fwhm = 500, gamma = 0.5 } = options;\n        this.fwhm = fwhm;\n        this.gamma = gamma;\n    }\n    fwhmToWidth(fwhm = this.fwhm) {\n        return generalizedLorentzianFwhmToWidth(fwhm);\n    }\n    widthToFWHM(width) {\n        return generalizedLorentzianWidthToFWHM(width);\n    }\n    fct(x) {\n        return generalizedLorentzianFct(x, this.fwhm, this.gamma);\n    }\n    getArea(height = 1) {\n        return getGeneralizedLorentzianArea({\n            fwhm: this.fwhm,\n            height,\n            gamma: this.gamma,\n        });\n    }\n    getFactor(area) {\n        return getGeneralizedLorentzianFactor(area);\n    }\n    getData(options = {}) {\n        return getGeneralizedLorentzianData(this, options);\n    }\n    calculateHeight(area = 1) {\n        const { gamma, fwhm } = this;\n        return calculateGeneralizedLorentzianHeight({ fwhm, area, gamma });\n    }\n    getParameters() {\n        return ['fwhm', 'gamma'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return { kind: this.kind, fwhm: this.fwhm, gamma: this.gamma };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhm, dGamma } = generalizedLorentzianDerivative(x, this.fwhm, this.gamma);\n        return { fct, dx, parameters: [dFwhm, dGamma] };\n    }\n}\nexport const calculateGeneralizedLorentzianHeight = ({ fwhm = 1, gamma = 1, area = 1, }) => {\n    return (area / fwhm / (3.14159 - 0.420894 * gamma)) * 2;\n};\n/**\n * Calculate the area under a generalized Lorentzian peak (integral from Mathematica).\n * @param options - shape parameters including fwhm, height, and gamma.\n * @returns the area under the peak.\n */\nexport const getGeneralizedLorentzianArea = (options) => {\n    const { fwhm = 500, height = 1, gamma = 1 } = options;\n    return (height * fwhm * (3.14159 - 0.420894 * gamma)) / 2;\n};\nexport const generalizedLorentzianFct = (x, fwhm, gamma) => {\n    const u = ((2 * x) / fwhm) ** 2;\n    return (1 - gamma) / (1 + u) + (gamma * (1 + u / 2)) / (1 + u + u ** 2);\n};\n/**\n * Analytical value and partial derivatives of the generalized lorentzian function centered at x=0.\n * @param x - position at which to evaluate.\n * @param fwhm - full width at half maximum.\n * @param gamma - kurtosis parameter of the shape.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`), `fwhm` (`dFwhm`) and `gamma` (`dGamma`).\n */\nexport function generalizedLorentzianDerivative(x, fwhm, gamma) {\n    const u = ((2 * x) / fwhm) ** 2;\n    const lorentzian = 1 / (1 + u); // A\n    const rational = (1 + u / 2) / (1 + u + u * u); // B\n    const fct = (1 - gamma) * lorentzian + gamma * rational;\n    // dA/du and dB/du\n    const dLorentzianDu = -1 / ((1 + u) * (1 + u));\n    const denominator = 1 + u + u * u;\n    const dRationalDu = -(0.5 + 2 * u + 0.5 * u * u) / (denominator * denominator);\n    const dFctDu = (1 - gamma) * dLorentzianDu + gamma * dRationalDu;\n    const duDx = (8 * x) / (fwhm * fwhm);\n    const duDfwhm = (-8 * x * x) / (fwhm * fwhm * fwhm);\n    const dx = dFctDu * duDx;\n    const dFwhm = dFctDu * duDfwhm;\n    const dGamma = rational - lorentzian; // B - A\n    return { fct, dx, dFwhm, dGamma };\n}\nexport const generalizedLorentzianWidthToFWHM = (width) => {\n    return width * ROOT_THREE;\n};\nexport const generalizedLorentzianFwhmToWidth = (fwhm) => {\n    return fwhm / ROOT_THREE;\n};\nconst generalizedLorentzianQuantile = (p) => Math.tan(Math.PI * (p - 0.5));\nexport const getGeneralizedLorentzianFactor = (area = 0.9999) => {\n    if (area >= 1) {\n        throw new Error('area should be (0 - 1)');\n    }\n    const halfResidual = (1 - area) * 0.5;\n    return ((generalizedLorentzianQuantile(1 - halfResidual) -\n        generalizedLorentzianQuantile(halfResidual)) /\n        2);\n};\nexport const getGeneralizedLorentzianData = (shape = {}, options = {}) => {\n    const { fwhm = 500, gamma = 1 } = shape;\n    const { factor = getGeneralizedLorentzianFactor(), height = calculateGeneralizedLorentzianHeight({ fwhm, area: 1, gamma }), } = options;\n    let { length } = options;\n    if (!length) {\n        length = Math.min(Math.ceil(fwhm * factor), 2 ** 25 - 1);\n        if (length % 2 === 0)\n            length++;\n    }\n    const center = (length - 1) / 2;\n    const data = new Float64Array(length);\n    for (let i = 0; i <= center; i++) {\n        const value = generalizedLorentzianFct(i - center, fwhm, gamma) * height;\n        data[i] = value;\n        data[length - 1 - i] = value;\n    }\n    return data;\n};\n//# sourceMappingURL=GeneralizedLorentzian.js.map","import { ROOT_PI_OVER_LN2 } from \"../../../util/constants.js\";\nimport { gaussianDerivative, gaussianFct, gaussianFwhmToWidth, gaussianWidthToFWHM, getGaussianFactor, } from \"../gaussian/Gaussian.js\";\nexport class SplitGaussian {\n    kind = 'splitGaussian';\n    /**\n     * Full width at half maximum of the lower-x half (x <= 0).\n     * @default 500\n     */\n    fwhmLow;\n    /**\n     * Full width at half maximum of the higher-x half (x > 0).\n     * @default 500\n     */\n    fwhmHigh;\n    constructor(options = {}) {\n        const { fwhmLow = 500, fwhmHigh = 500 } = options;\n        this.fwhmLow = fwhmLow;\n        this.fwhmHigh = fwhmHigh;\n    }\n    /**\n     * Full width at half maximum of the peak. The half-maximum crossings are at\n     * `-fwhmLow / 2` and `fwhmHigh / 2`, so the width between them is the mean of\n     * both halves.\n     * @returns the full width at half maximum.\n     */\n    get fwhm() {\n        return (this.fwhmLow + this.fwhmHigh) / 2;\n    }\n    /**\n     * Set the full width at half maximum. Both halves are scaled by the same\n     * ratio, so their mean becomes `value` while the asymmetry between them is\n     * preserved. A peak with no width has no ratio to preserve, so both halves\n     * take `value` and the peak stays symmetric.\n     * @param value - the new full width at half maximum.\n     */\n    set fwhm(value) {\n        const { fwhm } = this;\n        if (fwhm === 0) {\n            this.fwhmLow = value;\n            this.fwhmHigh = value;\n            return;\n        }\n        const ratio = value / fwhm;\n        this.fwhmLow *= ratio;\n        this.fwhmHigh *= ratio;\n    }\n    /**\n     * Convert a full width at half maximum to the width between the inflection\n     * points. For this peak's own fwhm the result is exactly `σlow + σhigh`.\n     * @param fwhm - full width at half maximum. Defaults to the peak's fwhm.\n     * @returns the width between the inflection points.\n     */\n    fwhmToWidth(fwhm = this.fwhm) {\n        return gaussianFwhmToWidth(fwhm);\n    }\n    /**\n     * Convert a width between the inflection points back to a full width at half\n     * maximum. A single width does not encode the asymmetry, so it cannot recover\n     * `fwhmLow` and `fwhmHigh` individually.\n     * @param width - width between the inflection points.\n     * @returns the corresponding full width at half maximum.\n     */\n    widthToFWHM(width) {\n        return gaussianWidthToFWHM(width);\n    }\n    fct(x) {\n        return splitGaussianFct(x, this.fwhmLow, this.fwhmHigh);\n    }\n    getArea(height = calculateSplitGaussianHeight({\n        fwhmLow: this.fwhmLow,\n        fwhmHigh: this.fwhmHigh,\n    })) {\n        return getSplitGaussianArea({\n            fwhmLow: this.fwhmLow,\n            fwhmHigh: this.fwhmHigh,\n            height,\n        });\n    }\n    getFactor(area) {\n        return getGaussianFactor(area);\n    }\n    getData(options = {}) {\n        return getSplitGaussianData(this, options);\n    }\n    calculateHeight(area = 1) {\n        return calculateSplitGaussianHeight({\n            fwhmLow: this.fwhmLow,\n            fwhmHigh: this.fwhmHigh,\n            area,\n        });\n    }\n    getParameters() {\n        return ['fwhmLow', 'fwhmHigh'];\n    }\n    /**\n     * Descriptor of this shape, so `JSON.stringify` round-trips through `getShape1D`.\n     * @returns the shape descriptor.\n     */\n    toJSON() {\n        return {\n            kind: this.kind,\n            fwhmLow: this.fwhmLow,\n            fwhmHigh: this.fwhmHigh,\n        };\n    }\n    derivative(x) {\n        const { fct, dx, dFwhmLow, dFwhmHigh } = splitGaussianDerivative(x, this.fwhmLow, this.fwhmHigh);\n        return { fct, dx, parameters: [dFwhmLow, dFwhmHigh] };\n    }\n}\n/**\n * Calculate the peak height for a given area and both half-widths.\n * @param options - fwhmLow, fwhmHigh and area.\n * @returns the peak height.\n */\nexport function calculateSplitGaussianHeight(options) {\n    const { fwhmLow = 500, fwhmHigh = 500, area = 1 } = options;\n    return (4 * area) / ROOT_PI_OVER_LN2 / (fwhmLow + fwhmHigh);\n}\n/**\n * Evaluate the split (asymmetric) gaussian function centered at x=0.\n * The lower-x half (x <= 0) uses `fwhmLow`, the higher-x half (x > 0) uses `fwhmHigh`.\n * @param x - position at which to evaluate.\n * @param fwhmLow - full width at half maximum of the lower-x half.\n * @param fwhmHigh - full width at half maximum of the higher-x half.\n * @returns the intensity at x.\n */\nexport function splitGaussianFct(x, fwhmLow, fwhmHigh) {\n    return x <= 0 ? gaussianFct(x, fwhmLow) : gaussianFct(x, fwhmHigh);\n}\n/**\n * Analytical value and partial derivatives of the split gaussian function centered at x=0.\n * Each half's fwhm only affects its own side, so the off-side derivative is 0.\n * @param x - position at which to evaluate.\n * @param fwhmLow - full width at half maximum of the lower-x half.\n * @param fwhmHigh - full width at half maximum of the higher-x half.\n * @returns the value `fct` and its partial derivatives with respect to `x` (`dx`), `fwhmLow` (`dFwhmLow`) and `fwhmHigh` (`dFwhmHigh`).\n */\nexport function splitGaussianDerivative(x, fwhmLow, fwhmHigh) {\n    if (x <= 0) {\n        const { fct, dx, dFwhm } = gaussianDerivative(x, fwhmLow);\n        return { fct, dx, dFwhmLow: dFwhm, dFwhmHigh: 0 };\n    }\n    const { fct, dx, dFwhm } = gaussianDerivative(x, fwhmHigh);\n    return { fct, dx, dFwhmLow: 0, dFwhmHigh: dFwhm };\n}\n/**\n * Calculate the area under a split gaussian peak.\n * @param options - fwhmLow, fwhmHigh and height.\n * @returns the area.\n */\nexport function getSplitGaussianArea(options) {\n    const { fwhmLow = 500, fwhmHigh = 500, height = 1 } = options;\n    return (height * ROOT_PI_OVER_LN2 * (fwhmLow + fwhmHigh)) / 4;\n}\n/**\n * Generate an intensity array for a split gaussian shape.\n * @param shape - split gaussian shape parameters (fwhmLow, fwhmHigh).\n * @param options - sampling options (length, factor, height).\n * @returns Float64Array of intensity values.\n */\nexport function getSplitGaussianData(shape = {}, options = {}) {\n    const { fwhmLow = 500, fwhmHigh = 500 } = shape;\n    const { factor = getGaussianFactor(), height = calculateSplitGaussianHeight({ fwhmLow, fwhmHigh }), } = options;\n    let { length } = options;\n    if (!length) {\n        length = Math.min(Math.ceil(Math.max(fwhmLow, fwhmHigh) * factor), 2 ** 25 - 1);\n        if (length % 2 === 0)\n            length++;\n    }\n    const center = (length - 1) / 2;\n    const data = new Float64Array(length);\n    for (let i = 0; i < length; i++) {\n        data[i] = splitGaussianFct(i - center, fwhmLow, fwhmHigh) * height;\n    }\n    return data;\n}\n//# sourceMappingURL=SplitGaussian.js.map","import { Gaussian } from \"./gaussian/Gaussian.js\";\nimport { GeneralizedLorentzian } from \"./generalizedLorentzian/GeneralizedLorentzian.js\";\nimport { Lorentzian } from \"./lorentzian/Lorentzian.js\";\nimport { LorentzianDispersive } from \"./lorentzianDispersive/LorentzianDispersive.js\";\nimport { PseudoVoigt } from \"./pseudoVoigt/PseudoVoigt.js\";\nimport { PseudoVoigtTCH } from \"./pseudoVoigtTCH/PseudoVoigtTCH.js\";\nimport { SplitGaussian } from \"./splitGaussian/SplitGaussian.js\";\nexport function getShape1D(shape) {\n    const { kind } = shape;\n    switch (kind) {\n        case 'gaussian':\n            return new Gaussian(shape);\n        case 'lorentzian':\n            return new Lorentzian(shape);\n        case 'pseudoVoigt':\n            return new PseudoVoigt(shape);\n        case 'pseudoVoigtTCH':\n            return new PseudoVoigtTCH(shape);\n        case 'lorentzianDispersive':\n            return new LorentzianDispersive(shape);\n        case 'generalizedLorentzian':\n            return new GeneralizedLorentzian(shape);\n        case 'splitGaussian':\n            return new SplitGaussian(shape);\n        default:\n            throw new Error(`Unknown distribution ${kind}`);\n    }\n}\n//# sourceMappingURL=getShape1D.js.map","export const DefaultParameters = {\n    x: {\n        init: (peak) => peak.x,\n        min: (peak, peakShape) => peak.x - peakShape.fwhm * 2,\n        max: (peak, peakShape) => peak.x + peakShape.fwhm * 2,\n        gradientDifference: (peak, peakShape) => peakShape.fwhm * 2e-3,\n    },\n    y: {\n        init: (peak) => peak.y,\n        min: (peak) => (peak.y < 0 ? -1.1 : 0),\n        max: (peak) => (peak.y < 0 ? 0 : 1.1),\n        gradientDifference: () => 1e-3,\n    },\n    fwhm: {\n        init: (peak, peakShape) => peakShape.fwhm,\n        min: (peak, peakShape) => peakShape.fwhm * 0.25,\n        max: (peak, peakShape) => peakShape.fwhm * 4,\n        gradientDifference: (peak, peakShape) => peakShape.fwhm * 2e-3,\n    },\n    fwhmG: {\n        init: (peak, peakShape) => peakShape.fwhm * 0.6,\n        min: (peak, peakShape) => peakShape.fwhm * 0.6 * 0.25,\n        max: (peak, peakShape) => peakShape.fwhm * 0.6 * 4,\n        gradientDifference: (peak, peakShape) => peakShape.fwhm * 0.6 * 2e-3,\n    },\n    fwhmL: {\n        init: (peak, peakShape) => peakShape.fwhm * 0.4,\n        min: (peak, peakShape) => peakShape.fwhm * 0.4 * 0.25,\n        max: (peak, peakShape) => peakShape.fwhm * 0.4 * 4,\n        gradientDifference: (peak, peakShape) => peakShape.fwhm * 0.4 * 2e-3,\n    },\n    mu: {\n        init: (peak, peakShape) => peakShape.mu,\n        min: () => 0,\n        max: () => 1,\n        gradientDifference: () => 0.01,\n    },\n    gamma: {\n        init: (peak, peakShape) => peakShape.gamma || 0.5,\n        min: () => -1,\n        max: () => 2,\n        gradientDifference: () => 0.01,\n    },\n};\n//# sourceMappingURL=DefaultParameters.js.map","import { getShape1D } from 'ml-peak-shape-generator';\nimport { assert } from \"../assert.js\";\nimport { DefaultParameters } from \"./DefaultParameters.js\";\nconst properties = ['init', 'min', 'max', 'gradientDifference'];\n/**\n * Return an array of internalPeaks that contains the exact init, min, max values based on the options\n * @param peaks\n * @param minMaxY\n * @param yScale\n * @param options\n * @returns\n */\nexport function getInternalPeaks(peaks, yScale, options = {}) {\n    let index = 0;\n    const internalPeaks = [];\n    for (const originalPeak of peaks) {\n        const normalizedPeak = {\n            ...originalPeak,\n            y: originalPeak.y / yScale,\n        };\n        const peak = normalizedPeak;\n        const { id, shape = options.shape || { kind: 'gaussian' } } = peak;\n        const shapeFct = getShape1D(shape);\n        const parameters = ['x', 'y', ...shapeFct.getParameters()];\n        const propertiesValuesInternal = {\n            min: [],\n            max: [],\n            init: [],\n            gradientDifference: [],\n        };\n        for (const parameter of parameters) {\n            for (const property of properties) {\n                // check if the property is specified in the peak\n                let propertyValue = peak?.parameters?.[parameter]?.[property];\n                if (propertyValue !== undefined) {\n                    propertyValue = getNormalizedValue(propertyValue, parameter, property, yScale);\n                    propertiesValuesInternal[property].push(propertyValue);\n                    continue;\n                }\n                // check if there are some global option, it could be a number or a callback\n                let generalParameterValue = options?.parameters?.[parameter]?.[property];\n                if (generalParameterValue !== undefined) {\n                    if (typeof generalParameterValue === 'number') {\n                        generalParameterValue = getNormalizedValue(generalParameterValue, parameter, property, yScale);\n                        propertiesValuesInternal[property].push(generalParameterValue);\n                        continue;\n                    }\n                    else {\n                        // callbacks receive user-provided peak values (not Y-normalized)\n                        let value = generalParameterValue(originalPeak);\n                        value = getNormalizedValue(value, parameter, property, yScale);\n                        propertiesValuesInternal[property].push(value);\n                        continue;\n                    }\n                }\n                // we just need to take the default parameters\n                assert(DefaultParameters[parameter], `No default parameter for ${parameter}`);\n                const defaultParameterValues = DefaultParameters[parameter][property];\n                propertiesValuesInternal[property].push(\n                //@ts-expect-error parameters and shape instance are guaranteed to be present in the defaultParameterValues function\n                defaultParameterValues(peak, shapeFct));\n            }\n        }\n        const fromIndex = index;\n        const toIndex = fromIndex + parameters.length - 1;\n        index += toIndex - fromIndex + 1;\n        const propertiesValues = {\n            min: propertiesValuesInternal.min,\n            max: propertiesValuesInternal.max,\n            init: propertiesValuesInternal.init,\n            gradientDifference: propertiesValuesInternal.gradientDifference,\n        };\n        internalPeaks.push({\n            id,\n            shape,\n            shapeFct,\n            parameters,\n            propertiesValues,\n            fromIndex,\n            toIndex,\n        });\n    }\n    return internalPeaks;\n}\nfunction getNormalizedValue(value, parameter, property, yScale) {\n    if (parameter === 'y') {\n        if (property === 'gradientDifference') {\n            return value;\n        }\n        else {\n            return value / yScale;\n        }\n    }\n    return value;\n}\n//# sourceMappingURL=getInternalPeaks.js.map","import { isAnyArray } from 'is-any-array';\nexport default function checkOptions(data, options) {\n    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;\n    let { minValues, maxValues } = options;\n    if (damping <= 0) {\n        throw new Error('The damping option must be a positive number');\n    }\n    else if (!data.x || !data.y) {\n        throw new Error('The data parameter must have x and y elements');\n    }\n    else if (!isAnyArray(data.x) ||\n        data.x.length < 2 ||\n        !isAnyArray(data.y) ||\n        data.y.length < 2) {\n        throw new Error('The data parameter elements must be an array with more than 2 points');\n    }\n    else if (data.x.length !== data.y.length) {\n        throw new Error('The data parameter elements must have the same size');\n    }\n    if (!(initialValues && initialValues.length > 0)) {\n        throw new Error('The initialValues option is mandatory and must be an array');\n    }\n    const parameters = Array.from(initialValues);\n    const parLen = parameters.length;\n    maxValues = maxValues || new Array(parLen).fill(Number.MAX_SAFE_INTEGER);\n    minValues = minValues || new Array(parLen).fill(Number.MIN_SAFE_INTEGER);\n    if (maxValues.length !== minValues.length) {\n        throw new Error('minValues and maxValues must be the same size');\n    }\n    const gradientDifferenceArray = getGradientDifferenceArray(gradientDifference, parameters);\n    const filler = getFiller(weights, data.x.length);\n    const checkTimeout = getCheckTimeout(timeout);\n    const weightSquare = Array.from({ length: data.x.length }, (_, i) => filler(i));\n    return {\n        checkTimeout,\n        minValues,\n        maxValues,\n        parameters,\n        weightSquare,\n        damping,\n        dampingStepUp,\n        dampingStepDown,\n        maxIterations,\n        errorTolerance,\n        centralDifference,\n        gradientDifference: gradientDifferenceArray,\n        improvementThreshold,\n    };\n}\nfunction getGradientDifferenceArray(gradientDifference, parameters) {\n    if (typeof gradientDifference === 'number') {\n        return new Array(parameters.length).fill(gradientDifference);\n    }\n    else if (isAnyArray(gradientDifference)) {\n        const parLen = parameters.length;\n        if (gradientDifference.length !== parLen) {\n            return new Array(parLen).fill(gradientDifference[0]);\n        }\n        return Array.from(gradientDifference);\n    }\n    throw new Error('gradientDifference should be a number or array with length equal to the number of parameters');\n}\nfunction getFiller(weights, dataLength) {\n    if (typeof weights === 'number') {\n        const value = 1 / weights ** 2;\n        return () => value;\n    }\n    else if (isAnyArray(weights)) {\n        if (weights.length < dataLength) {\n            const value = 1 / weights[0] ** 2;\n            return () => value;\n        }\n        return (i) => 1 / weights[i] ** 2;\n    }\n    throw new Error('weights should be a number or array with length equal to the number of data points');\n}\nfunction getCheckTimeout(timeout) {\n    if (timeout !== undefined) {\n        if (typeof timeout !== 'number') {\n            throw new Error('timeout should be a number');\n        }\n        const endTime = Date.now() + timeout * 1000;\n        return () => Date.now() > endTime;\n    }\n    else {\n        return () => false;\n    }\n}\n//# sourceMappingURL=check_options.js.map","/**\n * the sum of the weighted squares of the errors (or weighted residuals) between the data.y\n * and the curve-fit function.\n *\n * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param parameters - Array of current parameter values\n * @param parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param weightSquare - Square of weights (must be same length as data.x)\n */\nexport default function errorCalculation(data, parameters, parameterizedFunction, weightSquare) {\n    let error = 0;\n    const func = parameterizedFunction(parameters);\n    for (let i = 0; i < data.x.length; i++) {\n        error += (data.y[i] - func(data.x[i])) ** 2 / weightSquare[i];\n    }\n    return error;\n}\n//# sourceMappingURL=error_calculation.js.map","import { CholeskyDecomposition, Matrix, inverse } from 'ml-matrix';\nimport gradientFunction from \"./gradient_function.js\";\n/**\n * Builds the (nbParams x nbPoints) Jacobian of the residuals from an analytical\n * model gradient. The residual is `y - model`, so the residual Jacobian is the\n * negative of the model gradient — matching the sign convention produced by the\n * finite-difference `gradientFunction`.\n * @param data - points to fit\n * @param params - current parameter values\n * @param jacobianFunction - returns, for an x, the model partials over params\n */\nfunction analyticalGradient(data, params, jacobianFunction) {\n    const nbParams = params.length;\n    const nbPoints = data.x.length;\n    const ans = Matrix.zeros(nbParams, nbPoints);\n    const gradient = jacobianFunction(params);\n    for (let point = 0; point < nbPoints; point++) {\n        const partials = gradient(data.x[point]);\n        for (let param = 0; param < nbParams; param++) {\n            ans.set(param, point, -partials[param]);\n        }\n    }\n    return ans;\n}\n/**\n * Matrix function over the samples\n *\n * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param evaluatedData - Array of previous evaluated function values\n */\nfunction matrixFunction(data, evaluatedData) {\n    const m = data.x.length;\n    const ans = new Matrix(m, 1);\n    for (let point = 0; point < m; point++) {\n        ans.set(point, 0, data.y[point] - evaluatedData[point]);\n    }\n    return ans;\n}\n/**\n * Iteration for Levenberg-Marquardt\n *\n * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param params - Array of previous parameter values\n * @param damping - Levenberg-Marquardt parameter\n * @param gradientDifference - The step size to approximate the jacobian matrix\n * @param centralDifference - If true the jacobian matrix is approximated by central differences otherwise by forward differences\n * @param parameterizedFunction - The parameters and returns a function with the independent variable as a parameter\n * @param weights - scale the gradient and residual error by weights\n * @param jacobianFunction - optional analytical Jacobian, replaces finite differences when provided\n */\nexport default function step(data, params, damping, gradientDifference, parameterizedFunction, centralDifference, weights, jacobianFunction) {\n    const func = parameterizedFunction(params);\n    const evaluatedData = new Float64Array(data.x.length);\n    for (let i = 0; i < data.x.length; i++) {\n        evaluatedData[i] = func(data.x[i]);\n    }\n    const gradientFunc = jacobianFunction\n        ? analyticalGradient(data, params, jacobianFunction)\n        : gradientFunction(data, evaluatedData, params, gradientDifference, parameterizedFunction, centralDifference);\n    const residualError = matrixFunction(data, evaluatedData);\n    const hessianApproximation = gradientFunc.mmulByTranspose(weights);\n    for (let i = 0; i < params.length; i++) {\n        hessianApproximation.set(i, i, hessianApproximation.get(i, i) + damping);\n    }\n    const jacobianWeightResidualError = gradientFunc.mmul(residualError.scale('row', { scale: weights }));\n    // (damping * I + Jᵀ W J) is symmetric positive-definite for damping > 0, so a\n    // Cholesky solve is faster and more numerically stable than forming the full\n    // inverse and multiplying. Fall back to the inverse only in the rare case the\n    // approximated Hessian is not positive-definite.\n    const cholesky = new CholeskyDecomposition(hessianApproximation);\n    const perturbations = cholesky.isPositiveDefinite()\n        ? cholesky.solve(jacobianWeightResidualError)\n        : inverse(hessianApproximation).mmul(jacobianWeightResidualError);\n    return {\n        perturbations,\n        jacobianWeightResidualError,\n    };\n}\n//# sourceMappingURL=step.js.map","import { Matrix } from 'ml-matrix';\n/**\n * Difference of the matrix function over the parameters\n * @param data Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param evaluatedData - Array of previous evaluated function values\n * @param params - Array of previous parameter values\n * @param gradientDifference - The step size to approximate the jacobian matrix\n * @param centralDifference - If true the jacobian matrix is approximated by central differences otherwise by forward differences\n * @param paramFunction - The parameters and returns a function with the independent variable as a parameter\n */\nexport default function gradientFunction(data, evaluatedData, params, gradientDifference, paramFunction, centralDifference) {\n    const nbParams = params.length;\n    const nbPoints = data.x.length;\n    const ans = Matrix.zeros(nbParams, nbPoints);\n    let rowIndex = 0;\n    for (let param = 0; param < nbParams; param++) {\n        if (gradientDifference[param] === 0)\n            continue;\n        let delta = gradientDifference[param];\n        let auxParams = params.slice();\n        auxParams[param] += delta;\n        const funcParam = paramFunction(auxParams);\n        if (!centralDifference) {\n            for (let point = 0; point < nbPoints; point++) {\n                ans.set(rowIndex, point, (evaluatedData[point] - funcParam(data.x[point])) / delta);\n            }\n        }\n        else {\n            auxParams = params.slice();\n            auxParams[param] -= delta;\n            delta *= 2;\n            const funcParam2 = paramFunction(auxParams);\n            for (let point = 0; point < nbPoints; point++) {\n                ans.set(rowIndex, point, (funcParam2(data.x[point]) - funcParam(data.x[point])) / delta);\n            }\n        }\n        rowIndex++;\n    }\n    return ans;\n}\n//# sourceMappingURL=gradient_function.js.map","import checkOptions from \"./check_options.js\";\nimport errorCalculation from \"./error_calculation.js\";\nimport step from \"./step.js\";\n/**\n * Curve fitting algorithm\n * @param data - Array of points to fit in the format [x1, x2, ... ], [y1, y2, ... ]\n * @param parameterizedFunction - Takes an array of parameters and returns a function with the independent variable as its sole argument\n * @param options - Options object\n */\nexport function levenbergMarquardt(data, parameterizedFunction, options) {\n    const checkedOptions = checkOptions(data, options);\n    const { checkTimeout, minValues, maxValues, parameters, weightSquare, dampingStepUp, dampingStepDown, maxIterations, errorTolerance, centralDifference, gradientDifference, improvementThreshold, } = checkedOptions;\n    let damping = checkedOptions.damping;\n    const { jacobianFunction } = options;\n    let error = errorCalculation(data, parameters, parameterizedFunction, weightSquare);\n    let optimalError = error;\n    let optimalParameters = parameters.slice();\n    let converged = error <= errorTolerance;\n    let iteration = 0;\n    for (; iteration < maxIterations && !converged; iteration++) {\n        const previousError = error;\n        const { perturbations, jacobianWeightResidualError } = step(data, parameters, damping, gradientDifference, parameterizedFunction, centralDifference, weightSquare, jacobianFunction);\n        for (let k = 0; k < parameters.length; k++) {\n            parameters[k] = Math.min(Math.max(minValues[k], parameters[k] - perturbations.get(k, 0)), maxValues[k]);\n        }\n        error = errorCalculation(data, parameters, parameterizedFunction, weightSquare);\n        if (isNaN(error))\n            break;\n        if (error < optimalError - errorTolerance) {\n            optimalError = error;\n            optimalParameters = parameters.slice();\n        }\n        const improvementMetric = (previousError - error) /\n            perturbations\n                .transpose()\n                .mmul(perturbations.mul(damping).add(jacobianWeightResidualError))\n                .get(0, 0);\n        if (improvementMetric > improvementThreshold) {\n            damping = Math.max(damping / dampingStepDown, 1e-7);\n        }\n        else {\n            damping = Math.min(damping * dampingStepUp, 1e7);\n        }\n        if (checkTimeout()) {\n            throw new Error(`The execution time is over to ${options.timeout} seconds`);\n        }\n        converged = error <= errorTolerance;\n    }\n    return {\n        parameterValues: optimalParameters,\n        parameterError: optimalError,\n        iterations: iteration,\n    };\n}\n//# sourceMappingURL=levenberg_marquardt.js.map","/**\n * Preparata, F. P., & Shamos, M. I. (2012). Computational geometry: an introduction. Springer Science & Business Media.\n * @param {Array} x - The array with x coordinates of the points.\n * @param {Array} y - The array with y coordinates of the points.\n * @return {Array} The indices of the points of anticlockwise lower convex hull\n * @private\n */\nexport default function antiLowerConvexHull(x, y) {\n  if (x.length !== y.length) {\n    throw new RangeError('X and Y vectors has different dimensions');\n  }\n\n  const nbPoints = x.length - 1;\n  if (nbPoints === 0) return [0];\n  if (nbPoints === 1) return [0, 1];\n\n  let currentPoint = 0;\n  let result = new Array(x.length).fill(true);\n  while (true) {\n    const a = currentPoint;\n    const b = moveOn(currentPoint, nbPoints, result);\n    const c = moveOn(moveOn(currentPoint, nbPoints, result), nbPoints, result);\n\n    const det =\n      x[c] * (y[a] - y[b]) + x[a] * (y[b] - y[c]) + x[b] * (y[c] - y[a]);\n\n    const leftTurn = det >= 0;\n\n    if (leftTurn) {\n      currentPoint = b;\n    } else {\n      result[b] = false;\n      currentPoint = moveBack(currentPoint, nbPoints, result);\n    }\n    if (c === nbPoints) break;\n  }\n\n  return result\n    .map((item, index) => (item === false ? false : index))\n    .filter((item) => item !== false);\n}\n\n/**\n * @param {number} currentPoint - The index of the current point to make the move\n * @param {number} nbPoints - The total number of points in the array\n * @param {Array} vector - The array with the points\n * @return {number} the index of the point after the move\n * @private\n */\n\nfunction moveBack(currentPoint, nbPoints, vector) {\n  let counter = currentPoint - 1;\n  while (vector[counter] === false) counter--;\n  return currentPoint === 0 ? nbPoints : counter;\n}\n\nfunction moveOn(currentPoint, nbPoints, vector) {\n  let counter = currentPoint + 1;\n  while (vector[counter] === false) counter++;\n  return currentPoint === nbPoints ? 0 : counter;\n}\n","import { xNorm, xMaxValue, xMinValue } from 'ml-spectra-processing';\n\nimport antiLowerConvexHull from './util/antiLowerConvexHull';\n\n/**\n * Performs a global optimization of required parameters\n * It will return an object containing:\n * - `minFunctionValue`: The minimum value found for the objetive function\n * - `optima`: Array of Array of values for all the variables where the function reach its minimum value\n * - `iterations`: Number of iterations performed in the process\n * - `finalState`: Internal state allowing to continue optimization (initialState)\n * @param {function} objectiveFunction Function to evaluate. It should accept an array of variables\n * @param {Array} lowerBoundaries Array containing for each variable the lower boundary\n * @param {Array} upperBoundaries Array containing for each variable the higher boundary\n * @param {Object} [options={}]\n * @param {number} [options.iterations] - Number of iterations.\n * @param {number} [options.epsilon] - Tolerance to choose best current value.\n * @param {number} [options.tolerance] - Minimum tollerance of the function.\n * @param {number} [options.tolerance2] - Minimum tollerance of the function.\n * @param {Object} [options.initialState={}}] - finalState of previous optimization.\n * @return {Object} {finalState, iterations, minFunctionValue}\n * */\n\nexport default function direct(\n  objectiveFunction,\n  lowerBoundaries,\n  upperBoundaries,\n  options = {},\n) {\n  const {\n    iterations = 50,\n    epsilon = 1e-4,\n    tolerance = 1e-16,\n    tolerance2 = 1e-12,\n    initialState = {},\n  } = options;\n\n  if (\n    objectiveFunction === undefined ||\n    lowerBoundaries === undefined ||\n    upperBoundaries === undefined\n  ) {\n    throw new RangeError('There is something undefined');\n  }\n\n  lowerBoundaries = new Float64Array(lowerBoundaries);\n  upperBoundaries = new Float64Array(upperBoundaries);\n\n  if (lowerBoundaries.length !== upperBoundaries.length) {\n    throw new Error(\n      'Lower bounds and Upper bounds for x are not of the same length',\n    );\n  }\n\n  //-------------------------------------------------------------------------\n  //                        STEP 1. Initialization\n  //-------------------------------------------------------------------------\n  let n = lowerBoundaries.length;\n  let diffBorders = upperBoundaries.map((x, i) => x - lowerBoundaries[i]);\n\n  let {\n    numberOfRectangles = 0,\n    totalIterations = 0,\n    unitaryCoordinates = [new Float64Array(n).fill(0.5)],\n    middlePoint = new Float64Array(n).map((value, index) => {\n      return (\n        lowerBoundaries[index] +\n        unitaryCoordinates[0][index] * diffBorders[index]\n      );\n    }),\n    bestCurrentValue = objectiveFunction(middlePoint),\n    fCalls = 1,\n    smallerDistance = 0,\n    edgeSizes = [new Float64Array(n).fill(0.5)],\n    diagonalDistances = [Math.sqrt(n * 0.5 ** 2)],\n    functionValues = [bestCurrentValue],\n    differentDistances = diagonalDistances,\n    smallerValuesByDistance = [bestCurrentValue],\n    choiceLimit = undefined,\n  } = initialState;\n  if (\n    initialState.originalCoordinates &&\n    initialState.originalCoordinates.length > 0\n  ) {\n    bestCurrentValue = xMinValue(functionValues);\n    choiceLimit =\n      epsilon * Math.abs(bestCurrentValue) > 1e-8\n        ? epsilon * Math.abs(bestCurrentValue)\n        : 1e-8;\n\n    smallerDistance = getMinIndex(\n      functionValues,\n      diagonalDistances,\n      choiceLimit,\n      bestCurrentValue,\n    );\n\n    unitaryCoordinates = initialState.originalCoordinates.slice();\n    for (let j = 0; j < unitaryCoordinates.length; j++) {\n      for (let i = 0; i < lowerBoundaries.length; i++) {\n        unitaryCoordinates[j][i] =\n          (unitaryCoordinates[j][i] - lowerBoundaries[i]) / diffBorders[i];\n      }\n    }\n  }\n\n  let iteration = 0;\n  //-------------------------------------------------------------------------\n  //                          Iteration loop\n  //-------------------------------------------------------------------------\n\n  while (iteration < iterations) {\n    //----------------------------------------------------------------------\n    //  STEP 2. Identify the set S of all potentially optimal rectangles\n    //----------------------------------------------------------------------\n\n    let S1 = [];\n    let idx = differentDistances.findIndex(\n      // eslint-disable-next-line no-loop-func\n      (e) => e === diagonalDistances[smallerDistance],\n    );\n    let counter = 0;\n    for (let i = idx; i < differentDistances.length; i++) {\n      for (let f = 0; f < functionValues.length; f++) {\n        if (\n          (functionValues[f] === smallerValuesByDistance[i]) &\n          (diagonalDistances[f] === differentDistances[i])\n        ) {\n          S1[counter++] = f;\n        }\n      }\n    }\n\n    let optimumValuesIndex, S3;\n    if (differentDistances.length - idx > 1) {\n      let a1 = diagonalDistances[smallerDistance];\n      let b1 = functionValues[smallerDistance];\n      let a2 = differentDistances[differentDistances.length - 1];\n      let b2 = smallerValuesByDistance[differentDistances.length - 1];\n      let slope = (b2 - b1) / (a2 - a1);\n      let constant = b1 - slope * a1;\n      let S2 = new Uint32Array(counter);\n      counter = 0;\n      for (let i = 0; i < S2.length; i++) {\n        let j = S1[i];\n        if (\n          functionValues[j] <=\n          slope * diagonalDistances[j] + constant + tolerance2\n        ) {\n          S2[counter++] = j;\n        }\n      }\n\n      let xHull = [];\n      let yHull = [];\n      for (let i = 0; i < counter; i++) {\n        xHull.push(diagonalDistances[S2[i]]);\n        yHull.push(functionValues[S2[i]]);\n      }\n\n      let lowerIndexHull = antiLowerConvexHull(xHull, yHull);\n\n      S3 = [];\n      for (let i = 0; i < lowerIndexHull.length; i++) {\n        S3.push(S2[lowerIndexHull[i]]);\n      }\n    } else {\n      S3 = S1.slice(0, counter);\n    }\n    optimumValuesIndex = S3;\n    //--------------------------------------------------------------\n    // STEPS 3,5: Select any rectangle j in S\n    //--------------------------------------------------------------\n    for (let k = 0; k < optimumValuesIndex.length; k++) {\n      let j = optimumValuesIndex[k];\n      let largerSide = xMaxValue(edgeSizes[j]);\n      let largeSidesIndex = new Uint32Array(edgeSizes[j].length);\n      counter = 0;\n      for (let i = 0; i < edgeSizes[j].length; i++) {\n        if (Math.abs(edgeSizes[j][i] - largerSide) < tolerance) {\n          largeSidesIndex[counter++] = i;\n        }\n      }\n      let delta = (2 * largerSide) / 3;\n      let bestFunctionValues = [];\n      for (let r = 0; r < counter; r++) {\n        let i = largeSidesIndex[r];\n        let firstMiddleCenter = unitaryCoordinates[j].slice();\n        let secondMiddleCenter = unitaryCoordinates[j].slice();\n        firstMiddleCenter[i] += delta;\n        secondMiddleCenter[i] -= delta;\n        let firstMiddleValue = new Float64Array(firstMiddleCenter.length);\n        let secondMiddleValue = new Float64Array(secondMiddleCenter.length);\n        for (let i = 0; i < firstMiddleCenter.length; i++) {\n          firstMiddleValue[i] =\n            lowerBoundaries[i] + firstMiddleCenter[i] * diffBorders[i];\n          secondMiddleValue[i] =\n            lowerBoundaries[i] + secondMiddleCenter[i] * diffBorders[i];\n        }\n        let firstMinValue = objectiveFunction(firstMiddleValue);\n        let secondMinValue = objectiveFunction(secondMiddleValue);\n        fCalls += 2;\n        bestFunctionValues.push({\n          minValue: Math.min(firstMinValue, secondMinValue),\n          index: r,\n        });\n        // [Math.min(firstMinValue, secondMinValue), r];\n        unitaryCoordinates.push(firstMiddleCenter, secondMiddleCenter);\n        functionValues.push(firstMinValue, secondMinValue);\n      }\n\n      let b = bestFunctionValues.sort((a, b) => a.minValue - b.minValue);\n      for (let r = 0; r < counter; r++) {\n        let u = largeSidesIndex[b[r].index];\n        let ix1 = numberOfRectangles + 2 * (b[r].index + 1) - 1;\n        let ix2 = numberOfRectangles + 2 * (b[r].index + 1);\n        edgeSizes[j][u] = delta / 2;\n        edgeSizes[ix1] = edgeSizes[j].slice();\n        edgeSizes[ix2] = edgeSizes[j].slice();\n        diagonalDistances[j] = xNorm(edgeSizes[j]);\n        diagonalDistances[ix1] = diagonalDistances[j];\n        diagonalDistances[ix2] = diagonalDistances[j];\n      }\n      numberOfRectangles += 2 * counter;\n    }\n\n    //--------------------------------------------------------------\n    //                  Update\n    //--------------------------------------------------------------\n\n    bestCurrentValue = xMinValue(functionValues);\n\n    choiceLimit =\n      epsilon * Math.abs(bestCurrentValue) > 1e-8\n        ? epsilon * Math.abs(bestCurrentValue)\n        : 1e-8;\n\n    smallerDistance = getMinIndex(\n      functionValues,\n      diagonalDistances,\n      choiceLimit,\n      bestCurrentValue,\n      iteration,\n    );\n\n    differentDistances = Array.from(new Set(diagonalDistances));\n    differentDistances = differentDistances.sort((a, b) => a - b);\n\n    smallerValuesByDistance = [];\n    for (let i = 0; i < differentDistances.length; i++) {\n      let minIndex;\n      let minValue = Number.POSITIVE_INFINITY;\n      for (let k = 0; k < diagonalDistances.length; k++) {\n        if (diagonalDistances[k] === differentDistances[i]) {\n          if (functionValues[k] < minValue) {\n            minValue = functionValues[k];\n            minIndex = k;\n          }\n        }\n      }\n      smallerValuesByDistance.push(functionValues[minIndex]);\n    }\n\n    let currentMin = [];\n    for (let j = 0; j < functionValues.length; j++) {\n      if (functionValues[j] === bestCurrentValue) {\n        let temp = [];\n        for (let i = 0; i < lowerBoundaries.length; i++) {\n          temp.push(\n            lowerBoundaries[i] + unitaryCoordinates[j][i] * diffBorders[i],\n          );\n        }\n        currentMin.push(temp);\n      }\n    }\n    iteration += 1;\n  }\n  //--------------------------------------------------------------\n  //                  Saving results\n  //--------------------------------------------------------------\n\n  let result = {};\n  result.minFunctionValue = bestCurrentValue;\n  result.iterations = iteration;\n  let originalCoordinates = [];\n  for (let j = 0; j < numberOfRectangles + 1; j++) {\n    let pair = [];\n    for (let i = 0; i < lowerBoundaries.length; i++) {\n      pair.push(lowerBoundaries[i] + unitaryCoordinates[j][i] * diffBorders[i]);\n    }\n    originalCoordinates.push(pair);\n  }\n\n  result.finalState = {\n    numberOfRectangles,\n    totalIterations: (totalIterations += iterations),\n    originalCoordinates,\n    middlePoint,\n    fCalls,\n    smallerDistance,\n    edgeSizes,\n    diagonalDistances,\n    functionValues,\n    differentDistances,\n    smallerValuesByDistance,\n    choiceLimit,\n  };\n\n  let minimizer = [];\n  for (let i = 0; i < functionValues.length; i++) {\n    if (functionValues[i] === bestCurrentValue) {\n      minimizer.push(originalCoordinates[i]);\n    }\n  }\n\n  result.optima = minimizer;\n  return result;\n}\n\nfunction getMinIndex(\n  functionValues,\n  diagonalDistances,\n  choiceLimit,\n  bestCurrentValue,\n) {\n  let item = [];\n  for (let i = 0; i < functionValues.length; i++) {\n    item[i] =\n      Math.abs(functionValues[i] - (bestCurrentValue + choiceLimit)) /\n      diagonalDistances[i];\n  }\n  const min = xMinValue(item);\n  let result = item.findIndex((x) => x === min);\n  return result;\n}\n","import direct from 'ml-direct';\n/**\n * Run a direct optimization on the provided data using a sum-of-shapes model.\n * @param data - The observed x/y data to fit.\n * @param sumOfShapes - A function returning the model prediction for a given parameter vector.\n * @param options - Optimization bounds and solver options.\n * @returns The optimized parameter values, the final objective error, and the number of iterations.\n */\nexport function directOptimization(data, sumOfShapes, options) {\n    const { minValues, maxValues, maxIterations, epsilon, tolerance, tolerance2, initialState, } = options;\n    const objectiveFunction = getObjectiveFunction(data, sumOfShapes);\n    const result = direct(objectiveFunction, \n    // direct internally converts ArrayLike to Float64Array,\n    // so we can safely cast minValues and maxValues to number[]\n    minValues, maxValues, {\n        iterations: maxIterations,\n        epsilon,\n        tolerance,\n        tolerance2,\n        initialState,\n    });\n    const { optima, minFunctionValue, iterations } = result;\n    return {\n        parameterError: minFunctionValue,\n        iterations,\n        parameterValues: optima[0],\n    };\n}\nfunction getObjectiveFunction(data, sumOfShapes) {\n    const { x, y } = data;\n    const nbPoints = x.length;\n    return (parameters) => {\n        const fct = sumOfShapes(parameters);\n        let error = 0;\n        for (let i = 0; i < nbPoints; i++) {\n            error += (y[i] - fct(x[i])) ** 2;\n        }\n        return error;\n    };\n}\n//# sourceMappingURL=directOptimization.js.map","import { xMaxAbsoluteValue } from 'ml-spectra-processing';\nimport { getSumOfShapes } from \"./shapes/getSumOfShapes.js\";\nimport { buildOptimizationLayout } from \"./util/buildOptimizationLayout.js\";\nimport { getFixedParametersResult } from \"./util/getFixedParametersResult.js\";\nimport { getInternalPeaks } from \"./util/internalPeaks/getInternalPeaks.js\";\nimport { reconstructPeaks } from \"./util/reconstructPeaks.js\";\nimport { selectMethod } from \"./util/selectMethod.js\";\n/**\n * Fits a set of points to the sum of a set of bell functions.\n * @param data - An object containing the x and y data to be fitted.\n * @param peaks - A list of initial parameters to be optimized. e.g. coming from a peak picking [{x, y, width}].\n * @param options - Options for optimize\n * @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.\n */\nexport function optimize(data, peaks, options = {}) {\n    // rescale data so the maximum Y value becomes 1\n    const max = xMaxAbsoluteValue(data.y);\n    const yScale = max === 0 ? 1 : max;\n    const internalPeaks = getInternalPeaks(peaks, yScale, options);\n    // need to rescale what is related to Y\n    const normalizedY = new Float64Array(data.y.length);\n    for (let i = 0; i < data.y.length; i++) {\n        normalizedY[i] = data.y[i] / yScale;\n    }\n    const optimizationLayout = buildOptimizationLayout(internalPeaks, peaks, options, yScale);\n    const { freeIndices, variableMin, variableMax, variableInit, variableGrad, variables, } = optimizationLayout;\n    const { algorithm, optimizationOptions } = selectMethod(options.optimization);\n    const baseSumOfShapes = getSumOfShapes(internalPeaks);\n    const sumOfShapesForVariables = (variableValues) => {\n        return baseSumOfShapes(optimizationLayout.variableToPeakValues(variableValues));\n    };\n    if (freeIndices.length === 0) {\n        return getFixedParametersResult(internalPeaks, normalizedY, data.x, optimizationLayout.variableToPeakValues(variableInit), baseSumOfShapes, yScale);\n    }\n    // prepare arrays to pass to the algorithm (reduced if needed)\n    let minValues;\n    let maxValues;\n    let initialValues;\n    let gradientDifferences;\n    let sumOfShapesToUse = sumOfShapesForVariables;\n    if (freeIndices.length === variables.length) {\n        // nothing to reduce\n        minValues = variableMin;\n        maxValues = variableMax;\n        initialValues = variableInit;\n        gradientDifferences = variableGrad;\n    }\n    else {\n        // wrapper that maps reduced (free) parameters into the full parameter vector\n        const sumOfShapesForReduced = (reducedParameters) => {\n            const full = new Float64Array(variables.length);\n            full.set(variableInit);\n            for (let k = 0; k < freeIndices.length; k++) {\n                full[freeIndices[k]] = reducedParameters[k];\n            }\n            return sumOfShapesForVariables(full);\n        };\n        minValues = new Float64Array(freeIndices.length);\n        maxValues = new Float64Array(freeIndices.length);\n        initialValues = new Float64Array(freeIndices.length);\n        gradientDifferences = new Float64Array(freeIndices.length);\n        for (let j = 0; j < freeIndices.length; j++) {\n            const i = freeIndices[j];\n            minValues[j] = variableMin[i];\n            maxValues[j] = variableMax[i];\n            initialValues[j] = variableInit[i];\n            gradientDifferences[j] = variableGrad[i];\n        }\n        sumOfShapesToUse = sumOfShapesForReduced;\n    }\n    const fitted = algorithm({ x: data.x, y: normalizedY }, sumOfShapesToUse, {\n        minValues,\n        maxValues,\n        initialValues,\n        gradientDifference: gradientDifferences,\n        ...optimizationOptions,\n    });\n    let fittedVariableValues;\n    if (freeIndices.length === variables.length) {\n        fittedVariableValues = fitted.parameterValues;\n    }\n    else {\n        const full = variableInit.slice();\n        for (let k = 0; k < freeIndices.length; k++) {\n            full[freeIndices[k]] = fitted.parameterValues[k];\n        }\n        fittedVariableValues = full;\n    }\n    const fittedValues = optimizationLayout.variableToPeakValues(fittedVariableValues);\n    return {\n        error: fitted.parameterError,\n        iterations: fitted.iterations,\n        peaks: reconstructPeaks(internalPeaks, fittedValues, yScale),\n    };\n}\n//# sourceMappingURL=index.js.map","import { xCheck } from \"./xCheck.js\";\nimport { xGetFromToIndex } from \"./xGetFromToIndex.js\";\n/**\n * Computes the maximal value of an array of values\n * @param array - array of numbers\n * @param options - options\n */\nexport function xMaxAbsoluteValue(array, options = {}) {\n    xCheck(array);\n    const { fromIndex, toIndex } = xGetFromToIndex(array, options);\n    let maxValue = Math.abs(array[fromIndex]);\n    for (let i = fromIndex + 1; i <= toIndex; i++) {\n        if (array[i] >= 0) {\n            if (array[i] > maxValue) {\n                maxValue = array[i];\n            }\n        }\n        else if (-array[i] > maxValue) {\n            maxValue = -array[i];\n        }\n    }\n    return maxValue;\n}\n//# sourceMappingURL=xMaxAbsoluteValue.js.map","import { levenbergMarquardt } from 'ml-levenberg-marquardt';\nimport { directOptimization } from \"./wrappers/directOptimization.js\";\n/**\n * Algorithm to select the method.\n * @param optimizationOptions - Optimization options\n * @returns - The algorithm and optimization options\n */\nexport function selectMethod(optimizationOptions = {}) {\n    const { kind = 'lm', options } = optimizationOptions;\n    switch (kind) {\n        case 'lm':\n        case 'levenbergMarquardt':\n            return {\n                algorithm: levenbergMarquardt,\n                optimizationOptions: {\n                    damping: 1.5,\n                    maxIterations: 100,\n                    errorTolerance: 1e-8,\n                    ...options,\n                },\n            };\n        case 'direct': {\n            return {\n                algorithm: directOptimization,\n                optimizationOptions: {\n                    maxIterations: 20,\n                    epsilon: 1e-4,\n                    tolerance: 1e-16,\n                    tolerance2: 1e-12,\n                    initialState: {},\n                    ...options,\n                },\n            };\n        }\n        default:\n            throw new Error(`Unknown fitting algorithm`);\n    }\n}\n//# sourceMappingURL=selectMethod.js.map","/**\n * This function returns the sumOfShapes function\n * This function gives sumOfShapes access to the peak list and the associated data\n * @param internalPeaks\n */\nexport function getSumOfShapes(internalPeaks) {\n    return function sumOfShapes(parameters) {\n        for (const peak of internalPeaks) {\n            for (let i = 2; i < peak.parameters.length; i++) {\n                const shapeFctKey = peak.parameters[i];\n                peak.shapeFct[shapeFctKey] = parameters[peak.fromIndex + i];\n            }\n        }\n        return (x) => {\n            let totalY = 0;\n            for (const peak of internalPeaks) {\n                const peakX = parameters[peak.fromIndex];\n                const y = parameters[peak.fromIndex + 1];\n                totalY += y * peak.shapeFct.fct(x - peakX);\n            }\n            return totalY;\n        };\n    };\n}\n//# sourceMappingURL=getSumOfShapes.js.map","import { reconstructPeaks } from \"./reconstructPeaks.js\";\n/**\n * Build result when no parameters are free to optimize.\n * Computes the fit error using the provided `globalInit` parameter vector\n * and reconstructs the output peak objects from `internalPeaks`.\n * @template T - input Peak type\n * @param internalPeaks - internal representation of peaks (with parameter indices)\n * @param normalizedY - observed Y values normalized by the global scale\n * @param x - X axis values\n * @param globalInit - full parameter vector (actual-space) used to evaluate the model\n * @param baseSumOfShapes - function that returns the spectrum function given parameters\n * @param yScale - the scale factor used to normalize Y (used to reconstruct peak amplitudes)\n * @returns an object containing `error`, `iterations` (0) and the reconstructed `peaks`\n */\nexport function getFixedParametersResult(internalPeaks, normalizedY, x, globalInit, baseSumOfShapes, yScale) {\n    const fct = baseSumOfShapes(globalInit);\n    let error = 0;\n    for (let i = 0; i < normalizedY.length; i++) {\n        error += (normalizedY[i] - fct(x[i])) ** 2;\n    }\n    return {\n        error,\n        iterations: 0,\n        peaks: reconstructPeaks(internalPeaks, globalInit, yScale),\n    };\n}\n//# sourceMappingURL=getFixedParametersResult.js.map"],"names":["toString","Object","prototype","isAnyArray","value","tag","call","endsWith","includes","xCheck","input","options","minLength","TypeError","length","Error","xFindClosestIndex","array","target","sorted","low","high","middle","Math","abs","index","diff","Number","POSITIVE_INFINITY","i","currentDiff","xGetFromToIndex","x","fromIndex","toIndex","from","to","undefined","CholeskyDecomposition","matrix","Matrix","inverse","xMean","sumValue","xMaxValue","maxValue","xMinValue","minValue","xNorm","result","element","sqrt","assert","message","buildOptimizationLayout","internalPeaks","peaks","yScale","slots","peakIndex","internalPeak","parameters","parameter","push","actualIndex","peakId","id","init","propertiesValues","min","max","gradientDifference","optimize","getOptimizeFlag","buildParameterSlots","variables","linkedParameters","groupedActualIndices","Set","slotLookup","Map","idToIndices","slot","set","getSlotKey","indices","get","linkedParameter","buildLinkedVariable","has","sortKey","members","factor","offset","sort","a","b","map","_sortKey","variable","buildOptimizationVariables","variableMin","Float64Array","variableMax","variableInit","variableGrad","freeIndices","variableToPeakValues","variableValues","actualValues","Array","variableValue","member","resolvedMembers","peak","size","resolvePeakIndexById","isInteger","String","resolveLinkedSlot","getFactor","getOffset","memberActualIndices","add","firstMember","sharedMin","NEGATIVE_INFINITY","sharedMax","sharedInitCandidates","variableBounds","getMemberVariableBounds","m","isFinite","transformedMin","transformedMax","optimizeFlag","perPeakParam","globalParam","reconstructPeaks","newPeaks","shape","newPeak","y","GAUSSIAN_EXP_FACTOR","LN2","ROOT_PI_OVER_LN2","PI","ROOT_LN2","ROOT_THREE","ROOT_2LN2","ROOT_2LN2_MINUS_ONE","Gaussian","kind","fwhm","constructor","sd","this","gaussianWidthToFWHM","fwhmToWidth","gaussianFwhmToWidth","widthToFWHM","width","fct","gaussianFct","getArea","height","calculateGaussianHeight","getGaussianArea","area","getGaussianFactor","getData","ceil","center","data","getGaussianData","calculateHeight","getParameters","toJSON","derivative","dx","dFwhm","gaussianDerivative","exp","ln1MinusXSqrd","log","lnEtcBy2Plus2","firstSqrt","erfinv","Lorentzian","lorentzianFwhmToWidth","lorentzianWidthToFWHM","lorentzianFct","getLorentzianArea","getLorentzianFactor","getLorentzianData","calculateLorentzianHeight","denominator","lorentzianDerivative","lorentzianQuantile","p","tan","halfResidual","LorentzianDispersive","lorentzianDispersiveFct","getLorentzianDispersiveData","lorentzianDispersiveDerivative","sqrtLn2","pGaussian","k","sign","t","erf","pPseudoVoigt","mu","atan","pLorentz","PseudoVoigt","pseudoVoigtFwhmToWidth","pseudoVoigtWidthToFWHM","pseudoVoigtFct","getPseudoVoigtArea","getPseudoVoigtFactor","calculatePseudoVoigtHeight","getPseudoVoigtData","dMu","z","e","lorentz","dEdt","dLdt","dEdfwhm","dLdfwhm","pseudoVoigtDerivative","lorentzian","pTarget","tol","maxIter","RangeError","lo","hi","it","mid","val","pseudoVoigtFindFactor","PseudoVoigtTCH","_fwhmG","_fwhmL","_fwhm","_mu","_lorentzianWidthFraction","fwhmG","fwhmL","lorentzianWidthFraction","effectiveFwhm","computeEffectiveWidth","lorentzianFraction","gaussianWidthFraction","dFwhmG","dFwhmL","w","dFwhmDfwhmG","dFwhmDfwhmL","dPolyDfraction","dMuDfwhmG","dMuDfwhmL","denominator2","pseudoVoigtTCHDerivative","fraction","q","g","f","df","GeneralizedLorentzian","gamma","generalizedLorentzianFwhmToWidth","generalizedLorentzianWidthToFWHM","generalizedLorentzianFct","getGeneralizedLorentzianArea","getGeneralizedLorentzianFactor","getGeneralizedLorentzianData","calculateGeneralizedLorentzianHeight","dGamma","u","rational","dFctDu","duDx","duDfwhm","generalizedLorentzianDerivative","generalizedLorentzianQuantile","SplitGaussian","fwhmLow","fwhmHigh","ratio","splitGaussianFct","calculateSplitGaussianHeight","getSplitGaussianArea","getSplitGaussianData","dFwhmLow","dFwhmHigh","splitGaussianDerivative","getShape1D","DefaultParameters","peakShape","properties","getNormalizedValue","property","checkOptions","timeout","initialValues","weights","damping","dampingStepUp","dampingStepDown","maxIterations","errorTolerance","centralDifference","improvementThreshold","minValues","maxValues","parLen","fill","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","gradientDifferenceArray","getGradientDifferenceArray","filler","dataLength","getFiller","checkTimeout","endTime","Date","now","getCheckTimeout","weightSquare","_","errorCalculation","parameterizedFunction","error","func","step","params","jacobianFunction","evaluatedData","gradientFunc","nbParams","nbPoints","ans","zeros","gradient","point","partials","param","analyticalGradient","paramFunction","rowIndex","delta","auxParams","slice","funcParam","funcParam2","gradientFunction","residualError","matrixFunction","hessianApproximation","mmulByTranspose","jacobianWeightResidualError","mmul","scale","cholesky","perturbations","isPositiveDefinite","solve","levenbergMarquardt","checkedOptions","optimalError","optimalParameters","converged","iteration","previousError","isNaN","transpose","mul","parameterValues","parameterError","iterations","antiLowerConvexHull","currentPoint","moveOn","c","moveBack","item","filter","vector","counter","getMinIndex","functionValues","diagonalDistances","choiceLimit","bestCurrentValue","findIndex","directOptimization","sumOfShapes","epsilon","tolerance","tolerance2","initialState","objectiveFunction","getObjectiveFunction","lowerBoundaries","upperBoundaries","n","diffBorders","numberOfRectangles","totalIterations","unitaryCoordinates","middlePoint","fCalls","smallerDistance","edgeSizes","differentDistances","smallerValuesByDistance","originalCoordinates","j","optimumValuesIndex","S3","S1","idx","a1","b1","a2","slope","constant","S2","Uint32Array","xHull","yHull","lowerIndexHull","largerSide","largeSidesIndex","bestFunctionValues","r","firstMiddleCenter","secondMiddleCenter","firstMiddleValue","secondMiddleValue","firstMinValue","secondMinValue","ix1","ix2","minIndex","temp","minFunctionValue","pair","finalState","minimizer","optima","direct","xMaxAbsoluteValue","originalPeak","shapeFct","propertiesValuesInternal","propertyValue","generalParameterValue","defaultParameterValues","getInternalPeaks","normalizedY","optimizationLayout","algorithm","optimizationOptions","selectMethod","optimization","baseSumOfShapes","shapeFctKey","totalY","peakX","getSumOfShapes","sumOfShapesForVariables","globalInit","getFixedParametersResult","gradientDifferences","sumOfShapesToUse","sumOfShapesForReduced","reducedParameters","full","fitted","fittedVariableValues","fittedValues"],"mappings":";AACA,MAAMA,EAAWC,OAAOC,UAAUF,SAmB5B,SAAUG,EAAWC,GACzB,MAAMC,EAAML,EAASM,KAAKF,GAC1B,OAAOC,EAAIE,SAAS,YAAcF,EAAIG,SAAS,MACjD,CCLM,SAAUC,EACdC,EACAC,EAAyB,IAEzB,MAAMC,UAAEA,EAAY,GAAMD,EAC1B,IAAKR,EAAWO,GACd,MAAM,IAAIG,UAAU,0BAEtB,GAAqB,IAAjBH,EAAMI,OACR,MAAM,IAAID,UAAU,2BAEtB,GAAwB,iBAAbH,EAAM,GACf,MAAM,IAAIG,UAAU,8BAEtB,GAAIH,EAAMI,OAASF,EACjB,MAAM,IAAIG,MAAM,wCAAwCH,IAE5D,CClBM,SAAUI,EACdC,EACAC,EACAP,EAAoC,CAAA,GAEpC,MAAMQ,OAAEA,GAAS,GAASR,EAC1B,GAAIQ,EAAQ,CACV,IAAIC,EAAM,EACNC,EAAOJ,EAAMH,OAAS,EACtBQ,EAAS,EACb,KAAOD,EAAOD,EAAM,GAElB,GADAE,EAASF,GAAQC,EAAOD,GAAQ,GAC5BH,EAAMK,GAAUJ,EAClBE,EAAME,MACD,MAAIL,EAAMK,GAAUJ,GAGzB,OAAOI,EAFPD,EAAOC,CAGT,CAGF,OAAIF,EAAMH,EAAMH,OAA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