var diffstudio;
/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/constants.ts":
/*!************************************************************************************************!*\
  !*** ./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/constants.ts ***!
  \************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   FITTING_UI: () => (/* binding */ FITTING_UI),
/* harmony export */   GRID_SIZE: () => (/* binding */ GRID_SIZE),
/* harmony export */   HELP_LINK: () => (/* binding */ HELP_LINK),
/* harmony export */   INDICES: () => (/* binding */ INDICES),
/* harmony export */   LOSS: () => (/* binding */ LOSS),
/* harmony export */   LOSS_FUNC_CHART_OPTS: () => (/* binding */ LOSS_FUNC_CHART_OPTS),
/* harmony export */   METHOD: () => (/* binding */ METHOD),
/* harmony export */   MIN_RADAR_COLS_COUNT: () => (/* binding */ MIN_RADAR_COLS_COUNT),
/* harmony export */   NAME: () => (/* binding */ NAME),
/* harmony export */   SIZE: () => (/* binding */ SIZE),
/* harmony export */   STARTING_HELP: () => (/* binding */ STARTING_HELP),
/* harmony export */   TARGET_DATAFRAME_INFO: () => (/* binding */ TARGET_DATAFRAME_INFO),
/* harmony export */   TIMEOUT: () => (/* binding */ TIMEOUT),
/* harmony export */   TITLE: () => (/* binding */ TITLE),
/* harmony export */   lossTooltip: () => (/* binding */ lossTooltip),
/* harmony export */   methodTooltip: () => (/* binding */ methodTooltip)
/* harmony export */ });
/* eslint-disable max-len */
// Specific optimization constants
var METHOD;
(function (METHOD) {
    METHOD["NELDER_MEAD"] = "Nelder-Mead";
    METHOD["GRAD_DESC"] = "Gradient descent";
})(METHOD || (METHOD = {}));
;
const methodTooltip = new Map([
    [METHOD.NELDER_MEAD, 'The Nelder-Mead method'],
    [METHOD.GRAD_DESC, 'The gradient descent method'],
]);
var LOSS;
(function (LOSS) {
    LOSS["MAD"] = "MAD";
    LOSS["RMSE"] = "RMSE";
})(LOSS || (LOSS = {}));
;
const lossTooltip = new Map([
    [LOSS.MAD, 'Maximum absolute deviation'],
    [LOSS.RMSE, 'Root mean square error'],
]);
/** Grid elements sizes */
var GRID_SIZE;
(function (GRID_SIZE) {
    GRID_SIZE[GRID_SIZE["LOSS_COL_WIDTH"] = 60] = "LOSS_COL_WIDTH";
    GRID_SIZE[GRID_SIZE["ROW_HEIGHT"] = 280] = "ROW_HEIGHT";
    GRID_SIZE[GRID_SIZE["LOSS_GRAPH_WIDTH"] = 320] = "LOSS_GRAPH_WIDTH";
    GRID_SIZE[GRID_SIZE["GOF_VIEWER_WIDTH"] = 320] = "GOF_VIEWER_WIDTH";
    GRID_SIZE[GRID_SIZE["RADAR_WIDTH"] = 280] = "RADAR_WIDTH";
    GRID_SIZE[GRID_SIZE["BAR_HEIGHT"] = 100] = "BAR_HEIGHT";
})(GRID_SIZE || (GRID_SIZE = {}));
/** UI titles */
var TITLE;
(function (TITLE) {
    TITLE["ITER"] = "Iteration";
    TITLE["LOSS"] = "Loss";
    TITLE["LOSS_GRAPH"] = "Fitting profile";
    TITLE["TARGET"] = "Target";
    TITLE["FIT"] = "Fit";
    TITLE["METHOD"] = "method";
    TITLE["VALUE"] = "Value";
    TITLE["OBJECTIVE"] = "Target";
    TITLE["SAMPLES"] = "samples";
    TITLE["ID"] = "id";
    TITLE["OBTAINED"] = "Simulation";
    TITLE["LOSS_LOW"] = "loss";
    TITLE["SIMILARITY"] = "similarity";
})(TITLE || (TITLE = {}));
;
/** Items for the fitting help */
var HELP_ITEMS;
(function (HELP_ITEMS) {
    HELP_ITEMS["GOAL"] = "`Goal`";
    HELP_ITEMS["FIT"] = "`Fit`";
    HELP_ITEMS["MIN"] = "`min`";
    HELP_ITEMS["MAX"] = "`max`";
    HELP_ITEMS["TARGET"] = "`Target`";
    HELP_ITEMS["METHOD"] = "`method`";
    HELP_ITEMS["CONTEXT"] = "`Context Panel (F4)`";
    HELP_ITEMS["SAMPLES"] = "`samples`";
    HELP_ITEMS["LOSS"] = "`loss`";
    HELP_ITEMS["SIMILARITY"] = "`similarity`";
})(HELP_ITEMS || (HELP_ITEMS = {}));
;
var TIMEOUT;
(function (TIMEOUT) {
    TIMEOUT[TIMEOUT["MS_TO_SLEEP"] = 10] = "MS_TO_SLEEP";
    TIMEOUT[TIMEOUT["STYLE_TIMEOUT"] = 3000] = "STYLE_TIMEOUT";
    TIMEOUT[TIMEOUT["RADAR"] = 200] = "RADAR";
})(TIMEOUT || (TIMEOUT = {}));
;
/** Fitting UI constants */
var FITTING_UI;
(function (FITTING_UI) {
    FITTING_UI[FITTING_UI["SIMILARITY_MIN"] = 0] = "SIMILARITY_MIN";
    FITTING_UI[FITTING_UI["SIMILARITY_MAX"] = 100] = "SIMILARITY_MAX";
    FITTING_UI[FITTING_UI["SIMILARITY_DEFAULT"] = 10] = "SIMILARITY_DEFAULT";
    FITTING_UI[FITTING_UI["SAMPLES"] = 10] = "SAMPLES";
})(FITTING_UI || (FITTING_UI = {}));
;
const HELP_LINK = 'https://datagrok.ai/help/compute/function-analysis#parameter-optimization';
/** Starting help markdown */
const STARTING_HELP = `# Fitting

Use fitting to solve an inverse problem: find input conditions leading to specified output constraints. 
It computes inputs minimizing deviation measured by [loss function](https://en.wikipedia.org/wiki/Loss_function).

1. In the ${HELP_ITEMS.FIT} block, use switchers to specify inputs to be found:
   * Set ${HELP_ITEMS.MIN} and ${HELP_ITEMS.MAX} values for each selected item. They define the variation range
   * Set values of all other inputs

2. Set output constraints in the ${HELP_ITEMS.TARGET} block:
   * Use switchers to specify target outputs
   * Set target value for each selected item

3. Choose ${HELP_ITEMS.METHOD}. Press <i class="grok-icon fal fa-cog"></i> to specify its settings.

4. Specify the loss function type (in the ${HELP_ITEMS.LOSS} field).

5. Enter the number of points to be found (in the ${HELP_ITEMS.SAMPLES} field).

6. Set the maximum relative deviation (%) in the ${HELP_ITEMS.SIMILARITY} field. It defines the threshold for determining whether fitted points are similar.

7. Press the "Run" icon <i class="fas fa-play"></i> on the top panel to perform fitting. You will get a
[grid](https://datagrok.ai/help/visualize/viewers/grid) containing 

   * loss function values
   * fitted inputs
   * viewers visualizing the goodness of fit:
   * [line chart](https://datagrok.ai/help/visualize/viewers/line-chart) showing the loss function minimization

8. Open ${HELP_ITEMS.CONTEXT}. You will get the function run corresponding to the selected grid row.

9. Press **?** on the top panel to learn more about 
[parameters optimization](${HELP_LINK}).

# Learn more

* [Parameters optimization](${HELP_LINK})
* [Nelder-Mead method](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method)`;
var INDICES;
(function (INDICES) {
    INDICES[INDICES["SINGLE_VAL"] = 0] = "SINGLE_VAL";
    INDICES[INDICES["SINGLE_CAT"] = 1] = "SINGLE_CAT";
    INDICES[INDICES["DOUBLE_VAL1"] = 0] = "DOUBLE_VAL1";
    INDICES[INDICES["DOUBLE_VAL2"] = 1] = "DOUBLE_VAL2";
    INDICES[INDICES["DOUBLE_CAT"] = 2] = "DOUBLE_CAT";
    INDICES[INDICES["DIFF_STUDIO_OUTPUT"] = 0] = "DIFF_STUDIO_OUTPUT";
    INDICES[INDICES["SCALAR_VALS_COL"] = 1] = "SCALAR_VALS_COL";
    INDICES[INDICES["OLIVE"] = 8] = "OLIVE";
    INDICES[INDICES["LIGHT_OLIVE"] = 16] = "LIGHT_OLIVE";
    INDICES[INDICES["GREY"] = 7] = "GREY";
    INDICES[INDICES["LIGHT_GREY"] = 15] = "LIGHT_GREY";
    INDICES[INDICES["BLUE"] = 0] = "BLUE";
    INDICES[INDICES["ORANGE"] = 1] = "ORANGE";
})(INDICES || (INDICES = {}));
;
var NAME;
(function (NAME) {
    NAME["CATEGORY"] = "__Category__";
    NAME["SIZE"] = "__Size__";
    NAME["SIMULATION"] = "Simulation";
    NAME["TARGET"] = "Target";
    NAME["SCALARS"] = "Scalars";
    NAME["NULL"] = "Null";
})(NAME || (NAME = {}));
;
var SIZE;
(function (SIZE) {
    SIZE[SIZE["LINE_CHART_LINE_WIDTH"] = 2] = "LINE_CHART_LINE_WIDTH";
    SIZE[SIZE["SIMULATION"] = 1] = "SIMULATION";
    SIZE[SIZE["TARGET"] = 2] = "TARGET";
    SIZE[SIZE["MIN_MARKER"] = 1] = "MIN_MARKER";
    SIZE[SIZE["MAX_MARKER"] = 7] = "MAX_MARKER";
    SIZE[SIZE["LIGHTER_PERC"] = 50] = "LIGHTER_PERC";
})(SIZE || (SIZE = {}));
;
/** Info panel content */
const TARGET_DATAFRAME_INFO = `1. Set a dataframe with function(s) values

2. Select a column with the independent variable in the **argument** field

3. Specify one or more target columns with the dependent variable(s) in the **functions** field`;
/** Loss function line chart options */
const LOSS_FUNC_CHART_OPTS = {
    showYAxis: true,
    showXAxis: true,
    showXSelector: true,
    showYSelectors: true,
    lineColoringType: 'custom',
    lineColor: 4288600805,
    markerColor: 4288600805,
};
const MIN_RADAR_COLS_COUNT = 4;


/***/ }),

/***/ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/defs.ts":
/*!*******************************************************************************************************!*\
  !*** ./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/defs.ts ***!
  \*******************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ARG_COL_IDX: () => (/* binding */ ARG_COL_IDX),
/* harmony export */   ARG_IDX: () => (/* binding */ ARG_IDX),
/* harmony export */   ARG_INP_COUNT: () => (/* binding */ ARG_INP_COUNT),
/* harmony export */   DEFAULT_SET_VAL: () => (/* binding */ DEFAULT_SET_VAL),
/* harmony export */   MIN_TARGET_COLS_COUNT: () => (/* binding */ MIN_TARGET_COLS_COUNT),
/* harmony export */   MIN_WORKERS_COUNT: () => (/* binding */ MIN_WORKERS_COUNT),
/* harmony export */   NO_ERRORS: () => (/* binding */ NO_ERRORS),
/* harmony export */   RESULT_CODE: () => (/* binding */ RESULT_CODE),
/* harmony export */   WORKERS_COUNT_DOWNSHIFT: () => (/* binding */ WORKERS_COUNT_DOWNSHIFT)
/* harmony export */ });
const ARG_IDX = 0;
const NO_ERRORS = 'Success';
const DEFAULT_SET_VAL = 0;
const MIN_TARGET_COLS_COUNT = 2;
const ARG_INP_COUNT = 3;
const ARG_COL_IDX = 0;
const MIN_WORKERS_COUNT = 1;
const WORKERS_COUNT_DOWNSHIFT = 2;
var RESULT_CODE;
(function (RESULT_CODE) {
    RESULT_CODE[RESULT_CODE["SUCCEED"] = 0] = "SUCCEED";
    RESULT_CODE[RESULT_CODE["FAILED"] = 1] = "FAILED";
})(RESULT_CODE || (RESULT_CODE = {}));
;


/***/ }),

/***/ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/fitting-utils.ts":
/*!****************************************************************************************************************!*\
  !*** ./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/fitting-utils.ts ***!
  \****************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   fit: () => (/* binding */ fit),
/* harmony export */   getBatches: () => (/* binding */ getBatches),
/* harmony export */   isWorkerApplicable: () => (/* binding */ isWorkerApplicable),
/* harmony export */   mad: () => (/* binding */ mad),
/* harmony export */   rmse: () => (/* binding */ rmse)
/* harmony export */ });
/* harmony import */ var _datagrok_diff_grok__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @datagrok/diff-grok */ "./node_modules/@datagrok/diff-grok/index.ts");
/* harmony import */ var _optimizer_nelder_mead__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../optimizer-nelder-mead */ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/optimizer-nelder-mead.ts");
/* harmony import */ var _defs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./defs */ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/defs.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../constants */ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/constants.ts");
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/* eslint-disable valid-jsdoc */




/** Return true if in-worker fitting is applicable */
function isWorkerApplicable(ivp, ivpWW) {
    if ((ivp === undefined) || (ivpWW === undefined))
        return false;
    return (ivp.loop === null) && (ivp.updates === null) && (ivp.outputs === null);
}
/** Returns indices corresponding to the closest items */
function getIndices(targetArg, modelArg) {
    const modelCount = modelArg.length;
    const elemsCount = Math.min(targetArg.length, modelCount);
    const indices = new Uint32Array(elemsCount);
    let idxModel = 0;
    let difPrev = 0;
    let difCur = 0;
    for (let idxExp = 0; idxExp < elemsCount; ++idxExp) {
        while (true) {
            difPrev = Math.abs(modelArg[idxModel] - targetArg[idxExp]);
            ++idxModel;
            if (idxModel < modelCount) {
                difCur = Math.abs(modelArg[idxModel] - targetArg[idxExp]);
                if (difCur > difPrev) {
                    --idxModel;
                    break;
                }
                else
                    difPrev = difCur;
            }
            else {
                --idxModel;
                break;
            }
        }
        indices[idxExp] = idxModel;
    }
    return indices;
}
; // getIndices
/** Maximum absolute deviation */
function mad(targetArg, targetFuncs, scaleVals, modelArg, modelFuncs) {
    let res = 0;
    const dim = scaleVals.length;
    let localMax = 0;
    const indices = getIndices(targetArg, modelArg);
    const argsCount = indices.length;
    for (let i = 0; i < dim; ++i) {
        localMax = 0;
        for (let k = 0; k < argsCount; ++k)
            localMax = Math.max(localMax, Math.abs(targetFuncs[i][k] - modelFuncs[i][indices[k]]));
        res = Math.max(res, localMax / scaleVals[i]);
    }
    return res;
} // mad
/** Root mean square error */
function rmse(targetArg, targetFuncs, scaleVals, modelArg, modelFuncs) {
    let res = 0;
    const dim = scaleVals.length;
    let scale = 0;
    let sum = 0;
    let valsCount = 0;
    const indices = getIndices(targetArg, modelArg);
    const argsCount = indices.length;
    for (let i = 0; i < dim; ++i) {
        scale = scaleVals[i];
        sum = 0;
        for (let k = 0; k < argsCount; ++k) {
            sum += Math.pow(((targetFuncs[i][k] - modelFuncs[i][indices[k]]) / scale), 2);
            ++valsCount;
        }
        res += sum;
    }
    return Math.sqrt(res / valsCount);
} // rmse
/** Return points splitted into batches */
function getBatches(points, batchesCount) {
    const batches = new Array(batchesCount);
    const samplesCount = points.length;
    const chunkSize = Math.floor(samplesCount / batchesCount);
    let remainder = samplesCount % batchesCount;
    let start = 0;
    for (let i = 0; i < batchesCount; i++) {
        const extra = remainder > 0 ? 1 : 0;
        batches[i] = points.slice(start, start + chunkSize + extra);
        start += chunkSize + extra;
        --remainder;
    }
    return batches;
} // getBatches
/** Perform Neldel-Mead optimization */
function fit(task, start) {
    return __awaiter(this, void 0, void 0, function* () {
        const ivp = task.ivp2ww;
        const pipeline = task.pipeline;
        const inputSize = _defs__WEBPACK_IMPORTED_MODULE_2__.ARG_INP_COUNT + ivp.deqsCount + ivp.paramNames.length;
        const ivpInputVals = new Float64Array(inputSize);
        const ivpInputNames = task.nonParamNames.concat(ivp.paramNames);
        const funcNames = task.outputNames;
        //task.nonParamNames.slice(ARG_INP_COUNT - 1);
        let idx = 0;
        let cur = 0;
        for (const name of ivpInputNames) {
            cur = task.fixedInputsNames.indexOf(name);
            if (cur > -1)
                ivpInputVals[idx] = task.fixedInputsVals[cur];
            else {
                cur = task.variedInputNames.indexOf(name);
                ivpInputVals[idx] = start[cur];
            }
            ++idx;
        }
        const inpIndex = task.variedInputNames.map((name) => ivpInputNames.indexOf(name));
        const outIndex = task.targetNames.slice(1).map((name) => {
            const idx = funcNames.indexOf(name);
            if (idx < 0)
                throw new Error(`Inconsistent target dataframe: no ${name} column in the model's output.`);
            return idx;
        });
        const dim = start.length;
        const targetArgVals = task.targetVals[0];
        const targetFuncVals = task.targetVals.slice(1);
        const scaleVals = task.scaleVals.slice(1);
        const metric = (task.loss == _constants__WEBPACK_IMPORTED_MODULE_3__.LOSS.MAD) ? mad : rmse;
        let solution;
        const costFunc = (x) => __awaiter(this, void 0, void 0, function* () {
            for (let i = 0; i < dim; ++i)
                ivpInputVals[inpIndex[i]] = x[i];
            //solution = solveIvp(ivp, ivpInputVals);
            solution = (0,_datagrok_diff_grok__WEBPACK_IMPORTED_MODULE_0__.applyPipeline)(pipeline, ivp, ivpInputVals);
            return metric(targetArgVals, targetFuncVals, scaleVals, solution[_defs__WEBPACK_IMPORTED_MODULE_2__.ARG_COL_IDX], outIndex.map((idx) => solution[idx]));
        });
        const vec = new Float32Array(dim);
        for (let i = 0; i < dim; ++i)
            vec[i] = task.variedInpMin[i] + Math.random() * (task.variedInpMax[i] - task.variedInpMin[i]);
        costFunc(vec);
        const settings = new Map(task.settingNames.map((name, idx) => [name, task.settingVals[idx]]));
        const res = yield (0,_optimizer_nelder_mead__WEBPACK_IMPORTED_MODULE_1__.optimizeNM)(costFunc, start, settings, task.variedInpMin, task.variedInpMax);
        return res;
    });
} // fit


/***/ }),

/***/ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/workers/basic.ts":
/*!****************************************************************************************************************!*\
  !*** ./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/workers/basic.ts ***!
  \****************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _fitting_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../fitting-utils */ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/fitting-utils.ts");
/* harmony import */ var _defs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../defs */ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/defs.ts");
// Worker for optimization of parameters of Diff Studio model
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


onmessage = function (evt) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const task = evt.data.task;
            const startPoints = evt.data.startPoints;
            const pointsCount = startPoints.length;
            const fitRes = new Array(pointsCount);
            const extremums = [];
            for (let i = 0; i < pointsCount; ++i) {
                try {
                    extremums.push(yield (0,_fitting_utils__WEBPACK_IMPORTED_MODULE_0__.fit)(task, startPoints[i]));
                    fitRes[i] = _defs__WEBPACK_IMPORTED_MODULE_1__.NO_ERRORS;
                }
                catch (e) {
                    fitRes[i] = e instanceof Error ? e.message : 'Platform issue: in-webworker optimization failed';
                }
            }
            postMessage({ 'callResult': _defs__WEBPACK_IMPORTED_MODULE_1__.RESULT_CODE.SUCCEED, 'extremums': extremums, 'fitRes': fitRes });
        }
        catch (e) {
            postMessage({
                'callResult': _defs__WEBPACK_IMPORTED_MODULE_1__.RESULT_CODE.FAILED,
                'msg': e instanceof Error ? e.message : 'Platform issue: in-webworker optimization failed',
            });
        }
    });
};


/***/ }),

/***/ "./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/optimizer-nelder-mead.ts":
/*!************************************************************************************************************!*\
  !*** ./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/optimizer-nelder-mead.ts ***!
  \************************************************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   nelderMeadCaptions: () => (/* binding */ nelderMeadCaptions),
/* harmony export */   nelderMeadSettingsVals: () => (/* binding */ nelderMeadSettingsVals),
/* harmony export */   optimizeNM: () => (/* binding */ optimizeNM)
/* harmony export */ });
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/** The Nelder Mead seetings vals */
const nelderMeadSettingsVals = new Map([
    ['tolerance', { default: 0.000001, min: 1e-20, max: 1e-1 }],
    ['maxIter', { default: 50, min: 1, max: 10000 }],
    ['nonZeroParam', { default: 0.0001, min: 1e-20, max: 1e-1 }],
    ['initialScale', { default: 0.02, min: 1e-20, max: 1e-1 }],
    ['scaleReflaction', { default: 1, min: 1, max: 2 }],
    ['scaleExpansion', { default: 2, min: 1, max: 2 }],
    ['scaleContraction', { default: -0.5, min: -0.5, max: 0 }],
]);
/** Captions for the Nelder-Mead method settings */
const nelderMeadCaptions = new Map([
    ['tolerance', 'tolerance'],
    ['maxIter', 'max iterations'],
    ['nonZeroParam', 'non-zero param'],
    ['initialScale', 'initial scale'],
    ['scaleReflaction', 'scale reflection'],
    ['scaleExpansion', 'scale expansion'],
    ['scaleContraction', 'scale contraction'],
]);
function getInitialParams(objectiveFunc, settings, paramsInitial, restrictionsBottom, restrictionsTop) {
    return __awaiter(this, void 0, void 0, function* () {
        const dim = paramsInitial.length + 1;
        const dimParams = paramsInitial.length;
        const nonZeroParam = settings.get('nonZeroParam');
        const initScale = settings.get('initialScale');
        const optParams = new Array(dim);
        const pointObjectives = new Array(dim);
        for (let i = 0; i < dim; i++) {
            optParams[i] = new Float32Array(dimParams);
            for (let j = 0; j < dimParams; j++) {
                optParams[i][j] = paramsInitial[j];
                if (i != 0 && i - 1 === j) {
                    if (paramsInitial[j] == 0)
                        optParams[i][j] = nonZeroParam;
                    else
                        optParams[i][j] += initScale * paramsInitial[i - 1];
                    if (optParams[i][j] < restrictionsBottom[j])
                        optParams[i][j] = restrictionsBottom[j];
                    else if (optParams[i][j] > restrictionsTop[j])
                        optParams[i][j] = restrictionsTop[j];
                }
            }
            pointObjectives[i] = yield objectiveFunc(optParams[i]);
        }
        return [optParams, pointObjectives];
    });
}
function fillCentroid(centroid, dimParams, lastIndex, optParams) {
    for (let i = 0; i < dimParams; i++) {
        let val = 0;
        for (let j = 0; j < dimParams + 1; j++) {
            if (j != lastIndex)
                val += optParams[j][i];
        }
        centroid[i] = val / dimParams;
    }
}
function fillPoint(centroid, point, lastIndex, optParams, scale, dimParams, restrictionsBottom, restrictionsTop) {
    for (let i = 0; i < dimParams; i++) {
        point[i] = centroid[i];
        point[i] += scale * (centroid[i] - optParams[lastIndex][i]);
        if (point[i] < restrictionsBottom[i])
            point[i] = restrictionsBottom[i];
        else if (point[i] > restrictionsTop[i])
            point[i] = restrictionsTop[i];
    }
}
const optimizeNM = function (objectiveFunc, paramsInitial, settings, restrictionsBottom, restrictionsTop) {
    return __awaiter(this, void 0, void 0, function* () {
        // Settings initialization
        const tolerance = settings.get('tolerance');
        const maxIter = settings.get('maxIter');
        const scaleReflection = settings.get('scaleReflaction');
        const scaleExpansion = settings.get('scaleExpansion');
        const scaleContraction = settings.get('scaleContraction');
        const dim = paramsInitial.length + 1;
        const dimParams = paramsInitial.length;
        const [optParams, pointObjectives] = yield getInitialParams(objectiveFunc, settings, paramsInitial, restrictionsBottom, restrictionsTop);
        const indexes = new Array(dim);
        for (let i = 0; i < dim; i++)
            indexes[i] = i;
        const lastIndex = indexes.length - 1;
        let iteration = 0;
        let best = 0;
        let previousBest = 0;
        let noImprovment = 0;
        const centroid = new Float32Array(dimParams);
        const reflectionPoint = new Float32Array(dimParams);
        const expansionPoint = new Float32Array(dimParams);
        const contractionPoint = new Float32Array(dimParams);
        const costs = new Array(maxIter);
        if (dim > 1) {
            while (true) {
                indexes.sort((a, b) => {
                    return pointObjectives[a] - pointObjectives[b];
                });
                if (iteration > maxIter)
                    break;
                if (iteration == 0) {
                    best = pointObjectives[0];
                    previousBest = 2 * pointObjectives[indexes[0]];
                }
                costs[iteration] = best;
                ++iteration;
                best = pointObjectives[indexes[0]];
                if (previousBest - best > tolerance)
                    noImprovment = 0;
                else {
                    ++noImprovment;
                    if (noImprovment > 2 * dim)
                        break;
                }
                previousBest = best;
                //centroid
                fillCentroid(centroid, dimParams, indexes[lastIndex], optParams);
                // reflection
                fillPoint(centroid, reflectionPoint, indexes[lastIndex], optParams, scaleReflection, dimParams, restrictionsBottom, restrictionsTop);
                const reflectionScore = yield objectiveFunc(reflectionPoint);
                // expansion
                if (reflectionScore < pointObjectives[indexes[lastIndex]]) {
                    fillPoint(centroid, expansionPoint, indexes[lastIndex], optParams, scaleExpansion, dimParams, restrictionsBottom, restrictionsTop);
                    const expansionScore = yield objectiveFunc(expansionPoint);
                    if (expansionScore < reflectionScore) {
                        pointObjectives[indexes[lastIndex]] = expansionScore;
                        for (let i = 0; i < dimParams; i++)
                            optParams[indexes[lastIndex]][i] = expansionPoint[i];
                        continue;
                    }
                    else {
                        pointObjectives[indexes[lastIndex]] = reflectionScore;
                        for (let i = 0; i < dimParams; i++)
                            optParams[indexes[lastIndex]][i] = reflectionPoint[i];
                        continue;
                    }
                }
                // Contraction
                fillPoint(centroid, contractionPoint, indexes[lastIndex], optParams, scaleContraction, dimParams, restrictionsBottom, restrictionsTop);
                const contractionScore = yield objectiveFunc(contractionPoint);
                if (contractionScore < pointObjectives[indexes[lastIndex]]) {
                    pointObjectives[indexes[lastIndex]] = contractionScore;
                    for (let i = 0; i < dimParams; i++)
                        optParams[indexes[lastIndex]][i] = contractionPoint[i];
                    continue;
                }
                break;
            }
            for (let i = iteration; i < maxIter; i++)
                costs[i] = pointObjectives[indexes[0]];
        }
        return {
            point: optParams[indexes[0]],
            cost: pointObjectives[indexes[0]],
            iterCosts: costs,
            iterCount: iteration - 1,
        };
    });
};


/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = __webpack_modules__;
/******/ 	
/******/ 	// the startup function
/******/ 	__webpack_require__.x = () => {
/******/ 		// Load entry module and return exports
/******/ 		// This entry module depends on other loaded chunks and execution need to be delayed
/******/ 		var __webpack_exports__ = __webpack_require__.O(undefined, ["vendors-node_modules_datagrok_diff-grok_index_ts"], () => (__webpack_require__("./node_modules/@datagrok-libraries/compute-utils/function-views/src/fitting/diff-studio/workers/basic.ts")))
/******/ 		__webpack_exports__ = __webpack_require__.O(__webpack_exports__);
/******/ 		return __webpack_exports__;
/******/ 	};
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/chunk loaded */
/******/ 	(() => {
/******/ 		var deferred = [];
/******/ 		__webpack_require__.O = (result, chunkIds, fn, priority) => {
/******/ 			if(chunkIds) {
/******/ 				priority = priority || 0;
/******/ 				for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];
/******/ 				deferred[i] = [chunkIds, fn, priority];
/******/ 				return;
/******/ 			}
/******/ 			var notFulfilled = Infinity;
/******/ 			for (var i = 0; i < deferred.length; i++) {
/******/ 				var [chunkIds, fn, priority] = deferred[i];
/******/ 				var fulfilled = true;
/******/ 				for (var j = 0; j < chunkIds.length; j++) {
/******/ 					if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {
/******/ 						chunkIds.splice(j--, 1);
/******/ 					} else {
/******/ 						fulfilled = false;
/******/ 						if(priority < notFulfilled) notFulfilled = priority;
/******/ 					}
/******/ 				}
/******/ 				if(fulfilled) {
/******/ 					deferred.splice(i--, 1)
/******/ 					var r = fn();
/******/ 					if (r !== undefined) result = r;
/******/ 				}
/******/ 			}
/******/ 			return result;
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/ensure chunk */
/******/ 	(() => {
/******/ 		__webpack_require__.f = {};
/******/ 		// This file contains only the entry chunk.
/******/ 		// The chunk loading function for additional chunks
/******/ 		__webpack_require__.e = (chunkId) => {
/******/ 			return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {
/******/ 				__webpack_require__.f[key](chunkId, promises);
/******/ 				return promises;
/******/ 			}, []));
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/get javascript chunk filename */
/******/ 	(() => {
/******/ 		// This function allow to reference async chunks and sibling chunks for the entrypoint
/******/ 		__webpack_require__.u = (chunkId) => {
/******/ 			// return url for filenames based on template
/******/ 			return "" + chunkId + ".js";
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/global */
/******/ 	(() => {
/******/ 		__webpack_require__.g = (function() {
/******/ 			if (typeof globalThis === 'object') return globalThis;
/******/ 			try {
/******/ 				return this || new Function('return this')();
/******/ 			} catch (e) {
/******/ 				if (typeof window === 'object') return window;
/******/ 			}
/******/ 		})();
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/publicPath */
/******/ 	(() => {
/******/ 		var scriptUrl;
/******/ 		if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
/******/ 		var document = __webpack_require__.g.document;
/******/ 		if (!scriptUrl && document) {
/******/ 			if (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT')
/******/ 				scriptUrl = document.currentScript.src;
/******/ 			if (!scriptUrl) {
/******/ 				var scripts = document.getElementsByTagName("script");
/******/ 				if(scripts.length) {
/******/ 					var i = scripts.length - 1;
/******/ 					while (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;
/******/ 				}
/******/ 			}
/******/ 		}
/******/ 		// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
/******/ 		// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
/******/ 		if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
/******/ 		scriptUrl = scriptUrl.replace(/^blob:/, "").replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
/******/ 		__webpack_require__.p = scriptUrl;
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/importScripts chunk loading */
/******/ 	(() => {
/******/ 		// no baseURI
/******/ 		
/******/ 		// object to store loaded chunks
/******/ 		// "1" means "already loaded"
/******/ 		var installedChunks = {
/******/ 			"vendors-node_modules_datagrok-libraries_compute-utils_function-views_src_fitting_diff-studio_-33bd18": 1
/******/ 		};
/******/ 		
/******/ 		// importScripts chunk loading
/******/ 		var installChunk = (data) => {
/******/ 			var [chunkIds, moreModules, runtime] = data;
/******/ 			for(var moduleId in moreModules) {
/******/ 				if(__webpack_require__.o(moreModules, moduleId)) {
/******/ 					__webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ 				}
/******/ 			}
/******/ 			if(runtime) runtime(__webpack_require__);
/******/ 			while(chunkIds.length)
/******/ 				installedChunks[chunkIds.pop()] = 1;
/******/ 			parentChunkLoadingFunction(data);
/******/ 		};
/******/ 		__webpack_require__.f.i = (chunkId, promises) => {
/******/ 			// "1" is the signal for "already loaded"
/******/ 			if(!installedChunks[chunkId]) {
/******/ 				if(true) { // all chunks have JS
/******/ 					importScripts(__webpack_require__.p + __webpack_require__.u(chunkId));
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 		
/******/ 		var chunkLoadingGlobal = self["webpackChunkdiffstudio"] = self["webpackChunkdiffstudio"] || [];
/******/ 		var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);
/******/ 		chunkLoadingGlobal.push = installChunk;
/******/ 		
/******/ 		// no HMR
/******/ 		
/******/ 		// no HMR manifest
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/startup chunk dependencies */
/******/ 	(() => {
/******/ 		var next = __webpack_require__.x;
/******/ 		__webpack_require__.x = () => {
/******/ 			return __webpack_require__.e("vendors-node_modules_datagrok_diff-grok_index_ts").then(next);
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// run startup
/******/ 	var __webpack_exports__ = __webpack_require__.x();
/******/ 	diffstudio = __webpack_exports__;
/******/ 	
/******/ })()
;
//# sourceMappingURL=vendors-node_modules_datagrok-libraries_compute-utils_function-views_src_fitting_diff-studio_-33bd18.js.map