@datagrok/compute 1.34.1 → 1.34.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/package.json +2 -2
package/dist/package.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var compute;(()=>{var t={933:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/pipeline-view.css"],names:[],mappings:"AAAA;EACE;AACF;;AAEA;EACE,oBAAoB;EACpB,gBAAgB;EAChB,mBAAmB;EACnB,qBAAqB;AACvB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,oBAAoB;AACtB;;AAEA;EACE;AACF",sourcesContent:[".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}"],sourceRoot:""}]);const a=r},362:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/rich-function-view.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,gBAAgB;AACpB;;AAEA;IACI,eAAe;AACnB;;AAEA;IACI,mBAAmB;IACnB,yBAAyB;AAC7B;;AAEA,oCAAoC;AACpC;;;;IAII,aAAa;AACjB;;AAEA,mDAAmD;AACnD;IACI,gBAAgB;AACpB;;AAEA,+DAA+D;AAC/D;IACI,gBAAgB;AACpB;;AAEA,+CAA+C;AAC/C;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;AACA;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,QAAQ;IACR,yBAAyB;AAC7B;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,yBAAyB;IACzB,YAAY;AAChB;;AAEA;IACI,kBAAkB;IAClB,mBAAmB;AACvB;;AAEA;IACI,gBAAgB;IAChB,uCAAuC;AAC3C;;AAEA;IACI,+BAA+B;AACnC;;AAEA;IACI,WAAW;AACf",sourcesContent:[".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}"],sourceRoot:""}]);const a=r},993:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/sens-analysis.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,eAAe;AACnB;;AAEA;IACI,SAAS;IACT,SAAS;IACT,kBAAkB;AACtB;;AAEA;IACI,YAAY;AAChB;;AAEA;IACI,iBAAiB;AACrB",sourcesContent:[".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}"],sourceRoot:""}]);const a=r},847:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,'.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}',"",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/model-catalog/css/model-card.css"],names:[],mappings:"AAAA;IACI,YAAY;IACZ,WAAW;IACX,iBAAiB;IACjB,cAAc;AAClB;;AAEA;IACI,gBAAgB;IAChB,mBAAmB;IACnB,oBAAoB;IACpB,mBAAmB;AACvB;;AAEA;IACI,cAAc;IACd,mBAAmB;IACnB,aAAa;IACb,SAAS;IACT,YAAY;AAChB;;AAEA;IACI,6BAA6B;AACjC;;AAEA;IACI,WAAW;IACX,YAAY;IACZ,iBAAiB;AACrB;;AAEA;IACI,gBAAgB;AACpB;;AAEA;IACI,gBAAgB;IAChB,kBAAkB;IAClB,oBAAoB;IACpB,aAAa;IACb,cAAc;AAClB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,UAAU;IACV,SAAS;IACT,mBAAmB;IACnB,qBAAqB;IACrB,+BAA+B;IAC/B,kBAAkB;IAClB,sBAAsB;IACtB,4BAA4B;AAChC;;AAEA;IACI,kBAAkB;IAClB,QAAQ;IACR,OAAO;IACP,SAAS;IACT,MAAM;IACN,aAAa;IACb,mBAAmB;IACnB,uBAAuB;IACvB,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;AACnB;;AAEA;IACI,oBAAoB;AACxB;;AAEA;IACI,mBAAmB;AACvB",sourcesContent:['.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}'],sourceRoot:""}]);const a=r},911:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/file-input.css"],names:[],mappings:"AAAA;EACE,kBAAkB;AACpB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,gCAAgC;EAChC,gCAAgC;EAChC,oBAAoB;AACtB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,oBAAoB;AACtB",sourcesContent:[".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n"],sourceRoot:""}]);const a=r},703:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,"","",{version:3,sources:[],names:[],mappings:"",sourceRoot:""}]);const a=r},565:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/history-panel.css"],names:[],mappings:"AAAA;IACI,YAAY;AAChB;;AAEA;IACI,oBAAoB;IACpB,YAAY;AAChB;;AAEA;IACI,aAAa;AACjB;;AAEA;IACI,aAAa;IACb,uBAAuB;AAC3B;;AAEA;IACI,eAAe;IACf,YAAY;IACZ,8BAA8B;AAClC;;AAEA;IACI,6BAA6B;IAC7B,gBAAgB;AACpB;;AAEA;IACI,kBAAkB;AACtB;;AAEA;IACI,kBAAkB;IAClB,oBAAoB;AACxB;;AAEA;IACI,oBAAoB;IACpB,gBAAgB;AACpB",sourcesContent:[".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n"],sourceRoot:""}]);const a=r},314:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",i=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),i&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),i&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,i,o,s){"string"==typeof t&&(t=[[null,t,void 0]]);var r={};if(i)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(r[l]=!0)}for(var u=0;u<t.length;u++){var c=[].concat(t[u]);i&&r[c[0]]||(void 0!==s&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=s),n&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=n):c[2]=n),o&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=o):c[4]="".concat(o)),e.push(c))}},e}},354:t=>{"use strict";t.exports=function(t){var e=t[1],n=t[3];if(!n)return e;if("function"==typeof btoa){var i=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),o="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(i),s="/*# ".concat(o," */");return[e].concat([s]).join("\n")}return[e].join("\n")}},826:function(t){t.exports=function(){"use strict";var t="minute",e=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(i,o,s){var r=o.prototype;s.utc=function(t){return new o({date:t,utc:!0,args:arguments})},r.utc=function(e){var n=s(this.toDate(),{locale:this.$L,utc:!0});return e?n.add(this.utcOffset(),t):n},r.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var a=r.parse;r.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),a.call(this,t)};var l=r.init;r.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else l.call(this)};var u=r.utcOffset;r.utcOffset=function(i,o){var s=this.$utils().u;if(s(i))return this.$u?0:s(this.$offset)?u.call(this):this.$offset;if("string"==typeof i&&(i=function(t){void 0===t&&(t="");var i=t.match(e);if(!i)return null;var o=(""+i[0]).match(n)||["-",0,0],s=o[0],r=60*+o[1]+ +o[2];return 0===r?0:"+"===s?r:-r}(i),null===i))return this;var r=Math.abs(i)<=16?60*i:i,a=this;if(o)return a.$offset=r,a.$u=0===i,a;if(0!==i){var l=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(r+l,t)).$offset=r,a.$x.$localOffset=l}else a=this.utc();return a};var c=r.format;r.format=function(t){var e=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,e)},r.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},r.isUTC=function(){return!!this.$u},r.toISOString=function(){return this.toDate().toISOString()},r.toString=function(){return this.toDate().toUTCString()};var d=r.toDate;r.toDate=function(t){return"s"===t&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var p=r.diff;r.diff=function(t,e,n){if(t&&this.$u===t.$u)return p.call(this,t,e,n);var i=this.local(),o=s(t).local();return p.call(i,o,e,n)}}}()},693:(t,e,n)=>{t=n.nmd(t);var i="__lodash_hash_undefined__",o=9007199254740991,s="[object Arguments]",r="[object Boolean]",a="[object Date]",l="[object Function]",u="[object GeneratorFunction]",c="[object Map]",d="[object Number]",p="[object Object]",h="[object Promise]",f="[object RegExp]",m="[object Set]",v="[object String]",g="[object Symbol]",y="[object WeakMap]",b="[object ArrayBuffer]",A="[object DataView]",C="[object Float32Array]",w="[object Float64Array]",I="[object Int8Array]",T="[object Int16Array]",E="[object Int32Array]",x="[object Uint8Array]",R="[object Uint8ClampedArray]",S="[object Uint16Array]",O="[object Uint32Array]",P=/\w*$/,F=/^\[object .+?Constructor\]$/,_=/^(?:0|[1-9]\d*)$/,k={};k[s]=k["[object Array]"]=k[b]=k[A]=k[r]=k[a]=k[C]=k[w]=k[I]=k[T]=k[E]=k[c]=k[d]=k[p]=k[f]=k[m]=k[v]=k[g]=k[x]=k[R]=k[S]=k[O]=!0,k["[object Error]"]=k[l]=k[y]=!1;var M="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,B="object"==typeof self&&self&&self.Object===Object&&self,L=M||B||Function("return this")(),D=e&&!e.nodeType&&e,N=D&&t&&!t.nodeType&&t,V=N&&N.exports===D;function j(t,e){return t.set(e[0],e[1]),t}function $(t,e){return t.add(e),t}function Y(t,e,n,i){var o=-1,s=t?t.length:0;for(i&&s&&(n=t[++o]);++o<s;)n=e(n,t[o],o,t);return n}function H(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(t){}return e}function U(t){var e=-1,n=Array(t.size);return t.forEach((function(t,i){n[++e]=[i,t]})),n}function W(t,e){return function(n){return t(e(n))}}function G(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}var z,J=Array.prototype,q=Function.prototype,K=Object.prototype,Z=L["__core-js_shared__"],X=(z=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+z:"",Q=q.toString,tt=K.hasOwnProperty,et=K.toString,nt=RegExp("^"+Q.call(tt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),it=V?L.Buffer:void 0,ot=L.Symbol,st=L.Uint8Array,rt=W(Object.getPrototypeOf,Object),at=Object.create,lt=K.propertyIsEnumerable,ut=J.splice,ct=Object.getOwnPropertySymbols,dt=it?it.isBuffer:void 0,pt=W(Object.keys,Object),ht=Lt(L,"DataView"),ft=Lt(L,"Map"),mt=Lt(L,"Promise"),vt=Lt(L,"Set"),gt=Lt(L,"WeakMap"),yt=Lt(Object,"create"),bt=$t(ht),At=$t(ft),Ct=$t(mt),wt=$t(vt),It=$t(gt),Tt=ot?ot.prototype:void 0,Et=Tt?Tt.valueOf:void 0;function xt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Rt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function St(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Ot(t){this.__data__=new Rt(t)}function Pt(t,e,n){var i=t[e];tt.call(t,e)&&Yt(i,n)&&(void 0!==n||e in t)||(t[e]=n)}function Ft(t,e){for(var n=t.length;n--;)if(Yt(t[n][0],e))return n;return-1}function _t(t,e,n,i,o,h,y){var F;if(i&&(F=h?i(t,o,h,y):i(t)),void 0!==F)return F;if(!zt(t))return t;var _=Ht(t);if(_){if(F=function(t){var e=t.length,n=t.constructor(e);return e&&"string"==typeof t[0]&&tt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!e)return function(t,e){var n=-1,i=t.length;for(e||(e=Array(i));++n<i;)e[n]=t[n];return e}(t,F)}else{var M=Nt(t),B=M==l||M==u;if(Wt(t))return function(t,e){if(e)return t.slice();var n=new t.constructor(t.length);return t.copy(n),n}(t,e);if(M==p||M==s||B&&!h){if(H(t))return h?t:{};if(F=function(t){return"function"!=typeof t.constructor||jt(t)?{}:zt(e=rt(t))?at(e):{};var e}(B?{}:t),!e)return function(t,e){return Mt(t,Dt(t),e)}(t,function(t,e){return t&&Mt(e,Jt(e),t)}(F,t))}else{if(!k[M])return h?t:{};F=function(t,e,n,i){var o,s=t.constructor;switch(e){case b:return kt(t);case r:case a:return new s(+t);case A:return function(t,e){var n=e?kt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,i);case C:case w:case I:case T:case E:case x:case R:case S:case O:return function(t,e){var n=e?kt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}(t,i);case c:return function(t,e,n){return Y(e?n(U(t),!0):U(t),j,new t.constructor)}(t,i,n);case d:case v:return new s(t);case f:return function(t){var e=new t.constructor(t.source,P.exec(t));return e.lastIndex=t.lastIndex,e}(t);case m:return function(t,e,n){return Y(e?n(G(t),!0):G(t),$,new t.constructor)}(t,i,n);case g:return o=t,Et?Object(Et.call(o)):{}}}(t,M,_t,e)}}y||(y=new Ot);var L=y.get(t);if(L)return L;if(y.set(t,F),!_)var D=n?function(t){return function(t,e,n){var i=e(t);return Ht(t)?i:function(t,e){for(var n=-1,i=e.length,o=t.length;++n<i;)t[o+n]=e[n];return t}(i,n(t))}(t,Jt,Dt)}(t):Jt(t);return function(t,e){for(var n=-1,i=t?t.length:0;++n<i&&!1!==e(t[n],n););}(D||t,(function(o,s){D&&(o=t[s=o]),Pt(F,s,_t(o,e,n,i,s,t,y))})),F}function kt(t){var e=new t.constructor(t.byteLength);return new st(e).set(new st(t)),e}function Mt(t,e,n,i){n||(n={});for(var o=-1,s=e.length;++o<s;){var r=e[o],a=i?i(n[r],t[r],r,n,t):void 0;Pt(n,r,void 0===a?t[r]:a)}return n}function Bt(t,e){var n,i,o=t.__data__;return("string"==(i=typeof(n=e))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof e?"string":"hash"]:o.map}function Lt(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return function(t){return!(!zt(t)||(e=t,X&&X in e))&&(Gt(t)||H(t)?nt:F).test($t(t));var e}(n)?n:void 0}xt.prototype.clear=function(){this.__data__=yt?yt(null):{}},xt.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},xt.prototype.get=function(t){var e=this.__data__;if(yt){var n=e[t];return n===i?void 0:n}return tt.call(e,t)?e[t]:void 0},xt.prototype.has=function(t){var e=this.__data__;return yt?void 0!==e[t]:tt.call(e,t)},xt.prototype.set=function(t,e){return this.__data__[t]=yt&&void 0===e?i:e,this},Rt.prototype.clear=function(){this.__data__=[]},Rt.prototype.delete=function(t){var e=this.__data__,n=Ft(e,t);return!(n<0||(n==e.length-1?e.pop():ut.call(e,n,1),0))},Rt.prototype.get=function(t){var e=this.__data__,n=Ft(e,t);return n<0?void 0:e[n][1]},Rt.prototype.has=function(t){return Ft(this.__data__,t)>-1},Rt.prototype.set=function(t,e){var n=this.__data__,i=Ft(n,t);return i<0?n.push([t,e]):n[i][1]=e,this},St.prototype.clear=function(){this.__data__={hash:new xt,map:new(ft||Rt),string:new xt}},St.prototype.delete=function(t){return Bt(this,t).delete(t)},St.prototype.get=function(t){return Bt(this,t).get(t)},St.prototype.has=function(t){return Bt(this,t).has(t)},St.prototype.set=function(t,e){return Bt(this,t).set(t,e),this},Ot.prototype.clear=function(){this.__data__=new Rt},Ot.prototype.delete=function(t){return this.__data__.delete(t)},Ot.prototype.get=function(t){return this.__data__.get(t)},Ot.prototype.has=function(t){return this.__data__.has(t)},Ot.prototype.set=function(t,e){var n=this.__data__;if(n instanceof Rt){var i=n.__data__;if(!ft||i.length<199)return i.push([t,e]),this;n=this.__data__=new St(i)}return n.set(t,e),this};var Dt=ct?W(ct,Object):function(){return[]},Nt=function(t){return et.call(t)};function Vt(t,e){return!!(e=null==e?o:e)&&("number"==typeof t||_.test(t))&&t>-1&&t%1==0&&t<e}function jt(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||K)}function $t(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Yt(t,e){return t===e||t!=t&&e!=e}(ht&&Nt(new ht(new ArrayBuffer(1)))!=A||ft&&Nt(new ft)!=c||mt&&Nt(mt.resolve())!=h||vt&&Nt(new vt)!=m||gt&&Nt(new gt)!=y)&&(Nt=function(t){var e=et.call(t),n=e==p?t.constructor:void 0,i=n?$t(n):void 0;if(i)switch(i){case bt:return A;case At:return c;case Ct:return h;case wt:return m;case It:return y}return e});var Ht=Array.isArray;function Ut(t){return null!=t&&function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}(t.length)&&!Gt(t)}var Wt=dt||function(){return!1};function Gt(t){var e=zt(t)?et.call(t):"";return e==l||e==u}function zt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Jt(t){return Ut(t)?function(t,e){var n=Ht(t)||function(t){return function(t){return function(t){return!!t&&"object"==typeof t}(t)&&Ut(t)}(t)&&tt.call(t,"callee")&&(!lt.call(t,"callee")||et.call(t)==s)}(t)?function(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}(t.length,String):[],i=n.length,o=!!i;for(var r in t)!e&&!tt.call(t,r)||o&&("length"==r||Vt(r,i))||n.push(r);return n}(t):function(t){if(!jt(t))return pt(t);var e=[];for(var n in Object(t))tt.call(t,n)&&"constructor"!=n&&e.push(n);return e}(t)}t.exports=function(t,e){return _t(t,!0,!0,e)}},72:t=>{"use strict";var e=[];function n(t){for(var n=-1,i=0;i<e.length;i++)if(e[i].identifier===t){n=i;break}return n}function i(t,i){for(var s={},r=[],a=0;a<t.length;a++){var l=t[a],u=i.base?l[0]+i.base:l[0],c=s[u]||0,d="".concat(u," ").concat(c);s[u]=c+1;var p=n(d),h={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==p)e[p].references++,e[p].updater(h);else{var f=o(h,i);i.byIndex=a,e.splice(a,0,{identifier:d,updater:f,references:1})}r.push(d)}return r}function o(t,e){var n=e.domAPI(e);return n.update(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;n.update(t=e)}else n.remove()}}t.exports=function(t,o){var s=i(t=t||[],o=o||{});return function(t){t=t||[];for(var r=0;r<s.length;r++){var a=n(s[r]);e[a].references--}for(var l=i(t,o),u=0;u<s.length;u++){var c=n(s[u]);0===e[c].references&&(e[c].updater(),e.splice(c,1))}s=l}}},659:t=>{"use strict";var e={};t.exports=function(t,n){var i=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");i.appendChild(n)}},540:t=>{"use strict";t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},56:(t,e,n)=>{"use strict";t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},825:t=>{"use strict";t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var i="";n.supports&&(i+="@supports (".concat(n.supports,") {")),n.media&&(i+="@media ".concat(n.media," {"));var o=void 0!==n.layer;o&&(i+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),i+=n.css,o&&(i+="}"),n.media&&(i+="}"),n.supports&&(i+="}");var s=n.sourceMap;s&&"undefined"!=typeof btoa&&(i+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),e.styleTagTransform(i,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},113:t=>{"use strict";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}},e={};function n(i){var o=e[i];if(void 0!==o)return o.exports;var s=e[i]={id:i,loaded:!1,exports:{}};return t[i].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var i in e)n.o(e,i)&&!n.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),n.nc=void 0;var i={};(()=>{"use strict";n.r(i),n.d(i,{AmbTempValidator:()=>hi,CustomCustomizer:()=>si,CustomDataUploader:()=>ii,CustomStringInput:()=>mi,CustomUploader:()=>oi,DesiredTempValidator:()=>di,HeatCapValidator:()=>fi,InitialTempValidator:()=>pi,ObjectCoolingSelector:()=>vi,OutliersSelection:()=>Xn,PipelineStepEditor:()=>ti,RichFunctionViewEditor:()=>Qn,SimTimeValidator:()=>ci,_package:()=>Kn,init:()=>ri,modelCatalog:()=>li,openModelFromFuncall:()=>Zn,renderRestPanel:()=>ei});const t=grok,e=ui,o=DG,s=rxjs.operators,r=$;var a=n.n(r);const l=()=>document.querySelector(".d4-balloon-container");class u extends o.JsViewer{constructor(){super()}onFrameAttached(t){this.render()}onTableAttached(){this.render()}render(){if(!this.dataFrame||this.dataFrame.rowCount<=0)return void(this.root.innerHTML="");const n=this.dataFrame,i="isOutlier",s="Rationale",r="Count",u="isConfirmed";n.columns.byName(i)||n.columns.add(o.Column.fromBitSet(i,o.BitSet.create(n.rowCount,(()=>!1)))),n.columns.byName(s)||n.columns.add(o.Column.fromStrings(s,Array.from({length:n.rowCount},(()=>""))));const c=()=>o.DataFrame.fromColumns([o.Column.fromStrings(s,[]),o.Column.fromInt32Array(r,new Int32Array([])),o.Column.fromStrings("Actions",[]),o.Column.fromBitSet(u,o.BitSet.create(0,(()=>!1)))]),d=o.Viewer.grid(c());d.root.style.width="100%",d.root.style.minWidth="230px",d.columns.setVisible([s,r,"Actions"]),this.root.append(e.divV([e.divV([d.root],{style:{height:"75%"}})],{style:{height:"100%"}}));const p=()=>{var t,e;if(!d.dataFrame)return;null===(t=n.col(i))||void 0===t||t.markers.assign("true",o.MARKER_TYPE.OUTLIER);const r=null===(e=d.dataFrame)||void 0===e?void 0:e.cell(d.dataFrame.rowCount-1,s).value;n.selection.getSelectedIndexes().forEach((t=>{n.col(i).set(t,!0,!1),n.col(s).set(t,r,!1)})),n.selection.setAll(!1),n.fireValuesChanged(),a()(l()).empty()},h=()=>{d.dataFrame&&(d.dataFrame.rows.removeAt(d.dataFrame.rowCount-1),n.selection.setAll(!1),a()(l()).empty())};d.onCellPrepare((t=>{var o,r,a;t.isTableCell&&("Actions"===t.gridColumn.name&&(t.gridColumn.cellType="html",t.style.element=e.divH([...(null===(o=t.grid.dataFrame)||void 0===o?void 0:o.get(u,t.gridRow))?[(a=null===(r=t.grid.dataFrame)||void 0===r?void 0:r.get(s,t.gridRow),e.div(e.icons.delete((()=>{for(let t=0;t<n.rowCount;t++)n.columns.byName(s).get(t)===a&&(n.columns.byName(s).set(t,"",!1),n.columns.byName(i).set(t,!1,!1));n.fireValuesChanged()}),"Remove the outliers group"),{style:{"text-align":"center",margin:"6px"}}))]:[e.div(e.iconFA("check",p,"Confirm the outliers"),{style:{"text-align":"center",margin:"6px"}}),e.div(e.iconFA("times",h,"Cancel the outliers"),{style:{"text-align":"center",margin:"6px"}})]])))})),d.onCellValueEdited.subscribe((t=>{var e,i;if(!d.dataFrame||t.gridColumn.name!==s)return;if(!d.dataFrame.columns.byName(u).get(t.gridRow))return;const o=new Set;for(let t=0;t<(null===(e=d.dataFrame)||void 0===e?void 0:e.rowCount);t++){const e=null===(i=d.dataFrame)||void 0===i?void 0:i.columns.byName(s).get(t);o.add(e)}for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e);""==i||o.has(i)||n.columns.byName(s).set(e,t.cell.value)}}));const f=()=>{if(n.columns.byName(s))for(let t=0;t<n.rowCount;t++)n.columns.byName(i).get(t)?""===n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"Manual",!1):""!==n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"",!1);const t={};if(n.columns.byName(s))for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e),o=t[i];""!=i&&(o?t[i]++:t[i]=1)}d.dataFrame=c(),d.columns.setVisible([s,r,"Actions"]),Object.keys(t).map((e=>{var n;null===(n=d.dataFrame)||void 0===n||n.rows.addNew([e,t[e],"",!0])}))};n.onDataChanged.subscribe(f),n.onSelectionChanged.subscribe((()=>{if(!d.dataFrame||!n.selection.trueCount)return;const i=l();if(i&&!a()(i).is(":empty")||t.shell.info(e.div([e.divText("Confirm selected points as outliers?"),e.divH([e.bigButton("Confirm",p),e.button("Cancel",h)])])),d.dataFrame.columns.byName(u).toList().some((t=>!1===t)))d.dataFrame.set(r,d.dataFrame.rowCount-1,n.selection.trueCount);else{const t=d.dataFrame.rows.addNew(["Manual",n.selection.trueCount,"",!1]);d.dataFrame.currentCell=d.dataFrame.cell(t.idx,s)}})),n.selection.setAll(!1),f()}}const c=rxjs,d=dayjs;var p=n.n(d);const h=wu;var f=n.n(h);const m={barchart:o.VIEWER.BAR_CHART,boxplot:o.VIEWER.BOX_PLOT,calendar:o.VIEWER.CALENDAR,corrplot:o.VIEWER.CORR_PLOT,densityplot:o.VIEWER.DENSITY_PLOT,filters:o.VIEWER.FILTERS,form:o.VIEWER.FORM,globe:o.VIEWER.GLOBE,googlemap:o.VIEWER.GOOGLE_MAP,grid:o.VIEWER.GRID,heatmap:o.VIEWER.HEAT_MAP,histogram:o.VIEWER.HISTOGRAM,linechart:o.VIEWER.LINE_CHART,markup:o.VIEWER.MARKUP,matrixplot:o.VIEWER.MATRIX_PLOT,networkdiagram:o.VIEWER.NETWORK_DIAGRAM,pcplot:o.VIEWER.PC_PLOT,piechart:o.VIEWER.PIE_CHART,scatterplot:o.VIEWER.SCATTER_PLOT,"3dscatterplot":o.VIEWER.SCATTER_PLOT_3D,shapemap:o.VIEWER.SHAPE_MAP,statistics:o.VIEWER.STATISTICS,tileviewer:o.VIEWER.TILE_VIEWER,timelines:o.VIEWER.TIMELINES,treemap:o.VIEWER.TREE_MAP,trellisplot:o.VIEWER.TRELLIS_PLOT,wordcloud:o.VIEWER.WORD_CLOUD},v="JsCardView",g="viewer",y="restrictedValues",b="editState";var A;!function(t){t.INPUT="Input",t.OUTPUT="Output"}(A||(A={}));const C="experimental",w="Run name",I="RunId";var T,E,x,R;(R=T||(T={})).HIDDEN="hidden",R.VISIBLE="visible",(x=E||(E={})).ENABLED="enabled",x.DISABLED="disabled";const S="ModelStorage",O="Source",P="Is favorite",F="Is complete",_="Delete",k="Author",M="Date",B="Title",L="Desc.",D="Tags";function N(t){return t&&t.root&&t.onInput}function V(t){return(null==t?void 0:t.setValidation)&&N(t)}function j(t){return(null==t?void 0:t.setDisabled)&&(null==t?void 0:t.setRestricted)&&(null==t?void 0:t.setRestrictedUnlocked)&&(null==t?void 0:t.setInconsistent)&&(null==t?void 0:t.setUserInput)&&N(t)}function Y(t){var e;return!(null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.length)&&!(null==t?void 0:t.pending)}function H(t,e){return{description:t,actions:e}}function U(t){if(null==t?void 0:t.errors)return t.errors.map((t=>t.description)).join("; ")}function W(t){var e,n,i;const o=t=>"string"==typeof t?H(t):t;return{errors:null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.map((t=>o(t))),warnings:null===(n=null==t?void 0:t.warnings)||void 0===n?void 0:n.map((t=>o(t))),notifications:null===(i=null==t?void 0:t.notifications)||void 0===i?void 0:i.map((t=>o(t)))}}function G(...t){var e,n,i,o,s;const r=[],a=[],l=[],u=[];let c={};for(const d of t)d&&(r.push(...null!==(e=d.errors)&&void 0!==e?e:[]),a.push(...null!==(n=d.warnings)&&void 0!==n?n:[]),l.push(...null!==(i=d.notifications)&&void 0!==i?i:[]),u.push(...null!==(o=d.revalidate)&&void 0!==o?o:[]),c=Object.assign(Object.assign({},c),null!==(s=d.context)&&void 0!==s?s:{}));return{errors:r,warnings:a,notifications:l,revalidate:u,context:c}}function z(t,n,i){if(i&&n){for(function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(n,i);i.firstChild&&i.removeChild(i.firstChild););const o=function(t){var n;const i=e.divV([],{style:{gap:"10px"}});for(const o of["errors","warnings","notifications"]){const s=t[o];if(null==s?void 0:s.length)for(const t of s){const s=J(o);s.style.marginRight="4px",i.appendChild(e.divV([e.divH([s,e.span([t.description])]),...(null!==(n=t.actions)&&void 0!==n?n:[]).map((t=>e.link(t.actionName,t.action,void 0,{style:{paddingLeft:"20px"}})))]))}}return i}(t);i.appendChild(o),i.showPopover()}}function J(t){let n;return"errors"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--red-3)"):"warnings"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--orange-2)"):"notifications"===t&&(n=e.iconFA("info-circle"),n.style.color="var(--blue-1)"),n&&(n.classList.remove("fal"),n.classList.add("far")),n}var q=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const K=t=>!Z(t)||!t.id,Z=t=>{try{return t.started}catch(t){return null}},X=(e,n)=>{var i,o,s,r,a,l,u;if(n===k)return null!==(o=null===(i=e.author)||void 0===i?void 0:i.friendlyName)&&void 0!==o?o:t.shell.user.friendlyName;const c=null!==(l=null!==(a=null!==(r=null!==(s=e[n])&&void 0!==s?s:e.inputs[n])&&void 0!==r?r:e.outputs[n])&&void 0!==a?a:e.options[n])&&void 0!==l?l:null;return null!==(u=null==c?void 0:c.toString())&&void 0!==u?u:""},Q=t=>t.options.mainParams?JSON.parse(t.options.mainParams):null;function tt(t){const e=t;return e.dart&&o.toJs(e.dart)instanceof o.InputBase}const et=t=>{const e=t.clone();t.options.forEach((n=>e.options[n]=t.options[n]));const n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e},nt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},it=(t,e)=>{t.addRow(["Parameter","Value","Units"]).font={bold:!0},e.forEach((e=>{t.addRow([e.caption,e.value,e.units])})),t.getColumn(1).width=1.2*Math.max(...e.map((t=>t.caption.toString().length)),9),t.getColumn(2).width=1.2*Math.max(...e.map((t=>t.value.toString().length)),5),t.getColumn(3).width=1.2*Math.max(...e.map((t=>t.units.toString().length)),5)};let ot=0;const st=(t,e,n,i)=>{const o=t.getColumn(null!=n?n:1).letter,s={name:`ID_${ot.toString()}`,ref:`${o}${null!=i?i:1}`,columns:e.columns.toList().map((t=>({name:t.name,filterButton:!1}))),rows:new Array(e.rowCount).fill(0).map(((t,n)=>[...e.row(n).cells].map((t=>t.value))))};t.addTable(s),t.columns.forEach((t=>{t.width=25,t.alignment={wrapText:!0}})),ot++},rt=(t,e,n,i,...s)=>q(void 0,[t,e,n,i,...s],void 0,(function*(t,e,n,i,s=0){yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const r=window.html2canvas,a=yield r(n,{logging:!1}),l=a.toDataURL("image/png"),u=t.addImage({base64:l,extension:"png"});e.addImage(u,{tl:{col:i,row:s},ext:{width:a.width,height:a.height}})}));function at(t,e,n){return q(this,void 0,void 0,(function*(){return"file"===t.propertyType&&n.getInput?n.getInput(t.name).value.arrayBuffer():e}))}function lt(t,e){return q(this,void 0,void 0,(function*(){return"file"===t?new File([e],""):e}))}var ut=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ct=t=>{switch(t){case"Today":return"started > -1d";case"Yesterday":return"started > -2d and started < -1d";case"Any time":return"";case"Last year":return"started > -2y and started < -1y";case"This year":return"started > -1y";case"Last month":return"started > -2m and started < -1m";case"This month":return"started > -1m";case"Last week":return"started > -2w and started < -1w";case"This week":return"started > -1w"}};var dt;!function(e){const n={},i=new o.LruCache;function s(e){return ut(this,arguments,void 0,(function*(e,i=!0){var o;const s=e.func.id,r=t.dapi.functions.include("package").allPackageVersions().find(s),a=i&&null!==(o=n[s])&&void 0!==o?o:yield r;n[s]||(n[s]=a),e.func=a}))}e.augmentCallWithFunc=s,e.loadChildRuns=function(e){return ut(this,void 0,void 0,(function*(){const n=yield t.dapi.functions.calls.allPackageVersions().find(e);yield s(n);const i=yield t.dapi.functions.calls.allPackageVersions().include("func").filter(`options.parentCallId="${e}"`).list();return yield Promise.all(i.map((t=>ut(this,void 0,void 0,(function*(){return s(t)}))))),{parentRun:n,childRuns:i}}))},e.loadRun=function(e){return ut(this,arguments,void 0,(function*(e,n=!1){const i=yield t.dapi.functions.calls.allPackageVersions().include("session.user, inputs, outputs").find(e);if(yield s(i),!n){const e=f()(i.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.outputs[t.name]));yield Promise.all(e.map((e=>ut(this,void 0,void 0,(function*(){return i.outputs[e.name]=yield t.dapi.tables.getTable(i.outputs[e.name]),Promise.resolve()})))));const n=f()(i.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.inputs[t.name]));yield Promise.all(n.map((e=>ut(this,void 0,void 0,(function*(){return i.inputs[e.name]=yield t.dapi.tables.getTable(i.inputs[e.name]),Promise.resolve()})))))}return i}))},e.saveRun=function(e){return ut(this,void 0,void 0,(function*(){let n=i.get("All users");n||(n=yield t.dapi.groups.find(o.Group.defaultGroupsIds["All users"]),i.set("All users",n));const s=et(e);K(s)&&(s.options.createdOn=p()().unix());const r=f()(s.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.outputs[t.name]));yield Promise.all(r.map((e=>ut(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.outputs[e.name]),yield t.dapi.permissions.grant(s.outputs[e.name].getTableInfo(),n,!1)})))));const a=f()(s.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.inputs[t.name]));return yield Promise.all(a.map((e=>ut(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.inputs[e.name]),yield t.dapi.permissions.grant(s.inputs[e.name].getTableInfo(),n,!1)}))))),yield t.dapi.functions.calls.allPackageVersions().save(s)}))},e.deleteRun=function(e){return ut(this,void 0,void 0,(function*(){e.options.isDeleted=!0,yield t.dapi.functions.calls.allPackageVersions().save(e)}))},e.pullRuns=function(e){return ut(this,arguments,void 0,(function*(e,n={},i={}){let o=`func.id="${e}"`;return o+=n.author?` and session.user.id="${n.author.id}"`:"",o+=n.date?ct(n.date):"",t.dapi.functions.calls.allPackageVersions().filter(o).include("session.user, options").list(i)}))},e.pullRunsByName=function(e){return ut(this,arguments,void 0,(function*(e,n=[],i={},r=[],a=!1){let l="";for(const t of n){const e=[];t.author&&e.push(`session.user.id="${t.author.id}"`),t.date&&e.push(ct(t.date)),t.text&&e.push(`((options.title like "${t.text}") or (options.annotation like "${t.text}"))`),t.includeDeleted||e.push('((options.isDeleted != "true") or (options.isDeleted = null))');const n=e.join(" and ");""!==n&&(l+=""===l?`(${n})`:` or (${n})`)}""!==l&&(l=` and (${l})`);const u=yield t.dapi.functions.calls.allPackageVersions().filter(`func.name="${e}"${l}`).include(`${r.join(",")}`).list(i);for(const t of u)yield s(t);if((r.includes("inputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.inputs[t.name]));for(const i of n)e.inputs[i.name]=yield t.dapi.tables.getTable(e.inputs[i.name])}if((r.includes("outputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.outputs[t.name]));for(const i of n)e.outputs[i.name]=yield t.dapi.tables.getTable(e.outputs[i.name])}return u}))}}(dt||(dt={}));var pt=n(72),ht=n.n(pt),ft=n(825),mt=n.n(ft),vt=n(659),gt=n.n(vt),yt=n(56),bt=n.n(yt),At=n(540),Ct=n.n(At),wt=n(113),It=n.n(wt),Tt=n(911),Et={};Et.styleTagTransform=It(),Et.setAttributes=bt(),Et.insert=gt().bind(null,"head"),Et.domAPI=mt(),Et.insertStyleElement=Ct(),ht()(Tt.A,Et),Tt.A&&Tt.A.locals&&Tt.A.locals;var xt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Rt="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";class St extends o.InputBase{get value(){return this.fileValue}set value(t){this.stringValue=(null==t?void 0:t.name)||"Drag-n-drop your file",this.fileValue=t,this.notify&&this.fireInput()}constructor(t="Drag-n-drop here",n=null,i=null,o=Rt){super(e.stringInput("Input file","",null).dart),this.initialText=t,this.initialValue=n,this.onValueChanged=i,this.fileType=o,this.uploadedFile$=new c.Subject,this.onFileUploaded=this.uploadedFile$,this.fileValue=null,this.isValid=new c.BehaviorSubject(!0),this.hiddenInput=document.createElement("input"),this.icon=e.iconFA("cloud-upload",(()=>this.hiddenInput.click())),this.subscribeOnEvents(),this.root.style.display="flex",this.isValid.subscribe((t=>{if(t){this.input.classList.remove("error"),this.input.classList.add("success");const t=e.iconFA("times",(()=>this.reset()),"Reset uploaded file");this.icon.replaceWith(t),this.icon=t}else{this.input.classList.remove("success"),this.input.classList.add("error");const t=e.iconFA("redo",(()=>this.hiddenInput.click()),"Re-upload a file");this.icon.replaceWith(t),this.icon=t}})),this.uploadedFile$.subscribe((t=>{if(this.onValueChanged&&this.onValueChanged(t),!t){const t=e.iconFA("cloud-upload",(()=>this.hiddenInput.click()),"Choose a file to upload");this.icon.replaceWith(t),this.icon=t}this.value=t})),this.reset()}subscribeOnEvents(){this.input.readOnly=!0,this.input.classList.add("default");const t=t=>xt(this,void 0,void 0,(function*(){if(t&&t.length&&this.enabled){if(t.length>1)throw this.isValid.next(!1),new Error("Please specify single input file");if(this.fileType&&t[0].type!==this.fileType)throw this.isValid.next(!1),new Error("File type is not supported");this.isValid.value?this.uploadedFile$.next(t[0]):this.uploadedFile$.next(null)}}));this.root.classList.add("fi-drop-area"),this.root.style.width="100%",this.hiddenInput.type="file",this.hiddenInput.addEventListener("change",(()=>xt(this,void 0,void 0,(function*(){return yield t(this.hiddenInput.files)}))),!1),["dragenter","dragover","dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(t=>{t.preventDefault(),t.stopPropagation()}),!1)})),["dragenter","dragover"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.add("drag-n-dropping")}),!1)})),["dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.remove("drag-n-dropping")}),!1)})),this.input.addEventListener("drop",(e=>xt(this,void 0,void 0,(function*(){const n=e.dataTransfer.files;t(n)}))),!1),this.input.addEventListener("click",(()=>this.hiddenInput.click()),!1),this.addOptions(this.icon),["drag","dragenter"].forEach((t=>{document.getElementsByClassName("layout-workarea")[0].addEventListener(t,(t=>{t.stopPropagation()}),!1)}))}reset(){this.input.classList.value="ui-input-editor default",this.hiddenInput.value="",this.uploadedFile$.next(null)}}var Ot=n(703),Pt={};Pt.styleTagTransform=It(),Pt.setAttributes=bt(),Pt.insert=gt().bind(null,"head"),Pt.domAPI=mt(),Pt.insertStyleElement=Ct(),ht()(Ot.A,Pt),Ot.A&&Ot.A.locals&&Ot.A.locals;var Ft=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class _t extends o.Dialog{constructor(n,i){var s,r,a;super(e.dialog({title:"Edit run metadata"}).dart),this._onMetadataEdit=new c.Subject,this.onMetadataEdit=this._onMetadataEdit.asObservable();let l=null!==(s=n.options.title)&&void 0!==s?s:"",u=null!==(r=n.options.description)&&void 0!==r?r:"",d=i;const p=e.stringInput("Title",l,(t=>l=t)),h=e.stringInput(" ",""),f=o.TagEditor.create();(null!==(a=n.options.tags)&&void 0!==a?a:[]).forEach((t=>{f.addTag(t)})),h.input.replaceWith(f.root);const m=()=>{""===v.value||f.tags.includes(v.value)||(f.addTag(v.value),v.value="")},v=e.stringInput("Tag","").addOptions(e.iconFA("plus",m,"Add this tag")),g=(0,c.fromEvent)(v.input,"onkeydown").subscribe((t=>{"Enter"==t.key&&(t.stopPropagation(),m())}));this.sub(g),this.add(e.form([p,e.stringInput("Description",u,(t=>u=t)),e.boolInput("Favorites",d,(t=>d=t)),v,h])),this.addButton("Save",(()=>Ft(this,void 0,void 0,(function*(){if(""!==v.value)return void t.shell.info(`Dialog has unsaved tags: ${v.value}`);let e="same";d&&!i&&(e="favorited"),!d&&i&&(e="unfavorited");const n={title:""!==l?l:null,description:""!==u?u:null,tags:f.tags.map((t=>t)),favorite:e};this._onMetadataEdit.next(n),this.close()}))))}}class kt extends o.Dialog{constructor(t){super(e.dialog({title:`Delete ${t.size>1?t.size:""} ${t.size>1?"runs":"run"}`}).dart),this._onFuncCallDelete=new c.Subject,this.onFuncCallDelete=this._onFuncCallDelete.asObservable(),this.add(e.divText(`Deleted ${t.size>1?t.size:""} ${t.size>1?"runs":"run"} ${t.size>1?"are":"is"} impossible to restore. Are you sure?`)),this.onOK((()=>Ft(this,void 0,void 0,(function*(){return this._onFuncCallDelete.next(t)}))))}}var Mt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Bt=t=>{var e,n;if(null===(e=t.options)||void 0===e?void 0:e.default)return JSON.parse(null===(n=t.options)||void 0===n?void 0:n.default);const i=t.defaultValue;return t.propertyType===o.TYPE.STRING&&i?i.substring(1,i.length-1):i};function Lt(t,n){n?(a()(t).addClass("ui-box").css({width:"auto",height:"auto"}),e.setUpdateIndicator(t,!0)):(e.setUpdateIndicator(t,!1),a()(t).removeClass("ui-box"))}const Dt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},Nt=t=>{try{return t.started.toDate().toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}catch(t){return"Not completed"}};var Vt=n(826),jt=n.n(Vt),$t=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};p().extend(jt());const Yt=Object.values(o.COLUMN_TYPE).filter((t=>t!==o.TYPE.DATA_FRAME)),Ht=t=>t.replace(/([A-Z])/g,(t=>` ${t.toLowerCase()}`)).trim().replace(/^./,(t=>t.toUpperCase())),Ut=new o.LruCache;class Wt extends o.Widget{storageName(t){return`${S}_${[...t.values()][0].func.name}_Fav`}get onRunsDfChanged(){return this._onRunsDfChanged.asObservable()}get onChosen(){return this._onChosen.asObservable()}get chosen(){return this._onChosen.value}set chosen(t){var e;this.chosenById=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:null}set chosenById(t){if(t){for(let e=0;e<this.currentDf.rowCount;e++)if(this.currentDf.getCol(Jt).get(e)===t){this.currentDf.currentRowIdx=e;break}}else this.currentDf.currentRowIdx=-1}get selected(){return this._onSelectedChanged.value}get runs(){return this.onRunsChanged.value}get onSelectedChanged(){return this._onSelectedChanged.asObservable()}saveIsFavorite(e,n){return $t(this,void 0,void 0,(function*(){const i=`${S}_${e.func.name}_Fav`;return n?t.dapi.userDataStorage.postValue(i,e.id,""):t.dapi.userDataStorage.remove(i,e.id)}))}getRunByIdx(t){return this.runs.get(this.currentDf.get(Jt,t))}showEditDialog(e,n){const i=new _t(e,n),o=i.onMetadataEdit.subscribe((n=>$t(this,void 0,void 0,(function*(){var i;if(null===(i=this.options)||void 0===i?void 0:i.isHistory)return("same"!==n.favorite?this.saveIsFavorite(e,"favorited"===n.favorite):Promise.resolve()).then((()=>dt.loadRun(e.id,!1))).then((t=>(n.title&&(t.options.title=n.title),n.description&&(t.options.description=n.description),n.tags&&(t.options.tags=n.tags),[dt.saveRun(t),t]))).then((([,t])=>{this.updateRun(t),this.onMetadataEdit.next(t),o.unsubscribe()})).catch((e=>{t.shell.error(e)}));this.updateRun(e)}))));i.show({center:!0,width:500})}visibleProps(t){var e,n,i;return null!==(i=null!==(n=null===(e=this.options)||void 0===e?void 0:e.visibleProps)&&void 0!==n?n:Q(t))&&void 0!==i?i:t.inputs.filter((t=>Yt.includes(t.propertyType))).map((t=>t.name))}constructor(n,i){var s,r,l,u,d,h,m;super(e.div([],{style:{height:"100%",width:"100%"}})),this.initialRuns=n,this.options=i,this.onRunsChanged=new c.BehaviorSubject(this.initialRuns.reduce(((t,e)=>(t.set(e.id,e),t)),new Map)),this._onRunsDfChanged=new c.BehaviorSubject(o.DataFrame.fromColumns([o.Column.bool(O,0),...(null===(s=this.options)||void 0===s?void 0:s.isHistory)?[o.Column.bool(P,0)]:[],...(null===(r=this.options)||void 0===r?void 0:r.showActions)?[o.Column.string(_,0)]:[],o.Column.bool(F,0),o.Column.dateTime(M,0),o.Column.string(k,0),o.Column.string(D,0),o.Column.string(B,0),o.Column.string(L,0),o.Column.fromStrings(Jt,[])])),this._historyFilters=o.Viewer.filters(this._onRunsDfChanged.value,{title:"Filters",columnNames:[]}),this._historyGrid=o.Viewer.grid(this._onRunsDfChanged.value,{showRowHeader:!1,showColumnGridlines:!1,allowEdit:!1}),this.onComparisonCalled=new c.Subject,this.onMetadataEdit=new c.Subject,this._onChosen=new c.BehaviorSubject(null),this.onDelete=new c.Subject,this._onSelectedChanged=new c.BehaviorSubject(new Set([])),this.layout=e.splitH([],null,!0),this.defaultGridText=e.divText(null!==(u=null===(l=this.options)||void 0===l?void 0:l.fallbackText)&&void 0!==u?u:"No historical runs found","hp-no-elements-label"),this.defaultFiltersText=e.divText("No filters to show","hp-no-elements-label"),this.filterWithText=e.divH([this.defaultFiltersText,this._historyFilters.root],"ui-box"),this.trashIcon=e.div(e.iconFA("trash-alt",(()=>{const t=this.currentDf.selection.getSelectedIndexes(),e=new Set;t.forEach((t=>e.add(this.getRunByIdx(t))));const n=new kt(e),i=n.onFuncCallDelete.subscribe((t=>$t(this,void 0,void 0,(function*(){yield Promise.all(f()(t.values()).map((t=>$t(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()}))))),i.unsubscribe()}))));n.show({center:!0,width:500,modal:!0})}),"Delete selected runs"),{style:{"padding-top":"5px"}}),this.compareIcon=e.div(e.iconFA("exchange",(()=>$t(this,void 0,void 0,(function*(){const t=this.currentDf.selection.getSelectedIndexes(),e=[];t.forEach((t=>{e.push(this.currentDf.getCol(Jt).get(t))})),this.onComparisonCalled.next(e)}))),"Compare selected runs"),{style:{"padding-top":"5px"}}),this._isFilterHidden=new c.BehaviorSubject(!1),this.showFiltersIcon=e.div(e.iconFA("filter",(()=>{this._isFilterHidden.next(!this._isFilterHidden.value)}),"Toggle filters"),{style:{"padding-top":"4px"}}),this._compactMode=new c.BehaviorSubject(null!==(h=null===(d=this.options)||void 0===d?void 0:d.isHistory)&&void 0!==h&&h),this.toggleCompactMode=e.div(e.iconFA("expand-alt",(()=>{this.compactMode=!this.compactMode}),"Toggle compact mode"),{style:{"padding-top":"4px"}}),this.showMetadataIcon=e.switchInput("Metadata",!0,(()=>{this.styleHistoryGrid(),this.styleHistoryFilters()})),this.showInputsIcon=e.switchInput("Params",!1,(t=>$t(this,void 0,void 0,(function*(){var e;0!==this.runs.size&&(t&&(null===(e=this.options)||void 0===e?void 0:e.isHistory)?((yield Promise.all([...this.runs.values()].map((t=>$t(this,void 0,void 0,(function*(){if(Ut.has(t.id))return Ut.get(t.id);{const e=yield dt.loadRun(t.id,!0);return Ut.set(e.id,e),e}})))))).forEach((t=>{this.runs.set(t.id,t)})),this.onRunsChanged.next(this.runs)):(this.styleHistoryGrid(),this.styleHistoryFilters()))}))));const v=e.divH([e.divH([...(null==i?void 0:i.isHistory)?[this.toggleCompactMode]:[],this.showFiltersIcon,this.showMetadataIcon.root,this.showInputsIcon.root],{style:{gap:"5px",padding:"5px"}}),e.divH((null===(m=this.options)||void 0===m?void 0:m.showBatchActions)?[this.trashIcon,this.compareIcon]:[],{style:{gap:"5px",padding:"5px"}})],{style:{"justify-content":"space-between",padding:"0px 5px"}});v.style.setProperty("overflow-y","hidden","important");const g=e.divV([this.defaultGridText,v,this._historyGrid.root],"ui-box");a()(g).removeClass("ui-div"),a()(g).css("width","100%"),this.root.appendChild(this.layout),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1),this.setGridCellRendering();const y=this.onRunsChanged.subscribe((n=>$t(this,void 0,void 0,(function*(){var i,s,r;const a=[...n.values()],l=t=>{var e,n;return t.propertyType===o.TYPE.DATE_TIME?o.Column.dateTime(null!==(e=t.caption)&&void 0!==e?e:Ht(t.name),a.length).init((e=>window.grok_DayJs_To_DateTime(a[e].inputs[t.name]))):o.Column.fromType(t.propertyType,null!==(n=t.caption)&&void 0!==n?n:Ht(t.name),a.length).init((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t.name])||void 0===o?void 0:o.call(i,a[e]))&&void 0!==s?s:X(a[e],t.name)}))},u=t=>t===M?o.Column.dateTime(Ht(t),a.length).init((t=>window.grok_DayJs_To_DateTime(Z(a[t])?a[t].started.utc(!0):p().unix(a[t].options.createdOn)))):t===F?o.Column.bool(Ht(t),a.length).init((t=>Z(a[t]))):o.Column.fromStrings(Ht(t),a.map((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t])||void 0===o?void 0:o.call(i,e))&&void 0!==s?s:X(e,t)})));if(n.size>0){const c=null!==(i=yield t.dapi.userDataStorage.get(this.storageName(n)))&&void 0!==i?i:{},d=Object.keys(c),p=[...this.runs.values()][0].func,h=t=>{var e;const n=null!==(e=p.inputs.find((e=>e.name===t)))&&void 0!==e?e:p.outputs.find((e=>e.name===t));return n?l(n):u(t)},f=o.DataFrame.fromColumns([o.Column.string(O,a.length).init((t=>{const e=a[t].options.immutable_tags;return e&&e.includes(C)?"Experimental":"Simulated"})),...(null===(s=this.options)||void 0===s?void 0:s.isHistory)?[o.Column.bool(P,a.length).init((t=>d.includes(a[t].id)))]:[],...(null===(r=this.options)||void 0===r?void 0:r.showActions)?[o.Column.string(_,a.length).init("")]:[],u(M),u(F),u(k),o.Column.string(D,a.length).init((t=>a[t].options.tags?a[t].options.tags.join(","):"")),o.Column.string(B,a.length).init((t=>a[t].options.title)),o.Column.string(L,a.length).init((t=>a[t].options.description))]);this.visibleProps(p).map((t=>h(t))).forEach((t=>{t.name=f.columns.getUnusedName(t.name),f.columns.add(t,!1)})),f.columns.add(o.Column.fromStrings(Jt,a.map((t=>t.id)))),e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!1),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.showMetadataIcon.root,this.trashIcon,this.compareIcon,this.showFiltersIcon],!0),e.setDisplay(this.showInputsIcon.root,this.visibleProps(p).length>0),this._onRunsDfChanged.next(f)}else e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!0),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.showMetadataIcon.root,this.showInputsIcon.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1)})))),b=this._onRunsDfChanged.subscribe((t=>{this._historyFilters.dataFrame=t,this._historyGrid.dataFrame=t,this.currentDf.getCol(D).setTag(o.TAGS.MULTI_VALUE_SEPARATOR,","),this.styleHistoryGrid(),this.styleHistoryFilters();const e=t.onCurrentRowChanged.subscribe((()=>{var t;this.currentDf.rows.select((()=>!1)),this._onChosen.next(null!==(t=this.getRunByIdx(this.currentDf.currentRowIdx))&&void 0!==t?t:null)})),n=t.onSelectionChanged.subscribe((()=>{const e=[...t.selection.getSelectedIndexes()].map((t=>this.getRunByIdx(t)));this._onSelectedChanged.next(new Set(e)),this.redrawSelectionState()}));this.redrawSelectionState(),this.subs.push(e,n)})),A=this._isFilterHidden.subscribe((t=>{t?(a()(this.showFiltersIcon.firstChild).addClass("fal"),a()(this.showFiltersIcon.firstChild).removeClass("fad"),e.setDisplay(this.filterWithText,!1)):(a()(this.showFiltersIcon.firstChild).addClass("fad"),a()(this.showFiltersIcon.firstChild).removeClass("fal"),a()(this.filterWithText).css(this.compactMode?"height":"width","320px"),a()(this.filterWithText).css(this.compactMode?"width":"height","100%"),e.setDisplay(this.filterWithText,!0))})),w=this._compactMode.subscribe((t=>{const n=[g,this.filterWithText];a()(this.filterWithText).removeClass("ui-div");const i={style:{width:"100%",height:"100%"}};a()(this.toggleCompactMode.firstChild).addClass(t?"fa-expand-alt":"fa-compress-alt"),a()(this.toggleCompactMode.firstChild).removeClass(t?"fa-compress-alt":"fa-expand-alt");const o=t?e.splitV(n,i,!0):e.splitH(n,i,!0);this.layout.replaceWith(o),this.layout=o,e.tools.waitForElementInDom(this.layout).then((t=>{a()(t).css(this.compactMode?"height":"width","100%"),a()(this._historyFilters.root).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),a()(this.filterWithText).css(Object.assign({},this.compactMode?{height:"310px",width:"100%"}:{width:"310px",height:"100%"})),a()(g).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),setTimeout((()=>{this.styleHistoryGrid(),this.styleHistoryFilters()}),100)}))}));this.subs.push(y,w,b,A)}setGridColumnsRendering(){const t=this._historyGrid.columns.byName(_);t&&(t.cellType="html",t.width=35);const e=this._historyGrid.columns.byName(P);e&&(e.cellType="html",e.width=20);const n=this._historyGrid.columns.byName(O);n.cellType="html",n.width=20;const i=this._historyGrid.columns.byName(D);i.cellType="html",i.width=90,this._historyGrid.columns.byName(M).width=110,this._historyGrid.columns.byName(Jt).cellType="html"}isFavoriteByIndex(t){return this.currentDf.get(P,t)}setGridCellRendering(){this._historyGrid.onCellPrepare((n=>{var i,o,s,r,l,u,c,d,p,h,m;if(n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.name)&&[_,O,P].includes(n.tableColumn.name)&&(n.customText=""),!n.isColHeader){if((null===(o=n.tableColumn)||void 0===o?void 0:o.name)===_){n.customText="";const t=this.getRunByIdx(n.tableRowIndex);n.element=e.divH([e.iconFA("trash",(()=>{const t=new Set([this.getRunByIdx(n.tableRowIndex)]),e=new kt(t),i=e.onFuncCallDelete.subscribe((()=>$t(this,void 0,void 0,(function*(){yield Promise.all(f()(t.values()).map((t=>$t(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()}))))),i.unsubscribe()}))));e.show({center:!0,width:500})}),"Remove run from history"),e.iconFA("edit",(()=>this.showEditDialog(t,this.isFavoriteByIndex(n.tableRowIndex))),"Edit run metadata")],{style:{padding:"6px 0px",gap:"6px","justify-content":"space-between"}})}if((null===(s=n.tableColumn)||void 0===s?void 0:s.name)===P){n.customText="";const t=this.getRunByIdx(n.tableRowIndex),i=e.iconFA("star",(()=>this.saveIsFavorite(t,!1).then((()=>this.updateRun(t)))),"Unfavorite");a()(i).addClass("fas"),n.element=e.div(n.cell.value?i:e.iconFA("star",(()=>this.saveIsFavorite(t,!0).then((()=>this.updateRun(t)))),"Favorite"),{style:{padding:"5px 0px"}})}if((null===(r=n.tableColumn)||void 0===r?void 0:r.name)===O){n.customText="";const t=e.iconFA("flask",null,"Experimental run");a()(t).addClass("fad fa-sm"),a()(t).removeClass("fal"),n.element=n.cell.value&&"Experimental"===n.cell.value?e.div(t,{style:{padding:"5px"}}):e.div()}if((null===(l=n.tableColumn)||void 0===l?void 0:l.name)===D){n.customText="";const t=n.cell.value.length>0?e.div(null===(u=n.cell.value)||void 0===u?void 0:u.split(",").map((t=>e.span([t],"d4-tag"))),"d4-tag-editor"):e.div();a()(t).css({padding:"3px","background-color":"transparent"}),n.element=t}if((null===(c=n.tableColumn)||void 0===c?void 0:c.name)===Jt){n.customText="";const i=this.getRunByIdx(n.tableRowIndex);if(!i)return;const o=i.author.picture;a()(o).css({width:"25px",height:"25px",fontSize:"20px"}),e.bind(i.author,o);const s=e.iconFA("flask",null,"Experimental run");s.classList.add("fad","fa-sm"),s.classList.remove("fal"),s.style.marginLeft="3px";const r=i.options.immutable_tags,l=e.span([e.label(null!==(h=null!==(d=i.options.title)&&void 0!==d?d:null===(p=i.author)||void 0===p?void 0:p.friendlyName)&&void 0!==h?h:t.shell.user.friendlyName,{style:{color:"var(--blue-1)"}}),...r&&r.includes(C)?[s]:[]]),u=e.iconFA("edit",(t=>{t.stopPropagation(),this.showEditDialog(i,this.isFavoriteByIndex(n.tableRowIndex))}),"Edit run metadata");u.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const c=e.iconFA("trash-alt",(t=>$t(this,void 0,void 0,(function*(){t.stopPropagation();const e=new Set([this.getRunByIdx(n.tableRowIndex)]),i=new kt(e),o=i.onFuncCallDelete.subscribe((()=>$t(this,void 0,void 0,(function*(){yield Promise.all(f()(e.values()).map((t=>$t(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()}))))),o.unsubscribe()}))));i.show({center:!0,width:500})}))),"Delete run");c.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const v=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!1).then((()=>this.updateRun(i)))}),"Unfavorite");v.classList.add("fas","hp-funccall-card-icon");const g=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!0).then((()=>this.updateRun(i)))}),"Favorite");g.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon"),this.isFavoriteByIndex(n.tableRowIndex)?(e.setDisplay(g,!1),e.setDisplay(v,!0)):(e.setDisplay(v,!1),e.setDisplay(g,!0));const y=Nt(i),b=e.divH([e.divH([o,e.divV([l,e.span([y]),...i.options.tags&&i.options.tags.length>0?[e.div(i.options.tags.map((t=>e.span([t],"d4-tag"))))]:[]],"hp-card-content")]),e.divH([...(null===(m=this.options)||void 0===m?void 0:m.showActions)?[v,g,u,c]:[]])],"hp-funccall-card"),A=n.tableRowIndex;b.addEventListener("mouseover",(()=>{n.grid.dataFrame.mouseOverRowIdx=A})),b.addEventListener("click",(t=>{t.shiftKey?n.grid.dataFrame.selection.set(A,!0):t.ctrlKey?n.grid.dataFrame.selection.set(A,!1):n.grid.dataFrame.currentRowIdx=A})),n.element=b}}}))}deleteRun(e){return $t(this,void 0,void 0,(function*(){return dt.loadRun(e,!0).then((t=>{var e;return[(null===(e=this.options)||void 0===e?void 0:e.isHistory)?dt.deleteRun(t):Promise.resolve(),t]})).then((([,t])=>{var n;return this.runs.delete(e),this.onRunsChanged.next(this.runs),(null===(n=this.options)||void 0===n?void 0:n.isHistory)&&this.onDelete.next(t),t})).then((t=>{this.saveIsFavorite(t,!1)})).catch((e=>{t.shell.error(e)}))}))}editRun(t){this.showEditDialog(t,!1)}updateRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}addRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}updateRuns(t){this.onRunsChanged.next(t.reduce(((t,e)=>(t.set(e.id,e),t)),new Map))}get isFilterHidden(){return this._isFilterHidden.value}set isFilterHidden(t){this._isFilterHidden.next(t)}get compactMode(){return this._compactMode.value}set compactMode(t){this._compactMode.next(t)}get onCompactModeChanged(){return this._compactMode.asObservable()}styleHistoryGrid(){var t;this._historyGrid.setOptions({showCurrentRowIndicator:!0,showCurrentCellOutline:!1,allowEdit:!1,allowBlockSelection:!1,showRowHeader:!1,showColumnLabels:!this.compactMode,extendLastColumn:this.compactMode}),this._historyGrid.sort([M],[!1]);for(let e=0;e<this._historyGrid.columns.length;e++){const n=this._historyGrid.columns.byIndex(e);n&&(null===(t=n.column)||void 0===t?void 0:t.type)===o.TYPE.DATE_TIME&&(n.format="MMM d, h:mm tt")}if(this.setGridColumnsRendering(),0!==this.runs.size)if(this.compactMode)this._historyGrid.columns.setVisible([Jt]),this._historyGrid.props.rowHeight=70,this._historyGrid.invalidate();else{this._historyGrid.props.rowHeight=28;const t=[...this.runs.values()][0].func,e=this.showMetadataIcon.value,n=this.currentDf.getCol(D);this._historyGrid.columns.setVisible([O,P,_,...e?[M]:[],...e?[k]:[],...e&&n.stats.missingValueCount<n.length?[D]:[],...e?[B]:[],...e?[L]:[],...this.showInputsIcon.value?this.visibleProps(t).map((e=>{var n,i;const o=null!==(n=t.inputs.find((t=>t.name===e)))&&void 0!==n?n:t.outputs.find((t=>t.name===e));return o?null!==(i=o.caption)&&void 0!==i?i:Ht(o.name):Ht(e)})):[]])}}get currentDf(){return this._onRunsDfChanged.value}styleHistoryFilters(){var t,n;if(this.runs.size>0){const i=[...this.runs.values()][0].func,o=this.currentDf.getCol(D),s=this.showMetadataIcon.value,r=[...s&&this.currentDf.getCol(O).categories.length>1?[O]:[],...s&&(null!==(n=null===(t=this.currentDf.col(P))||void 0===t?void 0:t.categories.length)&&void 0!==n?n:0)>1?[P]:[],...s?[M,F]:[],...s&&this.currentDf.getCol(k).categories.length>1?[k]:[],...s&&o.stats.missingValueCount<o.length?[D]:[],...s&&this.currentDf.getCol(B).categories.length>1?[B]:[],...s&&this.currentDf.getCol(L).categories.length>1?[L]:[],...this.showInputsIcon.value?this.visibleProps(i).map((t=>{var e,n;const o=null!==(e=i.inputs.find((e=>e.name===t)))&&void 0!==e?e:i.outputs.find((e=>e.name===t));return o?null!==(n=o.caption)&&void 0!==n?n:Ht(o.name):Ht(t)})).filter((t=>{var e;return!(null===(e=this.options)||void 0===e?void 0:e.isHistory)||this.currentDf.getCol(t).categories.length>1})).map((t=>t)):[]];r.length>0?(a()(this.filterWithText).css({paddingTop:"10px"}),e.setDisplay(this.defaultFiltersText,!1),e.setDisplay(this._historyFilters.root,!0),this._historyFilters.setOptions({columnNames:r,showHeader:!1,showBoolCombinedFitler:!1})):(e.setDisplay(this.defaultFiltersText,!0),e.setDisplay(this._historyFilters.root,!1))}}redrawSelectionState(){const t=this.currentDf.selection.trueCount;t<2?this.compareIcon.firstChild.classList.add("hp-disabled"):this.compareIcon.firstChild.classList.remove("hp-disabled"),0===t?this.trashIcon.firstChild.classList.add("hp-disabled"):this.trashIcon.firstChild.classList.remove("hp-disabled")}}var Gt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class zt{static getHistoryRuns(e){return(0,c.from)((()=>Gt(this,void 0,void 0,(function*(){return yield dt.pullRunsByName(e,[{author:t.shell.user}],{order:"started"},["func.params","session.user","options"],!0)})))())}}const Jt="ID";class qt extends o.InputBase{constructor(t,n,i){var o,r;const a=e.stringInput(t,"",null);super(a.dart),this.label=t,this._funcName=n,this.options=i,this.onHistoricalRunChosen=new c.BehaviorSubject(null),this.experimentRunsUpdate=new c.Subject,this.store={experimentRuns:new c.Observable,isExperimentRunsLoading:new c.Subject,experimentRunData:new c.BehaviorSubject("")},this._historyList=new Wt([],{fallbackText:"No runs are found in history",showActions:!1,showBatchActions:!1,isHistory:!1,visibleProps:null===(o=this.options)||void 0===o?void 0:o.mainProps,propFuncs:null===(r=this.options)||void 0===r?void 0:r.propFuncs}),this._historyDialog=this.getHistoryDialog(),this._visibleInput=e.stringInput(this.label,"",null),this._visibleIcon=e.iconFA("search",(()=>this.showSelectionDialog())),this._chosenRun=null,this._chosenRunId=null,this._visibleInput=a,this._visibleInput.readOnly=!0,this._visibleInput.input.addEventListener("click",(()=>this.showSelectionDialog())),this._visibleInput.addOptions(this._visibleIcon),this.store.experimentRuns=this.experimentRunsUpdate.pipe((0,s.tap)((()=>this.toggleLoaderExpRuns(!0))),(0,s.switchMap)((()=>zt.getHistoryRuns(this._funcName).pipe((0,s.catchError)((t=>(console.error(t),c.EMPTY))),(0,s.finalize)((()=>this.toggleLoaderExpRuns(!1)))))),(0,s.shareReplay)(1)),this.store.experimentRuns.subscribe((t=>{this._historyList.updateRuns(t.filter((t=>!K(t))))})),this.store.isExperimentRunsLoading.subscribe((t=>{e.setUpdateIndicator(this._visibleInput.root,t),e.setUpdateIndicator(this._historyList.root,t)})),this.experimentRunsUpdate.next()}setCurrentRow(){this.getValue()?this._historyList.chosen=this.getValue():this.chosenRunId&&(this._historyList.chosenById=this.chosenRunId)}showSelectionDialog(){this.renderGridAndFilters(),this._historyDialog.getButton("OK").disabled=1!==this._historyList.selected.size,this._historyDialog.show({modal:!0,fullScreen:!0,center:!0,width:window.innerWidth-50,height:window.innerHeight-50})}renderGridAndFilters(){var t,e;const n=new Wt([...this._historyList.runs.values()],Object.assign(Object.assign({},this.options),{visibleProps:null===(t=this.options)||void 0===t?void 0:t.mainProps,propFuncs:null===(e=this.options)||void 0===e?void 0:e.propFuncs}));this._historyList.root.replaceWith(n.root),this._historyList=n,this._historyList.onChosen.subscribe((t=>{this._historyDialog.getButton("OK").disabled=!t})),this._historyList.onRunsDfChanged.pipe((0,s.filter)((t=>t.rowCount>0)),(0,s.take)(1)).subscribe((t=>{this.setCurrentRow()}))}getHistoryDialog(){const t=e.dialog();return a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form"),t.onOK((()=>Gt(this,void 0,void 0,(function*(){const t=this._historyList.chosen;t&&this.setValue(t),this.fireInput()})))),t.addButton("Refresh",(()=>{this.experimentRunsUpdate.next()}),2,"Reload list of runs"),t.addButton("Discard",(()=>{this.setValue(null),this.fireInput(),t.close()}),1,"Discard the previous choice"),a()(t.getButton("CANCEL")).hide(),t.add(this._historyList.root),t}setValue(t){var e,n,i,o,s,r,a;this._chosenRun=t,this._chosenRunId=null!==(n=null===(e=this._chosenRun)||void 0===e?void 0:e.id)&&void 0!==n?n:null,this.onHistoricalRunChosen.next(t),this.stringValue=t?(null===(i=this.options)||void 0===i?void 0:i.stringValueFunc)?null===(o=this.options)||void 0===o?void 0:o.stringValueFunc(t):[`${Nt(t)} \\ ${t.author.name}`,(null!==(a=null!==(r=null===(s=this.options)||void 0===s?void 0:s.mainProps)&&void 0!==r?r:Q(t.func))&&void 0!==a?a:[]).map((e=>X(t,e))).join(" \\ ")].join(" \\ "):"No run chosen",this.notify&&this.fireChanged()}getValue(){return this._chosenRun}get chosenRun(){return this._chosenRun}get chosenRunId(){return this._chosenRunId}set chosenRunId(t){this._chosenRunId=t}get root(){return this._visibleInput.root}set stringValue(t){this._visibleInput.value=t,this._visibleInput.setTooltip(this._visibleInput.value)}get stringValue(){return this._visibleInput.value}get iconRoot(){return this._visibleIcon}toggleLoaderExpRuns(t){this.store.isExperimentRunsLoading.next(t)}}class Kt extends qt{set value(t){this.setValue(t)}get value(){return this.getValue()}}class Zt extends qt{get value(){const t=this.getValue();return t?JSON.stringify({visualValue:this.stringValue,id:t.id.split("-")}):null}set value(t){this.setValue(null),this.stringValue=t?JSON.parse(t).visualValue:"No run is chosen",this.chosenRunId=t?JSON.parse(t).id.join("-"):""}}var Xt=n(565),Qt={};Qt.styleTagTransform=It(),Qt.setAttributes=bt(),Qt.insert=gt().bind(null,"head"),Qt.domAPI=mt(),Qt.insertStyleElement=Ct(),ht()(Xt.A,Qt),Xt.A&&Xt.A.locals&&Xt.A.locals;var te;class ee extends o.Widget{updateHistoryPane(t){this.historyList.updateRuns(t)}showEditDialog(t){this.historyList.editRun(t)}addRun(t){this.historyList.addRun(t)}get history(){return this.historyList.runs}get onCompactModeChanged(){return this.historyList.onCompactModeChanged}get compactMode(){return this.historyList.compactMode}constructor(n){super(e.box(e.divText("No historical runs loaded","hp-no-elements-label"),{style:{width:"100%",height:"100%"}})),this.func=n,this.onRunChosen=new c.Subject,this.onComparison=new c.Subject,this.afterRunEdited=new c.Subject,this.afterRunDeleted=new c.Subject,this.allRunsFetch=new c.Subject,this.historyList=new Wt([],{fallbackText:"No runs are found in history",showActions:!0,showBatchActions:!0,isHistory:!0}),this.panel=this.historyList.root;const i=this.historyList.onChosen.pipe((0,s.filter)((t=>!!t))).subscribe((t=>this.onRunChosen.next(t.id))),o=this.historyList.onComparisonCalled.subscribe((t=>this.onComparison.next(t))),r=this.allRunsFetch.subscribe((()=>{return n=this,i=void 0,s=function*(){e.setUpdateIndicator(this.root,!0),dt.pullRunsByName(this.func.name,[{author:t.shell.user}],{},["session.user","options"]).then((t=>{e.empty(this.root),this.root.appendChild(this.panel),this.updateHistoryPane(t)})).catch((e=>t.shell.error(e))).finally((()=>e.setUpdateIndicator(this.root,!1)))},new((o=void 0)||(o=Promise))((function(t,e){function r(t){try{l(s.next(t))}catch(t){e(t)}}function a(t){try{l(s.throw(t))}catch(t){e(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof o?n:new o((function(t){t(n)}))).then(r,a)}l((s=s.apply(n,i||[])).next())}));var n,i,o,s})),a=this.historyList.onMetadataEdit.subscribe((t=>{this.afterRunEdited.next(t)})),l=this.historyList.onDelete.subscribe((t=>{this.afterRunDeleted.next(t)}));this.subs.push(i,r,a,o,l),this.allRunsFetch.next()}}!function(t){t.fileInput=function(t="Drag-n-drop here",e=null,n=null,i=Rt){return new St(t,e,n,i)},t.historyInput=function(t,e,n){return new Kt(t,e,n)},t.historyInputJSON=function(t,e,n){return new Zt(t,e,n)},t.historyPanel=function(t){return new ee(t)}}(te||(te={}));var ne=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ie=window;class oe extends o.TableView{static fromComparedRuns(n,i){return ne(this,arguments,void 0,(function*(n,i,s={parentView:void 0,parentCall:void 0}){const r=((n,i,s={parentView:void 0,parentCall:void 0})=>{var r,l;const u=i,c=[...u.inputs,...u.outputs].map((t=>Dt(t))).reduce(((t,e)=>(t[e.name]?t[e.name].push(...e.config):t[e.name]=e.config,t)),{}),d=t=>{var e;if(t.propertyType===o.TYPE.DATA_FRAME){const e=c[t.name].map((e=>{var i;let s=null!==(i=t.caption)&&void 0!==i?i:t.name;const r=o.Column.fromType(o.TYPE.DATA_FRAME,s,n.length);r.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const a=p.columns.getUnusedName(`${r.name} (${e.type})`);return r.name=a,s=a,r.temp[g]=e,p.columns.add(r),r}));return e}{let i=null!==(e=t.caption)&&void 0!==e?e:t.name;const s=o.Column.fromType(t.propertyType,i,n.length);s.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const r=p.columns.getUnusedName(s.name);return s.name=r,i=r,p.columns.add(s),[s]}},p=o.DataFrame.create(n.length),h=[];return n.forEach((t=>{var e;let n=null!==(e=t.options.title)&&void 0!==e?e:`${t.func.name} - ${Nt(t)}`,i=2;for(;h.includes(n);)n=`${t.func.name} - ${Nt(t)})\n .toLocaleString('en-us', {month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric'})} - ${i}`,i++;h.push(n)})),p.columns.add(o.Column.fromStrings(w,h)),p.name=(null===(r=s.parentCall)||void 0===r?void 0:r.func.name)?`${null===(l=s.parentCall)||void 0===l?void 0:l.func.name} - comparison`:`${i.name} - comparison`,u.inputs.forEach((t=>d(t))),u.outputs.forEach((t=>d(t))),t.events.onCurrentObjectChanged.subscribe((({sender:n})=>{if(n instanceof o.Column&&n.type===o.TYPE.DATA_FRAME&&t.shell.tv&&t.shell.tv.temp.isComparison&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.temp[g].type)){t.shell.windows.showProperties=!0;const i=t=>{const e=t.get(0).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,0));for(let n=1;n<t.length;n++){const i=t.get(n).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=n.temp[g].look;setTimeout((()=>{switch(n.temp[g].type){case o.VIEWER.LINE_CHART:const r=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.line(Object.assign(Object.assign({},s),{split:I})).root}))));a()(r).css({width:"100%"}),t.shell.o=r;break;case o.VIEWER.SCATTER_PLOT:const l=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.scatter(Object.assign(Object.assign({},s),{color:I})).root}))));t.shell.o=l,a()(l).css({width:"100%"});break;case o.VIEWER.HISTOGRAM:const u=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.histogram(Object.assign(Object.assign({},s),{split:I})).root}))));t.shell.o=u,a()(u).css({width:"100%"});break;case o.VIEWER.BOX_PLOT:const c=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.box(Object.assign(Object.assign({},s),{category:I})).root}))));t.shell.o=c,a()(c).css({width:"100%"})}}))}})),p})(n,i,s),l=[...t.shell.views].find((t=>t.type===v||"scripts"===t.type||"functions"===t.type));return l&&(t.shell.v=l),new this(r,s)}))}constructor(e,n={}){super(ie.grok_TableView(e.dart,!1)),n.parentView&&(this.parentView=n.parentView),this.parentCall=n.parentCall||t.functions.getCurrentCall()}showAllColumns(){const t=this.dataFrame.columns.names();this.grid.columns.setVisible(t)}showChangingColumns(){const t=this.dataFrame.columns.names().filter((t=>o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)&&this.dataFrame.getCol(t).categories.length>1||!o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)));this.grid.columns.setVisible(t)}defaultCustomize(){var n;const i=e.iconFA("compress-alt",(()=>{this.showChangingColumns(),a()(s).show(),a()(i).hide()}),"Hide constant parameters"),s=e.iconFA("expand-arrows-alt",(()=>{this.showAllColumns(),a()(s).hide(),a()(i).show()}),"Show all parameters");a()(i).hide(),this.setRibbonPanels([...this.getRibbonPanels(),[i,s]]),this.showChangingColumns(),this.root.style.removeProperty("width"),this.root.firstChild.style.removeProperty("width"),this.root.firstChild.firstChild.style.removeProperty("width"),this.grid.props.rowHeight=180,this.grid.props.showAddNewRowIcon=!1,this.grid.props.allowEdit=!1,this.grid.columns.byName(w).width=70;for(let t=0;t<this.grid.columns.length;t++){const e=this.grid.columns.byIndex(t);(null===(n=e.column)||void 0===n?void 0:n.temp[g])&&(e.width=350,e.cellType="html")}const r=new o.LruCache;this.grid.onCellPrepare((t=>ne(this,void 0,void 0,(function*(){if(!t.isColHeader&&!t.isRowHeader){if(t.tableColumn.name===w){t.customText="";const n=t.cell.value.split(" - "),i=n.length>1?[n[0],e.element("br"),n[1]]:n;return t.element=e.div(i,{style:{"writing-mode":"vertical-rl","text-orientation":"mixed",margin:"auto"}}),void(t.element.parentElement.style.display="flex")}if(t.tableColumn&&t.tableColumn.temp[g]){const e=t.cell.value,n=t.tableColumn.temp[g],i=n.type,s=()=>ne(this,void 0,void 0,(function*(){const s=Object.values(m).includes(i)?o.Viewer.fromType(i,e):yield e.plot.fromType(i);return t.tableColumn.temp[g].look?s.setOptions(t.tableColumn.temp[g].look):(s.setOptions(n),t.tableColumn.temp[g]=s.getOptions()),s.root})),a=`${e.id}_${i}`;if(r.get(a))t.element=r.get(a);else{const e=yield s();r.set(a,e),t.element=e}t.element.style.width="100%",t.element.style.height="100%"}}}))));const l=e.box(e.div([],{style:{"min-height":"100px"}})),u=t.events.onCurrentViewChanged.subscribe((()=>{t.shell.v.id===this.id?t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25):t.shell.dockManager.close(l)})),c=this.grid.onCellClick.subscribe((n=>{var i;if(t.shell.v.id===this.id&&n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.type)===o.TYPE.DATA_FRAME&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.tableColumn.temp[g].type)){t.shell.dockManager.findNode(l)||t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25);const i=t=>{const e=o.toJs(t.get(0)).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,0));for(let n=1;n<t.length;n++){const i=o.toJs(t.get(n)).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=(t,e,i)=>{var s;switch(null===(s=n.tableColumn)||void 0===s?void 0:s.temp[g].type){case o.VIEWER.LINE_CHART:return i.plot.line(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.SCATTER_PLOT:return i.plot.scatter(Object.assign(Object.assign({},e),{color:I})).root;case o.VIEWER.HISTOGRAM:return i.plot.histogram(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.BOX_PLOT:return i.plot.box(Object.assign(Object.assign({},e),{category:I})).root}};e.setUpdateIndicator(l,!0),setTimeout((()=>{var t;if(!n.tableColumn.temp.unitedPlot){const o=n.tableColumn.temp[g].look,r=i(n.tableColumn);n.tableColumn.temp.unitedPlot=s(null===(t=n.tableColumn)||void 0===t?void 0:t.temp[g].type,o,r),e.setUpdateIndicator(l,!1)}e.empty(l),l.appendChild(n.tableColumn.temp.unitedPlot)}),10)}else t.shell.dockManager.close(l)}));this.subs.push(c,u)}}const se="_DG_CUSTOM_SERIALIZED_TOKEN_";function re(t,e){if(e&&e[se]&&e.value)switch(e[se]){case"DataFrame":return o.DataFrame.fromByteArray(new Uint8Array(e.value));case"ArrayBuffer":return new Uint8Array(e.value).buffer;case"Map":return new Map(e.value);case"Set":return new Set(e.value)}return e}const ae=[{name:"Null",predicate:function(t,e){return null==t&&null==e},checker:function(){}},{name:"Boolean",predicate:function(t,e){return"boolean"==typeof t&&"boolean"==typeof e},checker:ue},{name:"String",predicate:function(t,e){return"string"==typeof t&&"string"==typeof e},checker:ue},{name:"Integer",predicate:function(t,e){return Number.isInteger(t)&&Number.isInteger(e)},checker:ue},{name:"Float",predicate:function(t,e){return"number"==typeof t&&"number"==typeof e},checker:function(t,e,n){if(!(t===Number.POSITIVE_INFINITY&&e===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY&&e===Number.NEGATIVE_INFINITY||isNaN(t)&&isNaN(e)))return Math.abs(t-e)<n.options.floatTolerance?void 0:[{msg:`Expected ${e}, got ${t} (tolerance = ${n.options.floatTolerance})`}]}},{name:"Map",predicate:function(t,e){return t instanceof Map&&e instanceof Map},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Maps are of different size: actual map size is ${t.size} and expected map size is ${e.size}`};o.push(n)}for(const n of e.keys()){const o=t.get(n),s=e.get(n);i([String(n)],o,s)}return o}},{name:"Set",predicate:function(t,e){return t instanceof Set&&e instanceof Set},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Sets are of different size: actual set size is ${t.size} and expected set size is ${e.size}`};o.push(n)}for(const n of e.values()){const e=t.has(n);i([String(n)],e,!0)}return o}},{name:"ArrayBuffer",predicate:function(t,e){return t instanceof ArrayBuffer&&e instanceof ArrayBuffer},checker:function(t,e,n,i){return ce(Array.from(new Uint8Array(t)),Array.from(new Uint8Array(e)),0,i)}},{name:"Array",predicate:function(t,e){return t instanceof Array&&e instanceof Array},checker:ce},{name:"DataFrame",predicate:function(t,e){return t instanceof o.DataFrame&&e instanceof o.DataFrame},checker:function(t,e,n,i){const o=[];if(t.rowCount!==e.rowCount){const n={msg:`Dataframes has different row count: actual row count is ${t.rowCount} and expected row count is ${e.rowCount}`};o.push(n)}for(const n of e.columns){const s=t.columns.byName(n.name);if(s)if(s.type===n.type)for(let t=0;t<e.rowCount;t++){const e=s.get(t),o=n.get(t);i([n.name,String(t)],e,o)}else{const t={msg:`Column ${n.name} type expected ${n.type} got ${s.type}`};o.push(t)}else{const t={msg:`Column ${n.name} not found`};o.push(t)}}return o}},{name:"Object",predicate:function(t,e){return"object"==typeof t&&"object"==typeof e},checker:function(t,e,n,i){for(const[n,o]of Object.entries(e))i([n],t[n],o);return[]}}];class le extends Error{}function ue(t,e){if(t!==e)return[{msg:`Expected ${e}, got ${t}`}]}function ce(t,e,n,i){const o=[];if(t.length!==e.length){const n={msg:`Arrays are of different length: actual array length is ${t.length} and expected array length is ${e.length}`};o.push(n)}for(let n=0;n<t.length;n++)i([String(n)],t[n],e[n]);return o}const de={floatTolerance:.001,maxErrorsReport:5,maxDepth:128,checkersSeq:ae,prefix:""};class pe{constructor(t={}){this.options=Object.assign(Object.assign({},de),t),this.state={errors:[],currentPath:[],options:this.options}}run(t,e){this.matchChecker(t,e),this.checkErrorsLimit(0)}checkDeep(t,e,n){const i=t.length;if(this.state.currentPath.push(...t),this.state.currentPath.length>this.options.maxDepth)throw new le(`Max depth ${this.options.maxDepth} is exceeded, potentially a circular structure`);this.matchChecker(e,n),this.state.currentPath.splice(-i)}matchChecker(t,e){let n=!1;for(const{predicate:i,checker:o}of this.options.checkersSeq)if(i(t,e)){n=!0;const i=o(t,e,this.state,this.checkDeep.bind(this));i&&i.map((t=>this.addError(t)));break}if(!n){const n={msg:`Type mismatch or no checker defined: expected ${e}, got ${t}`};this.addError(n)}}addError(t){var e,n;const i={path:[...null!==(e=this.state.currentPath)&&void 0!==e?e:[],...null!==(n=t.path)&&void 0!==n?n:[]],msg:t.msg};this.state.errors.push(i),this.checkErrorsLimit()}checkErrorsLimit(t=this.options.maxErrorsReport){if(this.state.errors.length>t){const t=this.makeReport();throw new le(t)}}makeReport(){const t=this.state.errors.map((t=>{var e;const n=(null!==(e=t.path)&&void 0!==e?e:[]).map((t=>`['${String(t)}']`)).join("."),i=n?`${n}: ${t.msg}`:t.msg;return this.options.prefix?`${this.options.prefix}: ${i}`:i})).slice(0,this.options.maxErrorsReport).join("\n");return t}}var he=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};function fe(e,n){return he(this,arguments,void 0,(function*(e,n,i={}){var o;yield function(t,e){return he(this,void 0,void 0,(function*(){if(!(yield t.isReady.pipe((0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(e))),(0,s.takeWhile)((t=>!t),!0),(0,s.last)()).toPromise()))throw new Error(`Waiting for view ${t.name} timeout`)}))}(n,null!==(o=i.initWaitTimeout)&&void 0!==o?o:2e4);const r=()=>he(this,void 0,void 0,(function*(){var e;if(i.parent){const n=null!==(e=i.parentWaitTimeout)&&void 0!==e?e:5e3,o=yield i.parent.isUpdating.pipe((0,s.map)((()=>i.parent.getRunningUpdates())),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(n))),(0,s.takeWhile)((t=>0!==t.length),!0),(0,s.last)()).toPromise();if(null==o?void 0:o.length){const e=`{options.prefix}: parent updates failed to complete in ${n}ms, updates: ${o.join(",")}`,s=new Error(e);throw i.interactive&&t.shell.error(String(s)),s}}}));yield r();for(const[t,o]of Object.entries(e.inputs)){const e=n.funcCall.inputParams[t].property.propertyType;i.updateMode?null==n.funcCall.inputs[t]&&(n.funcCall.inputs[t]=yield lt(e,o)):n.funcCall.inputs[t]=yield lt(e,o)}if(yield r(),yield(()=>he(this,void 0,void 0,(function*(){var e;if(n instanceof $n){const o=null!==(e=i.validatorsWaitTimeout)&&void 0!==e?e:5e3,r=yield n.pendingValidations.pipe((0,s.map)((t=>Object.keys(t))),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(o))),(0,s.takeWhile)((()=>!n.isValid()),!0),(0,s.last)()).toPromise();if(null==r?void 0:r.length){const e=`{options.prefix}: validators failed to accept input in ${o}ms, inputs: ${r.join(",")}`,n=new Error(e);throw i.interactive&&t.shell.error(String(n)),n}}})))(),console.log(`running ${n.func.nqName}`),yield n.run(),!i.updateMode){console.log(`checking ${n.func.nqName} results`);try{!function(t,e,n){new pe(n).run(t,e)}(n.funcCall.outputs,e.outputs,i),!i.parent&&i.interactive&&t.shell.info(`${n.name} test passed`)}catch(e){throw i.interactive&&t.shell.error(String(e)),e}console.log(`${n.func.nqName} ok`)}}))}var me=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ve=new URL(t.shell.startUri),ge="Run Data JSON",ye=()=>me(void 0,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,selfBrowserSurface:"include"}),e=new MediaRecorder(t),n=[];e.ondataavailable=t=>n.push(t.data),e.onstop=()=>{const e=new Blob(n,{type:n[0].type});t.getVideoTracks()[0].stop(),o.Utils.download(`Recording ${(new Date).toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}.mkv`,e,n[0].type)},e.start()}));class be extends o.ViewBase{constructor(n,i={historyEnabled:!0,isTabbed:!1,skipInit:!1}){var s,r,a,l,u;super(),this.initValue=n,this.options=i,this._type="function",this.funcCallReplaced=new c.Subject,this.isReady=new c.BehaviorSubject(!1),this.exportConfig=null,this.getMocks=null,this.getTemplates=null,this.getHelp=null,this.reportBug=null,this.requestFeature=null,this.getAbout=null,this.historyBlock=null,this.isHistorical=new c.BehaviorSubject(!1),this.historyRoot=e.div(),this.consistencyState=new c.BehaviorSubject("consistent"),this.defaultExportFilename=(t,e)=>`${this.name} - ${(new Date).toLocaleString("en-US").replaceAll(/:|\//g,"-")}.${null!=e?e:this.exportConfig.supportedExtensions[t]}`,this.defaultSupportedExportExtensions=()=>({Excel:"xlsx"}),this.defaultSupportedExportFormats=()=>["Excel"],this.helpCache=null,this.box=!0,this.parentCall=t.functions.getCurrentCall(),n instanceof o.FuncCall&&(this.parentCall=n),this.parentView=null===(a=null===(r=null===(s=this.parentCall)||void 0===s?void 0:s.parentCall)||void 0===r?void 0:r.aux)||void 0===a?void 0:a.view,(null===(u=null===(l=this.parentCall)||void 0===l?void 0:l.func)||void 0===u?void 0:u.name)&&(this.basePath=`/${this.parentCall.func.name}`),i.skipInit||this.init()}onFuncCallReady(){return me(this,void 0,void 0,(function*(){if(yield dt.augmentCallWithFunc(this.funcCall,!1),!this.options.isTabbed){this.name&&"New view"!==this.name||(this.name=this.funcCall.func.friendlyName);try{this.func.package&&(yield this.getPackageData())}catch(t){console.log(t)}}this.build();const t=this.getStartId();if(t&&!this.options.isTabbed&&(e.setUpdateIndicator(this.root,!0),this.loadRun(t),e.setUpdateIndicator(this.root,!1),this.setAsLoaded()),this.isHistoryEnabled&&this.func){const t=this.options.isTabbed?this.isHistorical.subscribe((t=>{t||(this.funcCall.id=null)})):this.isHistorical.subscribe((t=>{var e,n;if(t){this.path=`?id=${this.funcCall.id}`;const t=Nt(this.funcCall);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=this.funcCall.options.title)&&void 0!==e?e:t}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=this.funcCall.options.title)&&void 0!==n?n:t}`}else this.path="",this.funcCall.id=null,this.name=`${this.name.substring(0,this.name.indexOf(" — ")>0?this.name.indexOf(" — "):void 0)}`}));this.subs.push(t)}}))}getStartId(){return t.shell.getVar("isLoaded")?void 0:ve.searchParams.get("id")}setAsLoaded(){return t.shell.setVar("isLoaded",!0)}get funcCall(){return this._funcCall}get func(){var t;return null===(t=this.funcCall)||void 0===t?void 0:t.func}get lastCall(){return this._lastCall}set lastCall(t){this._lastCall=t}get type(){return this._type}getPackageData(){return me(this,void 0,void 0,(function*(){var t,e;const n=this.func.package;if(!n)return;const i=null===(t=yield null==n?void 0:n.getProperties())||void 0===t?void 0:t.REPORT_BUG_URL;i&&!this.reportBug&&(this.reportBug=()=>me(this,void 0,void 0,(function*(){window.open(i,"_blank")})));const o=null===(e=yield null==n?void 0:n.getProperties())||void 0===e?void 0:e.REQUEST_FEATURE_URL;o&&!this.requestFeature&&(this.requestFeature=()=>me(this,void 0,void 0,(function*(){window.open(o,"_blank")})));const s=`${n.friendlyName}.\nLast updated on ${p()(n.updatedOn).format("YYYY MMM D, HH:mm")}`;this.getAbout||(this.getAbout=()=>me(this,void 0,void 0,(function*(){return s})))}))}linkFunccall(t){this._funcCall=t,this.funcCallReplaced.next(!0)}loadFuncCallById(){return me(this,void 0,void 0,(function*(){if(this.initValue instanceof o.FuncCall)return yield new Promise((t=>setTimeout(t,0))),void this.linkFunccall(this.initValue);e.setUpdateIndicator(this.root,!0);const n=this.getStartId();if(n&&!this.options.isTabbed)this.linkFunccall(yield dt.loadRun(n));else{const e=yield t.functions.eval(this.initValue);this.linkFunccall(e.prepare({}))}e.setUpdateIndicator(this.root,!1)}))}init(){return me(this,void 0,void 0,(function*(){yield this.loadFuncCallById(),yield this.onFuncCallReady(),this.isReady.next(!0)}))}build(){e.empty(this.root),this.root.appendChild(this.buildIO()),this.options.historyEnabled&&this.isHistoryEnabled&&this.buildHistoryBlock(),this.buildRibbonMenu(),this.buildRibbonPanels()}onComparisonLaunch(e){return me(this,void 0,void 0,(function*(){const n=this.comparatorFunc;if(n){const i=yield t.functions.eval(n),o=(yield i.prepare({params:{comparedRuns:e}}).call()).outputs.comparisonView;return void t.shell.addView(o)}const i=t.shell.v.parentCall,o=[...t.shell.views].find((t=>t.type===v)),s=yield oe.fromComparedRuns(e,this.func,{parentView:o,parentCall:i});t.shell.addView(s),s.defaultCustomize();const r=this.compareCustomizer;if(r){const e=yield t.functions.eval(r);yield e.prepare({params:{defaultView:s}}).call()}}))}onSaveClick(){return me(this,void 0,void 0,(function*(){yield this.saveRun(this.funcCall)}))}buildHistoryBlock(){const n=te.historyPanel(this.func);let i=!1;return this.subs.push(n.onCompactModeChanged.subscribe((e=>{const n=t.shell.dockManager.findNode(this.historyRoot);n&&(t.shell.dockManager.close(n),e?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3))})),n.onRunChosen.subscribe((t=>me(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0),yield this.loadRun(t),e.setUpdateIndicator(this.root,!1)})))),n.onComparison.subscribe((t=>me(this,void 0,void 0,(function*(){Lt(n.root,!0);const e=yield Promise.all(t.map((t=>dt.loadRun(t))));yield this.onComparisonLaunch(e),Lt(n.root,!1)})))),n.afterRunEdited.subscribe((t=>{var e,n;if(t.id===this.funcCall.id&&t.options.title){this.path=`?id=${this.funcCall.id}`;const i=Nt(t);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=t.options.title)&&void 0!==e?e:i}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=t.options.title)&&void 0!==n?n:i}`}})),t.events.onCurrentViewChanged.subscribe((()=>{var e;if(t.shell.v==this)i&&((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3));else{const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}}))),e.empty(this.historyRoot),this.historyRoot.style.removeProperty("justify-content"),this.historyRoot.append(n.root),this.historyBlock=n,n.root}buildRibbonPanels(){const n=e.iconFA("history",(()=>{var e;t.shell.dockManager.findNode(this.historyRoot)||((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3),this.historyRoot.parentElement.classList.add("ui-box"),this.historyRoot.classList.add("ui-box"))})),i=e.iconFA("save",(()=>me(this,void 0,void 0,(function*(){yield this.onSaveClick()}))),"Save current state"),o=e.comboPopup(e.iconFA("arrow-to-bottom"),this.getFormats(),this.exportRun.bind(this)),r=e.iconFA("edit",(()=>{this.historyBlock&&this.lastCall&&this.historyBlock.showEditDialog(this.historyBlock.history.get(this.funcCall.id))}),"Edit this run metadata"),l=this.isHistorical.subscribe((t=>{t?(e.setDisplay(o,!K(this.funcCall)),e.setDisplay(r,!0)):(a()(o).hide(),a()(r).hide())}));if(this.subs.push(l),e.tooltip.bind(o,(()=>"inconsistent"===this.consistencyState.value&&this.mandatoryConsistent?"Current run is inconsistent. Export feature is disabled.":null)),!this.options.isTabbed&&this.mandatoryConsistent){const t=this.consistencyState.pipe((0,s.distinctUntilChanged)()).subscribe((t=>{"inconsistent"===t?(a()(o).addClass("d4-disabled"),a()(o.lastChild).css("color","unset")):(a()(o).removeClass("d4-disabled"),a()(o.lastChild).removeProp("color"))}));this.subs.push(t)}const u=[[...!this.options.isTabbed&&this.isHistoryEnabled&&this.options.historyEnabled?[n]:[],...!this.options.isTabbed&&this.isHistoryEnabled?[i]:[],...!this.options.isTabbed&&this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0?[o]:[],...this.options.isTabbed?[]:[r]]];return this.setRibbonPanels(u),u}buildRibbonMenu(){if(this.ribbonMenu.clear(),!(this.exportConfig||this.reportBug||this.requestFeature||this.getHelp||this.getMocks||this.getTemplates))return;const t=this.ribbonMenu.group("Model");if(this.getMocks&&this.getMocks.length>0)if(1===this.getMocks.length)t.item("Input data mock",this.getMocks[0].action);else{const e=t.group("Input data mocks");this.getMocks.forEach((t=>{e.item(t.mockName,t.action)})),t.endGroup()}if(this.getTemplates&&this.getTemplates.length>0)if(1===this.getTemplates.length)t.item("Input data template",this.getTemplates[0].action);else{const e=t.group("Input data templates");this.getTemplates.forEach((t=>{e.item(t.name,t.action)})),t.endGroup()}this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0&&t.group("Export").items(this.getFormats(),this.exportRun.bind(this)).endGroup(),this.reportBug&&t.item("Report a bug",(()=>this.reportBug())),this.requestFeature&&t.item("Request a feature",(()=>this.requestFeature())),this.getHelp&&t.item("Help",(()=>this.getHelp()));const n=t.group("Test runner");n.item("Execute Test JSON",(()=>this.importRunJsonDialog())),n.item("Update Test JSON",(()=>this.importRunJsonDialog(!0))),t.endGroup(),t.item("Record the screen",ye),this.getAbout&&t.item("About",(()=>me(this,void 0,void 0,(function*(){const t=yield this.getAbout();if(t){const n=e.dialog("Current version");t.split("\n").forEach((t=>n.add(e.label(t)))),n.onOK((()=>{})),n.getButton("CANCEL").style.display="none",n.show({center:!0})}}))))}exportRun(t){return me(this,void 0,void 0,(function*(){if(t!==ge)o.Utils.download(this.exportConfig.filename(t),yield this.exportConfig.export(t));else{const t=yield this.exportRunJson();t&&o.Utils.download(this.defaultExportFilename("","json"),t)}}))}getFormats(){var t,e;return[...null!==(e=null===(t=this.exportConfig)||void 0===t?void 0:t.supportedFormats)&&void 0!==e?e:[],ge]}onBeforeSaveRun(t){return me(this,void 0,void 0,(function*(){}))}onAfterSaveRun(t){return me(this,void 0,void 0,(function*(){}))}saveRun(e){return me(this,void 0,void 0,(function*(){let n=et(e);var i;yield this.onBeforeSaveRun(n),K(e)&&(n=yield(i=e,q(void 0,void 0,void 0,(function*(){const e=(yield t.functions.eval(i.func.nqName)).prepare([...i.inputs].reduce(((t,[e,n])=>(t[e]=n,t)),{}));return i.options.forEach((t=>e.options[t]=i.options[t])),e})))),n.id&&n.newId();const o=yield dt.saveRun(n),s=yield dt.loadRun(o.id);return this.options.historyEnabled&&this.isHistoryEnabled&&this.historyBlock&&this.historyBlock.addRun(s),this.linkFunccall(s),this.isHistorical.next(!0),yield this.onAfterSaveRun(o),o}))}onBeforeDeleteRun(t){return me(this,void 0,void 0,(function*(){}))}onAfterDeleteRun(t){return me(this,void 0,void 0,(function*(){}))}deleteRun(t){return me(this,void 0,void 0,(function*(){return yield this.onBeforeDeleteRun(t),yield dt.deleteRun(t),yield this.onAfterDeleteRun(t),t.id}))}onBeforeLoadRun(){return me(this,void 0,void 0,(function*(){}))}onAfterLoadRun(t){return me(this,void 0,void 0,(function*(){}))}loadRun(t){return me(this,void 0,void 0,(function*(){yield this.onBeforeLoadRun();const e=yield dt.loadRun(t);return this.lastCall=et(e),this.linkFunccall(e),this.isHistorical.next(!0),yield this.onAfterLoadRun(e),e}))}onBeforeRun(t){return me(this,void 0,void 0,(function*(){}))}onAfterRun(t){return me(this,void 0,void 0,(function*(){}))}run(){return me(this,void 0,void 0,(function*(){if(!this.funcCall)throw new Error("The correspoding function is not specified");yield this.onBeforeRun(this.funcCall);const e=o.TaskBarProgressIndicator.create("Calculating...");try{this.funcCall.newId(),yield this.funcCall.call(),yield this.onAfterRun(this.funcCall),this.lastCall=et(this.funcCall),this.options.isTabbed||this.runningOnInput||!this.isHistoryEnabled||(yield this.saveRun(this.funcCall))}catch(e){t.shell.error(e.toString())}finally{e.close()}}))}exportRunJson(){return me(this,void 0,void 0,(function*(){if(this._lastCall)return function(t,e=2){return JSON.stringify(t,((t,e)=>e instanceof o.DataFrame?{[se]:"DataFrame",value:Array.from(e.toByteArray())}:e instanceof ArrayBuffer?{[se]:"ArrayBuffer",value:Array.from(new Uint8Array(e))}:e instanceof Map?{[se]:"Map",value:Array.from(e)}:e instanceof Set?{[se]:"Set",value:Array.from(e)}:e),e)}(yield function(t,e){return q(this,void 0,void 0,(function*(){const n={};for(const[i,o]of Object.entries(t.inputs)){const{property:t}=e.funcCall.inputParams[i];n[i]=yield at(t,o,e)}return{inputs:n,outputs:t.outputs}}))}(this._lastCall,this),0)}))}importRunJsonDialog(){return me(this,arguments,void 0,(function*(t=!1){const n=new St("JSON file",null,null,"application/json"),i={modal:!0,fullScreen:!0,width:500,height:200,center:!0};if(!(yield new Promise(((t,o)=>{e.dialog({title:"Import Run JSON"}).add(e.div([e.inputs([n])])).onOK((()=>t(!0))).onCancel((()=>t(!1))).show(i)})))||!n.value)return;const o=(r=yield n.value.text(),JSON.parse(r,re));var r;t?(yield this.executeTest(o,!0),yield this.isHistorical.pipe((0,s.filter)((t=>t)),(0,s.take)(1),(0,s.delay)(0)).toPromise(),yield this.exportRun(ge)):yield this.executeTest(o)}))}executeTest(t){return me(this,arguments,void 0,(function*(t,e=!1){yield fe(t,this,{updateMode:e,interactive:!0})}))}get compareCustomizer(){var t;return null!==(t=this.func.options.compareCustomizer)&&void 0!==t?t:null}get comparatorFunc(){var t;return null!==(t=this.func.options.comparatorFunc)&&void 0!==t?t:null}get uploadFunc(){var t;return null!==(t=this.func.options.uploadFunc)&&void 0!==t?t:null}get runningOnInput(){return"true"===this.func.options.runOnInput}get runningOnStart(){return"true"===this.func.options.runOnOpen}get mainParams(){return this.func.options.mainParams?JSON.parse(this.func.options.mainParams):null}get mandatoryConsistent(){var t;return"true"===(null===(t=this.parentCall)||void 0===t?void 0:t.func.options.mandatoryConsistent)}get hasContextHelp(){return!!this.func.options.help}getContextHelp(){return me(this,void 0,void 0,(function*(){const e=this.func.options.help;if(!e)return null;if(this.helpCache)return this.helpCache;const n=`System:AppData/${e}`;if(yield t.dapi.files.exists(n)){const e=yield t.dapi.files.readAsText(n);return this.helpCache=e,e}const i=`${t.shell.user.name}.home/${e}`;if(yield t.dapi.files.exists(i)){const e=yield t.dapi.files.readAsText(i);return this.helpCache=e,e}return null}))}get features(){var t;return JSON.parse(null!==(t=this.func.options.features)&&void 0!==t?t:"{}")}getFeature(t,e){var n;return this.features instanceof Array?this.features.includes(t):this.features instanceof Object&&null!==(n=this.features[t])&&void 0!==n?n:e}get isExportEnabled(){return this.getFeature("export",!0)}get isHistoryEnabled(){return this.getFeature("history",!0)}get isSaEnabled(){return this.getFeature("sens-analysis",!1)}get hasUploadMode(){return this.getFeature("upload",!1)}get isFittingEnabled(){return this.getFeature("fitting",!1)}}var Ae=Uint8Array,Ce=Uint16Array,we=Uint32Array,Ie=new Ae([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Te=new Ae([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ee=(new Ae([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),function(t,e){for(var n=new Ce(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];var o=new we(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)o[s]=s-n[i]<<5|i;return[n,o]}),xe=Ee(Ie,2),Re=xe[0],Se=xe[1];Re[28]=258,Se[258]=28;for(var Oe=Ee(Te,0),Pe=(Oe[0],Oe[1],new Ce(32768)),Fe=0;Fe<32768;++Fe){var _e=(43690&Fe)>>>1|(21845&Fe)<<1;_e=(61680&(_e=(52428&_e)>>>2|(13107&_e)<<2))>>>4|(3855&_e)<<4,Pe[Fe]=((65280&_e)>>>8|(255&_e)<<8)>>>1}var ke=new Ae(288);for(Fe=0;Fe<144;++Fe)ke[Fe]=8;for(Fe=144;Fe<256;++Fe)ke[Fe]=9;for(Fe=256;Fe<280;++Fe)ke[Fe]=7;for(Fe=280;Fe<288;++Fe)ke[Fe]=8;var Me=new Ae(32);for(Fe=0;Fe<32;++Fe)Me[Fe]=5;var Be=new Ae(0),Le="undefined"!=typeof TextDecoder&&new TextDecoder;try{Le.decode(Be,{stream:!0})}catch(t){}"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout&&setTimeout;var De=n(933),Ne={};Ne.styleTagTransform=It(),Ne.setAttributes=bt(),Ne.insert=gt().bind(null,"head"),Ne.domAPI=mt(),Ne.insertStyleElement=Ct(),ht()(De.A,Ne),De.A&&De.A.locals&&De.A.locals;var Ve=n(362),je={};je.styleTagTransform=It(),je.setAttributes=bt(),je.insert=gt().bind(null,"head"),je.domAPI=mt(),je.insertStyleElement=Ct(),ht()(Ve.A,je),Ve.A&&Ve.A.locals&&Ve.A.locals;var $e,Ye;!function(t){t.INCORRECT_SIZE_TYPE="Size must be an integer.",t.SIZE_MUST_BE_POSITIVE="Size must be positive."}($e||($e={})),function(t){t[t.BATCH_SIZE=100]="BATCH_SIZE",t[t.MS_TO_SLEEP=10]="MS_TO_SLEEP"}(Ye||(Ye={}));const He=t=>new Promise(((e,n)=>setTimeout(e,t)));function Ue(t){if(!Number.isInteger(t))throw new Error($e.INCORRECT_SIZE_TYPE);if(t<1)throw new Error($e.SIZE_MUST_BE_POSITIVE)}function We(t){return e=this,n=void 0,s=function*(){const e=[],n=o.TaskBarProgressIndicator.create("Running sensitivity analysis...");n.cancelable=!0;let i=0;const s=t.length;for(let o=0;o<s&&(e.push(yield t[o].call()),1===o&&(n.update(100*o/s,"Running sensitivity analysis..."),yield He(10*Ye.MS_TO_SLEEP)),++i,!n.canceled);++o)i>=Ye.BATCH_SIZE&&(n.update(100*o/s,"Running sensitivity analysis..."),yield He(Ye.MS_TO_SLEEP),i=0);return n.close(),e},new((i=void 0)||(i=Promise))((function(t,o){function r(t){try{l(s.next(t))}catch(t){o(t)}}function a(t){try{l(s.throw(t))}catch(t){o(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((s=s.apply(e,n||[])).next())}));var e,n,i,s}class Ge{constructor(t=1,e=1){Ue(t),Ue(e),this.N=t,this.d=e,this.A=this.generateMatrix(t,e),this.B=this.generateMatrix(t,e),this.AB=this.createMixMatrax(this.A,this.B)}generateMatrix(t,e){const n=new Array(e);for(let i=0;i<e;++i){n[i]=new Float32Array(t);for(let e=0;e<t;++e)n[i][e]=Math.random()}return n}createMixMatrax(t,e){const n=this.d,i=new Array(n);for(let o=0;o<n;++o){i[o]=new Array(0);for(let s=0;s<n;++s)o!==s?i[o].push(t[s]):i[o].push(e[s])}return i}getRow(t,e){const n=new Float32Array(this.d);for(let i=0;i<this.d;++i)n[i]=t[i][e];return n}getRowOfMatrixA(t){return this.getRow(this.A,t)}getRowOfMatrixB(t){return this.getRow(this.B,t)}getRowOfMatrixAB(t,e){return this.getRow(this.AB[t],e)}getConcatenatedColumns(){const t=new Array(0),e=this.N,n=this.d;for(let i=0;i<n;++i){const o=new Float32Array(e*(n+2));o.set(this.A[i]),o.set(this.B[i],e);for(let t=0;t<n;++t)o.set(this.AB[t][i],2*e+e*t);t.push(o)}return t}}const ze="Unsupported output type.";function Je(e,n){const i=e.rowCount,s=n.value.row;if(null!==s)return e.columns.names().map((t=>({idx:s,columnName:t})));const r=e.col(n.value.colName);if(null===r)return t.shell.warning(`Output dataframe "${e.name}" doesn't contain the "${n.value.colName}" column. The last row is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));if(r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.FLOAT)return t.shell.warning(`Non-supported type of the "${n.value.colName}" column: ${r.type}. Last row of the output dataframe "${e.name}" is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));const a=r.getRawData(),l=n.value.colValue;let u,c=0,d=Math.abs(a[0]-l);for(let t=1;t<i;++t)u=Math.abs(a[t]-l),u<d&&(d=u,c=t);return e.columns.names().map((t=>({idx:c,columnName:t})))}function qe(t,e){var n,i,s;if(t.length<1)throw new Error("Funccall array is empty.");const r=t.length,a=function(t,e){const n=[];for(const i of e)i.prop.propertyType==o.TYPE.DATA_FRAME?n.push({prop:i.prop,elements:Je(t.outputs[i.prop.name],i)}):n.push({prop:i.prop,elements:[]});return n}(t[0],e),l=function(t,e,n){var i;const s=[];for(const r of e){const e=r.prop,a=e.name;switch(e.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:s.push(o.Column.fromType(e.propertyType,a,n));break;case o.TYPE.DATA_FRAME:const l=t.outputs[a];if(r.elements)for(const t of r.elements)s.push(o.Column.fromType(null===(i=l.col(t.columnName))||void 0===i?void 0:i.type,t.columnName,n));break;default:throw new Error(ze)}}return o.DataFrame.fromColumns(s)}(t[0],a,r);for(let e=0;e<r;++e)for(const r of a){const a=r.prop,u=a.name,c=t[e];switch(a.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:null===(n=l.col(u))||void 0===n||n.set(e,c.outputs[u]);break;case o.TYPE.DATA_FRAME:const t=c.outputs[u],a=t.rowCount-1;if(r.elements)for(const n of r.elements)null===(i=l.col(n.columnName))||void 0===i||i.set(e,null===(s=t.col(n.columnName))||void 0===s?void 0:s.get(-1!==n.idx?n.idx:a));break;default:throw new Error(ze)}}return l}function Ke(t,e){const n=function(t,e){return e.forEach((e=>{t.forEach((t=>{t.name===e.name&&(t.name=`${t.name} (input)`,e.name=`${e.name} (output)`)}))})),t.concat(e)}(t,e),i=n.length;if(0===i)return o.DataFrame.create();const s=o.DataFrame.fromColumns([n[0]]);for(let t=1;t<i;++t)n[t].name=s.columns.getUnusedName(n[t].name),s.columns.add(n[t]);return s}class Ze{constructor(t,e,n,i,s){Ue(s),this.samplesCount=s,this.fixedInputs=e,this.func=t;const r=function(t,e){const n=e.length,i=function(t,e){return new Ge(t,e).getConcatenatedColumns()}(t,n);return[...Array(n).keys()].map((t=>function(t,e){var n;const i=e.length,s=o.Column.fromType(t.prop.propertyType,null!==(n=t.prop.caption)&&void 0!==n?n:t.prop.name,i),r=s.getRawData(),a=t.max-t.min;for(let n=0;n<i;++n)r[n]=t.min+a*e[n];return s}(e[t],i[t])))}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.runsCount=s*(this.dimension+2),this.funcCalls=[];for(let n=0;n<this.runsCount;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}getSobolIndeces(t){const e=this.dimension,n=this.samplesCount,i=new Float32Array(e),s=new Float32Array(e),r=t.getRawData(),a=2*n;let l=0,u=0;for(let t=0;t<a;++t)l+=r[t],u+=r[t]*r[t];const c=l/a,d=u/a-c*c;if(0===d)i.fill(0),s.fill(0);else for(let t=0;t<e;++t){let e=0,o=0,a=0;for(let i=0;i<n;++i)a=r[(2+t)*n+i]-r[i],e+=r[n+i]*a,o+=a*a;i[t]=e/(n*d),s[t]=o/(2*n*d)}return{firstOrder:o.Column.fromFloat32Array(t.name,i),totalOrder:o.Column.fromFloat32Array(t.name,s)}}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield We(this.funcCalls);const t=this.variedInputs.map((t=>t.column)),e=qe(this.funcCalls,this.outputsOfInterest).columns.toList(),n=Ke(t,e);n.name=`Sensitivity Analysis of ${this.func.friendlyName}`;const i=e.map((t=>this.getSobolIndeces(t))),s=o.Column.fromStrings("input",t.map((t=>t.name))),r=[s],a=[s];for(const t of i)r.push(t.firstOrder),a.push(t.totalOrder);const l=o.DataFrame.fromColumns(r);l.name="First order Sobol' indices";const u=o.DataFrame.fromColumns(a);return u.name="Total order Sobol' indices",{funcEvalResults:n,funcCalls:this.funcCalls,firstOrderSobolIndices:l,totalOrderSobolIndices:u}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}class Xe{constructor(t,e,n,i,s){Ue(s),this.func=t;const r=function(t,e){var n;const i=[];for(const s of e){const e=o.Column.fromType(s.prop.propertyType,null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name,t),r=e.getRawData(),a=s.max-s.min;for(let e=0;e<t;++e)r[e]=s.min+a*Math.random();i.push(e)}return i}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.funcCalls=[];for(let n=0;n<s;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield We(this.funcCalls);const t=Ke(this.variedInputs.map((t=>t.column)),qe(this.funcCalls,this.outputsOfInterest).columns.toList());return t.name=`Sensitivity Analysis of ${this.func.friendlyName}`,{funcEvalResults:t,funcCalls:this.funcCalls}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}var Qe,tn,en=n(993),nn={};nn.styleTagTransform=It(),nn.setAttributes=bt(),nn.insert=gt().bind(null,"head"),nn.domAPI=mt(),nn.insertStyleElement=Ct(),ht()(en.A,nn),en.A&&en.A.locals&&en.A.locals,function(t){t[t.COR_PLOT=.5]="COR_PLOT",t[t.PC_PLOT=.6]="PC_PLOT",t[t.GRAPH=.6]="GRAPH",t[t.BAR_CHART=.2]="BAR_CHART"}(Qe||(Qe={})),function(t){t.METHOD="`Method`",t.SAMPLES="`Samples`"}(tn||(tn={}));const on=`# Sensitivity Analysis\n\nSensitivity Analysis runs the computation multiple times with varying inputs, \nand analyzes the relationship between inputs and outputs.\n\nUse one of the following methods:\n\n* [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method) explores a function \nat randomly taken points\n\n* [Sobol](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis)\ndecomposes output variance into fractions, which can be attributed to inputs\n\n* **Grid** studies a function at the points of a grid with the specified step\n\n## Monte Carlo\n\nOnce you've chosen it in ${tn.METHOD}\n\n* Set in ${tn.SAMPLES} the number of random points \n\n* Use switchers to specify varied inputs and outputs to be analyzed\n\n* Press **Run** or <i class="fas fa-play"></i> on the top panel. You will get \n\n * [Correlation plot](https://datagrok.ai/help/visualize/viewers/correlation-plot) for exploring\ncorrelations between varied inputs and the specified outputs\n\n * [PC plot](https://datagrok.ai/help/visualize/viewers/pc-plot) visualizing multivariate data\nand providing variations of the selected inputs & outputs\n\n * [Line chart](https://datagrok.ai/help/visualize/viewers/line-chart) or \n[Scatterplot](https://datagrok.ai/help/visualize/viewers/scatter-plot) (dependently on the varied\ninputs count) showing a behavior of each output separately\n\n * [Grid](https://datagrok.ai/help/visualize/viewers/grid) containing inputs and outputs values \nof each function evaluation\n\n* Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[Sensitivity Analysis](https://datagrok.ai/help/compute/#sensitivity-analysis)\n\n## Sobol\n\nThis method performs \n[variance-based sensitivity analysis](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis). \nIt provides the same visualizations \nas **Monte Carlo** and [bar charts](https://datagrok.ai/help/visualize/viewers/bar-chart) showing \nSobol' indices:\n\n* First-order indices indicate the contribution to the output variance of varying each input alone\n\n* Total-order indices measure the contribution to the output variance of each input,\n including all variance caused by its interactions with any other inputs\n \n ## Grid\n \n This method provides the same visualization as the previous ones. Unlike them, it evaluates a function \n at the points of uniform grid within the specified ranges.`;var sn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const rn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME],an=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME];var ln,un;!function(t){t.GRID_ANALYSIS="Grid",t.RANDOM_ANALYSIS="Monte Carlo",t.SOBOL_ANALYSIS="Sobol"}(ln||(ln={})),function(t){t.LAST_ROW="Last row",t.FIRST_ROW="First row",t.ALL_COLUMNS="",t.BY_COL_VAL="By value in column"}(un||(un={}));const cn=()=>e.div([],"sa-switch-input");class dn{static fromEmpty(e){return sn(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield oe.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(t,n,i={parentView:void 0,parentCall:void 0,configFunc:void 0}){this.func=t,this.options=i,this.generateInputFields=t=>{const n={analysisType:{input:e.choiceInput("Method",ln.RANDOM_ANALYSIS,[ln.RANDOM_ANALYSIS,ln.SOBOL_ANALYSIS,ln.GRID_ANALYSIS],(t=>{n.analysisType.value.next(t),this.updateRunWidgetsState(),this.setAnalysisInputTooltip(),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip())})),value:new c.BehaviorSubject(ln.RANDOM_ANALYSIS)},samplesCount:{input:e.intInput("Samples",10,(t=>{n.samplesCount.value=t,this.updateRunWidgetsState()})),value:10}};n.analysisType.input.root.insertBefore(cn(),n.analysisType.input.captionLabel),n.samplesCount.input.root.insertBefore(cn(),n.samplesCount.input.captionLabel);const i=(t,e)=>void 0===t.options[e]?Bt(t):Number(t.options[e]),s=(t,n,i=!0)=>{const o=e.switchInput(" ",t,n);return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch to mark input as immutable":"Switch to mark input as mutable":o.value?"Switch to mark output as not requiring analysis":"Switch to mark output as requiring analysis")),o},r=t.inputs.reduce(((t,r)=>{const l=i(r,"default");switch(r.propertyType){case o.TYPE.INT:case o.TYPE.BIG_INT:case o.TYPE.FLOAT:const u=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),d=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),p={type:r.propertyType,prop:r,const:{input:(()=>{var t;const n=e.intInput(null!==(t=r.caption)&&void 0!==t?t:r.name,Bt(r),(t=>f.const.value=t));return n.root.insertBefore(d.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:Bt(r)},min:{input:(()=>{var t;const n=e.floatInput(`${null!==(t=r.caption)&&void 0!==t?t:r.name} min`,i(r,"min"),(t=>f.min.value=t));return n.root.insertBefore(u.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:i(r,"min")},max:{input:(()=>{var t;const n=e.floatInput(`${null!==(t=r.caption)&&void 0!==t?t:r.name} max`,i(r,"max"),(t=>f.max.value=t));return n.addPostfix(r.options.units),n})(),value:i(r,"max")},lvl:{input:e.intInput("Samples",3,(t=>{f.lvl.value=t,this.updateRunWidgetsState()})),value:3},isChanging:new c.BehaviorSubject(!1)};[p.max.input,p.lvl.input].forEach((t=>{t.root.insertBefore(cn(),t.captionLabel),a()(t.root).removeProp("display")}));const h=[p.lvl.input];t[r.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input,...h]});const f=t[r.name];f.isChanging.subscribe((t=>{u.notify=!1,u.value=t,u.notify=!0,d.notify=!1,d.value=t,d.notify=!0})),(0,c.combineLatest)([p.isChanging,n.analysisType.value]).subscribe((([t,e])=>{t?(f.constForm.forEach((t=>a()(t.root).hide())),f.saForm.forEach((t=>a()(t.root).css("display","flex"))),h.forEach((t=>e===ln.GRID_ANALYSIS?a()(t.root).css("display","flex"):a()(t.root).hide()))):(f.constForm.forEach((t=>a()(t.root).css("display","flex"))),f.saForm.forEach((t=>a()(t.root).hide())))}));break;case o.TYPE.BOOL:const m=s(!1,(t=>{g.isChanging.next(t),this.updateRunWidgetsState()})),v={type:r.propertyType,prop:r,const:{input:(()=>{var t,n;const i=e.boolInput(`${null!==(t=r.caption)&&void 0!==t?t:r.name}`,null!==(n=Bt(r))&&void 0!==n&&n,(t=>g.const.value=t));return i.root.insertBefore(m.root,i.captionLabel),i})(),value:l},isChanging:new c.BehaviorSubject(!1),lvl:1};t[r.name]=Object.assign(Object.assign({},v),{constForm:[v.const.input],saForm:[]});const g=t[r.name];g.isChanging.subscribe((t=>{g.lvl=t?2:1}));break;default:const y=cn(),b={input:(()=>{const t=e.input.forProperty(r,void 0,{onValueChanged:t=>b.value=t.value});return t.root.insertBefore(y,t.captionLabel),t.addPostfix(r.options.units),t})(),value:Bt(r)};t[r.name]={const:b,constForm:[b.input],saForm:[],type:r.propertyType,prop:r,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),l=t.outputs.reduce(((t,n)=>{const i={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name;let a;n.propertyType===o.TYPE.DATA_FRAME?(a=e.choiceInput(r,un.LAST_ROW,[un.LAST_ROW,un.FIRST_ROW,un.BY_COL_VAL],(t=>{i.value.returning=t,i.analysisInputs.forEach((e=>{e.root.hidden=t!==un.BY_COL_VAL})),a.setTooltip(this.getOutputTooltip(r,t))})),a.setTooltip(this.getOutputTooltip(r,un.LAST_ROW))):(a=e.input.forProperty(n),a.setTooltip("Scalar")),a.addCaption(r);const l=an.includes(n.propertyType)?s(!0,(t=>{i.isInterest.next(t),i.analysisInputs.forEach((t=>{t.root.hidden=i.value.returning!==un.BY_COL_VAL})),this.updateRunWidgetsState(),n.propertyType===o.TYPE.DATA_FRAME&&a.setTooltip(t?this.getOutputTooltip(r,un.LAST_ROW):"Dataframe")}),!1).root:cn();return a.root.insertBefore(l,a.captionLabel),a})(),analysisInputs:n.propertyType===o.TYPE.DATA_FRAME?[(()=>{var t;const o=e.stringInput("Column",un.ALL_COLUMNS,(t=>{i.value.colName=t}));return o.root.insertBefore(cn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Name of column of the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe`),o})(),(()=>{var t;const o=e.floatInput("Value",0,(t=>{i.value.colValue=t}));return o.root.insertBefore(cn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Value specifying the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe row`),o})()]:[],value:{returning:un.LAST_ROW,colName:un.ALL_COLUMNS,colValue:0},isInterest:new c.BehaviorSubject(!0)};return a()(i.input.input).css("visibility","hidden"),i.prop.propertyType===o.TYPE.DATA_FRAME&&i.isInterest.subscribe((t=>{i.analysisInputs.forEach((e=>t?a()(e.root).show():a()(e.root).hide())),a()(i.input.input).css("visibility",t?"visible":"hidden")})),t[n.name]=i,t}),{});return{analysisInputs:n,inputs:r,outputs:l}},this.openedViewers=[],this.gridSubscription=null,this.store=this.generateInputFields(this.func),this.runButton=e.bigButton("Run",(()=>sn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon=e.iconFA("play",(()=>sn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon.style.color="var(--green-2)",this.runIcon.classList.add("fas"),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute.md#sensitivity-analysis","_blank")}),"Open help in a new tab");const s=this.buildFormWithBtn();this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled,this.addTooltips(),this.comparisonView=n,this.comparisonView.dockManager.dock(s,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Sensitivity Analysis`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1;const r=this.comparisonView.getRibbonPanels();r.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(r),this.comparisonView.helpUrl="https://datagrok.ai/help/compute.md#sensitivity-analysis",this.tableDockNode=this.comparisonView.dockManager.findNode(this.comparisonView.grid.root);const l=e.markdown(on);l.style.padding="10px",l.style.overflow="auto",this.helpMdNode=this.comparisonView.dockManager.dock(l,o.DOCK_TYPE.FILL,this.tableDockNode,"About")}closeOpenedViewers(){for(const t of this.openedViewers)t.close();this.openedViewers.splice(0),this.helpMdNode&&(this.helpMdNode.detachFromParent(),this.helpMdNode.container.destroy(),this.helpMdNode=void 0),this.gridSubscription&&(this.gridSubscription.unsubscribe(),this.gridSubscription=null)}getFuncCallCount(t,e){let n=0;switch(t.analysisType.value.value){case ln.GRID_ANALYSIS:let i=1;const s=t=>t.type===o.TYPE.INT||t.type===o.TYPE.BIG_INT||t.type===o.TYPE.FLOAT;for(const t of Object.values(e))t.isChanging.value&&(i*=s(t)?t.lvl.value:t.lvl,++n);return 0===n?0:i;case ln.RANDOM_ANALYSIS:return t.samplesCount.value;case ln.SOBOL_ANALYSIS:for(const t of Object.keys(e))e[t].isChanging.value&&++n;return 0===n?0:(n+2)*t.samplesCount.value;default:return 0}}getFuncCallCountAsString(){if(!this.canEvaluationBeRun())return"0";const t=this.getFuncCallCount(this.store.analysisInputs,this.store.inputs);return t<1e3?String(t):t<1e6?String(Math.ceil(t/10)/100)+"k":t<1e9?String(Math.ceil(t/1e4)/100)+"m":String(Math.ceil(t/1e7)/100)+"b"}updateRunWidgetsState(){this.runButton.textContent=`Run (${this.getFuncCallCountAsString()})`,this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled}buildFormWithBtn(){let t="Misc";const n=Object.values(this.store.inputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(...i.constForm.map((t=>t.root)),...i.saForm.map((t=>t.root))),n}),e.div([this.store.analysisInputs.analysisType.input,this.store.analysisInputs.samplesCount.input],{style:{"overflow-y":"scroll",width:"100%"}}));a()(n).addClass("ui-form");const i=e.h2("Outputs");n.appendChild(i),t="Misc";const o=Object.values(this.store.outputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(i.input.root,...i.analysisInputs.map((t=>t.root))),n}),n);this.store.analysisInputs.analysisType.value.subscribe((t=>{t===ln.GRID_ANALYSIS?a()(this.store.analysisInputs.samplesCount.input.root).hide():(a()(i).show(),a()(o).show(),a()(this.store.analysisInputs.samplesCount.input.root).show())}));let s=!1;for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value){s=!0;break}s||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0),this.updateRunWidgetsState();const r=e.buttonsInput([this.runButton]);return n.appendChild(r),a()(n).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),n}setAnalysisInputTooltip(){let t;switch(this.store.analysisInputs.analysisType.value.value){case ln.GRID_ANALYSIS:t="Grid analysis: the function is evaluated with respect to the selected inputs varying within the specified ranges";break;case ln.RANDOM_ANALYSIS:t="Monte Carlo simulation: the function is evaluated with respect to random variation of the selected inputs within the specified ranges";break;case ln.SOBOL_ANALYSIS:t="Variance-based sensitivity analysis: the Sobol' indices are computed";break;default:t="Unknown method!"}this.store.analysisInputs.analysisType.input.setTooltip(t)}getOutputTooltip(t,e){switch(e){case un.FIRST_ROW:return`To analyze first row of the '${t}' dataframe`;case un.LAST_ROW:return`To analyze last row of the '${t}' dataframe`;case un.BY_COL_VAL:return`To analyze "${t}"'s row defined by custom value in column`;default:return""}}samplesCountTooltip(){switch(this.store.analysisInputs.analysisType.value.value){case ln.RANDOM_ANALYSIS:return"Input sets count";case ln.SOBOL_ANALYSIS:return"Sample size for the Sobol' indices computation";default:return"Unknown method!"}}addTooltips(){var t;this.setAnalysisInputTooltip(),e.tooltip.bind(this.runButton,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),e.tooltip.bind(this.runIcon,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip());for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e].prop.propertyType;if(n===o.TYPE.BOOL||n===o.TYPE.STRING)continue;const i=this.store.inputs[e],s=null!==(t=i.prop.caption)&&void 0!==t?t:i.prop.name;i.const.input.setTooltip(`'${s}' value`),i.min.input.setTooltip(`Min value of '${s}'`),i.max.input.setTooltip(`Max value of '${s}'`),i.lvl.input.setTooltip(`Number of samples along the axis '${s}'`)}}isAnyInputSelected(){for(const t of Object.keys(this.store.inputs))if(this.store.inputs[t].isChanging.value)return!0;return!1}isAnyOutputSelected(){for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value)return!0;return!1}canEvaluationBeRun(){return this.isAnyInputSelected()&&this.isAnyOutputSelected()}runAnalysis(){return sn(this,void 0,void 0,(function*(){if(this.canEvaluationBeRun())switch(this.store.analysisInputs.analysisType.value.value){case ln.GRID_ANALYSIS:yield this.runGridAnalysis();break;case ln.RANDOM_ANALYSIS:yield this.runRandomAnalysis();break;case ln.SOBOL_ANALYSIS:yield this.runSobolAnalysis()}}))}getFixedInputColumns(t){return Object.values(this.store.inputs).filter((t=>!rn.includes(t.type)||!t.isChanging.value)).map((e=>{var n;return o.Column.fromList(e.type,null!==(n=e.prop.caption)&&void 0!==n?n:e.prop.name,Array(t).fill(e.const.value))}))}runSobolAnalysis(){return sn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new Ze(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform();this.closeOpenedViewers();const l=r.funcEvalResults,u=r.funcCalls,c=r.firstOrderSobolIndices,d=r.totalOrderSobolIndices,p=c.columns.names();this.comparisonView.dataFrame=l;const h=l.columns.names(),f=this.getFixedInputColumns(l.rowCount);for(const t of f)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([h[0]]),this.comparisonView.grid.columns.setVisible(h),this.comparisonView.grid.props.rowHeight=25;const m=o.Viewer.correlationPlot(l,{xColumnNames:h,yColumnNames:h}),v=this.comparisonView.dockManager.dock(m,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Qe.COR_PLOT);this.openedViewers.push(m);const g=o.Viewer.pcPlot(l,{columnNames:h});this.comparisonView.dockManager.dock(g,o.DOCK_TYPE.DOWN,v,"",Qe.PC_PLOT),this.openedViewers.push(g);const y=this.getOutputNameForScatterPlot(h,l,n.variedInputs.length),b=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(h)):o.Viewer.scatterPlot(l,this.getScatterOpt(h,y));this.openedViewers.push(b),this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Qe.GRAPH);const A=o.Viewer.barChart(c,this.getBarChartOpt(c.name,p[0],y)),C=this.comparisonView.dockManager.dock(A,o.DOCK_TYPE.RIGHT,void 0,"",Qe.BAR_CHART),w=o.Viewer.barChart(d,this.getBarChartOpt(d.name,p[0],y));this.comparisonView.dockManager.dock(w,o.DOCK_TYPE.DOWN,C),this.openedViewers=this.openedViewers.concat([A,w]),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!rn.includes(this.store.inputs[t].type)||!this.store.inputs[t].isChanging.value))}getVariedInputs(){return Object.keys(this.store.inputs).filter((t=>!!rn.includes(this.store.inputs[t].type)&&this.store.inputs[t].isChanging.value))}runRandomAnalysis(){return sn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new Xe(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform(),l=r.funcEvalResults,u=r.funcCalls;this.closeOpenedViewers(),this.comparisonView.dataFrame=l;const c=l.columns.names(),d=this.getFixedInputColumns(l.rowCount);for(const t of d)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([c[0]]),this.comparisonView.grid.columns.setVisible(c),this.comparisonView.grid.props.rowHeight=25;const p=o.Viewer.correlationPlot(l,{xColumnNames:c,yColumnNames:c}),h=this.comparisonView.dockManager.dock(p,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Qe.COR_PLOT);this.openedViewers.push(p);const f=o.Viewer.pcPlot(l,{columnNames:c});this.comparisonView.dockManager.dock(f,o.DOCK_TYPE.DOWN,h,"",Qe.PC_PLOT),this.openedViewers.push(f);const m=this.getOutputNameForScatterPlot(c,l,n.variedInputs.length),v=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(c)):o.Viewer.scatterPlot(l,this.getScatterOpt(c,m));this.openedViewers.push(v),this.comparisonView.dockManager.dock(v,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Qe.GRAPH),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}runGridAnalysis(){return sn(this,void 0,void 0,(function*(){var n,i;const s=Object.keys(this.store.inputs).reduce(((t,e)=>{switch(this.store.inputs[e].type){case o.TYPE.INT:case o.TYPE.BIG_INT:const n=this.store.inputs[e],i=(n.max.value-n.min.value)/(n.lvl.value-1);t[e]=n.isChanging.value?Array.from({length:n.lvl.value},((t,e)=>Math.round(n.min.value+e*i))):[n.const.value];break;case o.TYPE.FLOAT:const s=this.store.inputs[e],r=(s.max.value-s.min.value)/(s.lvl.value-1);t[e]=s.isChanging.value?Array.from({length:s.lvl.value},((t,e)=>s.min.value+e*r)):[s.const.value];break;case o.TYPE.BOOL:const a=this.store.inputs[e];t[e]=a.isChanging.value?[a.const.value,!a.const.value]:[a.const.value];break;default:const l=this.store.inputs[e];t[e]=[l.const.value]}return t}),{});let r=Object.values(s)[0].map((t=>[t]));for(let t=1;t<Object.values(s).length;t++){const e=Object.values(s)[t],n=[];for(const t of r)for(const i of e)n.push([...t,i]);r=n}const l=r.map((t=>this.func.prepare(this.func.inputs.map(((t,e)=>({name:t.name,idx:e}))).reduce(((e,{name:n,idx:i})=>(e[n]=t[i],e)),{})))),u=yield We(l);this.closeOpenedViewers();const c=[],d=u.length,p=this.getFixedInputColumns(d);for(const t of Object.keys(this.store.inputs)){const e=this.store.inputs[t],i=e.prop;e.isChanging.value&&c.push(o.Column.fromType(i.propertyType,null!==(n=i.caption)&&void 0!==n?n:i.name,d))}const h=[...c],f=h.length,m=o.DataFrame.fromColumns([h[0]]);for(let t=1;t<f;++t)h[t].name=m.columns.getUnusedName(h[t].name),m.columns.add(h[t]);for(let t=0;t<d;++t)for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e],o=n.prop;n.isChanging.value&&m.set(null!==(i=o.caption)&&void 0!==i?i:o.name,t,u[t].inputs[e])}const v=this.getOutputsOfInterest(),g=qe(u,v).columns;for(const t of g)h.forEach((e=>{e.name===t.name&&(e.name=`${e.name} (input)`,t.name=`${t.name} (output)`)})),t.name=m.columns.getUnusedName(t.name),m.columns.add(t);const y=m.columns.names();for(const t of p)t.name=m.columns.getUnusedName(`${t.name} (fixed)`),m.columns.add(t);this.comparisonView.dataFrame=m,this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root})),this.comparisonView.grid.columns.setVisible([y[0]]),this.comparisonView.grid.columns.setVisible(y),this.comparisonView.grid.props.rowHeight=25;const b=o.Viewer.correlationPlot(m,{xColumnNames:y,yColumnNames:y}),A=this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Qe.COR_PLOT);this.openedViewers.push(b);const C=o.Viewer.pcPlot(m,{columnNames:y});this.comparisonView.dockManager.dock(C,o.DOCK_TYPE.DOWN,A,"",Qe.PC_PLOT),this.openedViewers.push(C);const w=this.getOutputNameForScatterPlot(y,m,c.length),I=1===c.length?o.Viewer.lineChart(m,this.getLineChartOpt(y)):o.Viewer.scatterPlot(m,this.getScatterOpt(y,w));this.openedViewers.push(I),this.comparisonView.dockManager.dock(I,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Qe.GRAPH)}))}getOutputNameForScatterPlot(t,e,n){var i,o,s,r;for(let a=n;a<t.length;++a)if((null!==(o=null===(i=e.col(t[a]))||void 0===i?void 0:i.min)&&void 0!==o?o:0)<(null!==(r=null===(s=e.col(t[a]))||void 0===s?void 0:s.max)&&void 0!==r?r:0))return t[a];return t[n]}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];if(n.isInterest.value){let e;switch(n.value.returning){case un.LAST_ROW:e=-1;break;case un.FIRST_ROW:e=0;break;default:e=null}t.push({prop:n.prop,value:{row:e,colName:n.value.colName,colValue:n.value.colValue}})}}return t}getScatterOpt(t,e){return{xColumnName:t[0],yColumnName:t[1],colorColumnName:e,sizeColumnName:e,markerMaxSize:12,jitterSize:5}}getLineChartOpt(t){return{xColumnName:t[0],yColumnNames:t.slice(1,Math.min(t.length,8)),markerSize:1,markerType:o.MARKER_TYPE.GRADIENT,multiAxis:!0}}getBarChartOpt(t,e,n){return{description:t,splitColumnName:e,valueColumnName:n,valueAggrType:o.AGG.AVG,showTitle:!1,showCategorySelector:!1,showStackSelector:!1,showValueAxis:!1}}}var pn;!function(t){t.NELDER_MEAD="Nelder-Mead",t.GRAD_DESC="Gradient descent"}(pn||(pn={}));const hn=new Map([[pn.NELDER_MEAD,"The Nelder-Mead method"],[pn.GRAD_DESC,"The gradient descent method"]]);var fn;!function(t){t.MAD="MAD",t.RMSE="RMSE"}(fn||(fn={}));const mn=new Map([[fn.MAD,"Maximum absolute deviation"],[fn.RMSE,"Root mean square error"]]);var vn,gn,yn,bn;!function(t){t[t.LOSS_COL_WIDTH=60]="LOSS_COL_WIDTH",t[t.ROW_HEIGHT=180]="ROW_HEIGHT",t[t.LOSS_GRAPH_WIDTH=360]="LOSS_GRAPH_WIDTH",t[t.GOF_VIEWER_WIDTH=240]="GOF_VIEWER_WIDTH"}(vn||(vn={})),function(t){t.ITER="Iteration",t.LOSS="Loss",t.LOSS_GRAPH="Fitting profile",t.TARGET="Target",t.FIT="Fit",t.METHOD="method",t.VALUE="Value",t.OBJECTIVE="Target",t.SAMPLES="samples",t.ID="id",t.OBTAINED="Simulation",t.LOSS_LOW="loss",t.SIMILARITY="similarity"}(gn||(gn={})),function(t){t.GOAL="`Goal`",t.FIT="`Fit`",t.MIN="`min`",t.MAX="`max`",t.TARGET="`Target`",t.METHOD="`method`",t.CONTEXT="`Context Panel (F4)`",t.SAMPLES="`samples`",t.LOSS="`loss`",t.SIMILARITY="`similarity`"}(yn||(yn={})),function(t){t[t.SIMILARITY_MIN=0]="SIMILARITY_MIN",t[t.SIMILARITY_DEFAULT=.01]="SIMILARITY_DEFAULT",t[t.SAMPLES=10]="SAMPLES"}(bn||(bn={}));const An=`# Fitting\n\nUse fitting to solve an inverse problem: find input conditions leading to specified output constraints. \nIt computes inputs minimizing deviation measured by [loss function](https://en.wikipedia.org/wiki/Loss_function).\n\n1. In the ${yn.FIT} block, use switchers to specify inputs to be found:\n * Set ${yn.MIN} and ${yn.MAX} values for each selected item. They define the variation range\n * Set values of all other inputs\n\n2. Set output constraints in the ${yn.TARGET} block:\n * Use switchers to specify target outputs\n * Set target value for each selected item\n\n3. Choose ${yn.METHOD}. Press <i class="grok-icon fal fa-cog"></i> to specify its settings.\n\n4. Specify the loss function type (in the ${yn.LOSS} field).\n\n5. Enter the number of points to be found (in the ${yn.SAMPLES} field).\n\n6. Set the maximum scaled deviation between similar fitted points (in the ${yn.SIMILARITY} field).\n\n7. Press the "Run" icon <i class="fas fa-play"></i> on the top panel to perform fitting. You will get a\n[grid](https://datagrok.ai/help/visualize/viewers/grid) containing \n\n * loss function values\n * fitted inputs\n * viewers visualizing the goodness of fit:\n * [line chart](https://datagrok.ai/help/visualize/viewers/line-chart) showing the loss function minimization\n\n8. Open ${yn.CONTEXT}. You will get the function run corresponding to the selected grid row.\n\n9. Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization).\n\n# Learn more\n\n* [Parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization)\n* [Nelder-Mead method](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method)`;class Cn extends Error{constructor(t){super(t)}}function wn(t){return new Promise(((e,n)=>setTimeout(e,t)))}function In(t,e){const n=t.getRawData(),i=e.getRawData(),o=e.length,s=Math.min(t.length,o),r=new Uint32Array(s);let a=0,l=0,u=0;for(let t=0;t<s;++t){for(;;){if(l=Math.abs(i[a]-n[t]),++a,!(a<o)){--a;break}if(u=Math.abs(i[a]-n[t]),u>l){--a;break}l=u}r[t]=a}return r}function Tn(t,e,n,i){const o=e.col(t),s=n.col(t);if(null===o)throw new Cn(`no "${t}" column in the target dataframe "${e.name}"`);if(null===s)throw new Cn(`no "${t}" column in the output dataframe "${n.name}"`);const r=In(o,s),a=e.columns,l=a.length,u=new Float32Array((l-1)*r.length);let c=0;for(const e of a)if(e.name!==t){const t=n.col(e.name);if(null===t)throw new Cn(`no "${e.name}" column in the output dataframe "${n.name}"`);const o=t.getRawData(),s=e.getRawData();if(i){const t=e.stats.max-e.stats.min,n=t>0?t:1;r.forEach(((t,e)=>{u[c]=(o[t]-s[e])/n,++c}))}else r.forEach(((t,e)=>{u[c]=o[t]-s[e],++c}))}return u}var En=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const xn=new Map([["tolerance",{default:1e-6,min:1e-20,max:.1}],["maxIter",{default:50,min:1,max:1e4}],["nonZeroParam",{default:1e-4,min:1e-20,max:.1}],["initialScale",{default:.02,min:1e-20,max:.1}],["scaleReflaction",{default:1,min:1,max:2}],["scaleExpansion",{default:2,min:1,max:2}],["scaleContraction",{default:-.5,min:-.5,max:0}]]),Rn=new Map([["tolerance","tolerance"],["maxIter","max iterations"],["nonZeroParam","non-zero param"],["initialScale","initial scale"],["scaleReflaction","scale reflection"],["scaleExpansion","scale expansion"],["scaleContraction","scale contraction"]]);function Sn(t,e,n,i){for(let o=0;o<e;o++){let s=0;for(let t=0;t<e+1;t++)t!=n&&(s+=i[t][o]);t[o]=s/e}}function On(t,e,n,i,o,s,r,a){for(let l=0;l<s;l++)e[l]=t[l],e[l]+=o*(t[l]-i[n][l]),e[l]<r[l]?e[l]=r[l]:e[l]>a[l]&&(e[l]=a[l])}const Pn=function(t,e,n,i,o){return En(this,void 0,void 0,(function*(){const s=n.get("tolerance"),r=n.get("maxIter"),a=n.get("scaleReflaction"),l=n.get("scaleExpansion"),u=n.get("scaleContraction"),c=e.length+1,d=e.length,[p,h]=yield function(t,e,n,i,o){return En(this,void 0,void 0,(function*(){const s=n.length+1,r=n.length,a=e.get("nonZeroParam"),l=e.get("initialScale"),u=new Array(s),c=new Array(s);for(let e=0;e<s;e++){u[e]=new Float32Array(r);for(let t=0;t<r;t++)u[e][t]=n[t],0!=e&&e-1===t&&(0==n[t]?u[e][t]=a:u[e][t]+=l*n[e-1],u[e][t]<i[t]?u[e][t]=i[t]:u[e][t]>o[t]&&(u[e][t]=o[t]));c[e]=yield t(u[e])}return[u,c]}))}(t,n,e,i,o),f=new Array(c);for(let t=0;t<c;t++)f[t]=t;const m=f.length-1;let v=0,g=0,y=0,b=0;const A=new Float32Array(d),C=new Float32Array(d),w=new Float32Array(d),I=new Float32Array(d),T=new Array(r);if(c>1){for(;f.sort(((t,e)=>h[t]-h[e])),!(v>r);){if(0==v&&(g=h[0],y=2*h[f[0]]),T[v]=g,++v,g=h[f[0]],y-g>s)b=0;else if(++b,b>2*c)break;y=g,Sn(A,d,f[m],p),On(A,C,f[m],p,a,d,i,o);const e=yield t(C);if(e<h[f[m]]){On(A,w,f[m],p,l,d,i,o);const n=yield t(w);if(n<e){h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=w[t];continue}h[f[m]]=e;for(let t=0;t<d;t++)p[f[m]][t]=C[t];continue}On(A,I,f[m],p,u,d,i,o);const n=yield t(I);if(!(n<h[f[m]]))break;h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=I[t]}for(let t=v;t<r;t++)T[t]=h[f[0]]}return{point:p[f[0]],cost:h[f[0]],iterCosts:T,iterCount:v-1}}))};function Fn(t,e,n){const i=e-n,o=new Array(t);for(let e=0;e<t;e++){const t=Math.random();o[e]=n+t*i}return o}function _n(t,e,n,i){return s=this,r=arguments,l=function*(t,e,n,i,s=1){const r=function(t,e,n){const i=e.length,o=new Array(t);for(let e=0;e<t;e++)o[e]=new Float32Array(i);for(let s=0;s<i;s++)if(e[s]===n[s])for(let n=0;n<t;n++)o[n][s]=e[s];else{const i=Fn(t,e[s],n[s]);for(let e=0;e<t;e++)o[e][s]=i[e]}return o}(s,n,e),a=[],l=[],u=[];let c=0,d=null;const p=o.TaskBarProgressIndicator.create("Fitting...");let h;for(h=0;h<s;++h)try{if(a.push(yield Pn(t,r[h],i,e,n)),p.update(100*(h+1)/s,"Fitting..."),yield wn(10),p.canceled)break}catch(t){if(p.close(),t instanceof Cn)throw new Error(`Inconsistent dataframes: ${t.message}`);++c,l.push(t instanceof Error?t.message:"Platform issue"),u.push(r[h])}if(p.close(),c>0){const t=n.length,e=new Array(t);for(let n=0;n<t;++n)e[n]=new Float32Array(c);u.forEach(((t,n)=>t.forEach(((t,i)=>e[i][n]=t)))),d=o.DataFrame.fromColumns(e.map(((t,e)=>o.Column.fromFloat32Array(`arg${e}`,t)))),d.columns.add(o.Column.fromStrings("Issue",l))}return{extremums:a,fails:d}},new((a=void 0)||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())}));var s,r,a,l}var kn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Mn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.DATA_FRAME],Bn=()=>e.div([],"sa-switch-input");class Ln{static fromEmpty(e){return kn(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield oe.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(n,i,s={parentView:void 0,parentCall:void 0,configFunc:void 0}){if(this.func=n,this.options=s,this.generateInputFields=t=>{const n=(t,e)=>void 0===t.options[e]?t.defaultValue:Number(t.options[e]),i=(t,n,i=!0)=>{const o=e.switchInput(" ",t,n);return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch OFF fitting the input":"Switch ON fitting the input":o.value?"Mark the output as not a target":"Mark the output as a target")),o},s=t.inputs.reduce(((t,s)=>{var r;const l=n(s,"default");if(s.propertyType===o.TYPE.FLOAT){const o=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),u=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),d=null!==(r=s.caption)&&void 0!==r?r:s.name,p={type:s.propertyType,prop:s,const:{input:(()=>{const t=e.floatInput(d,l,(t=>{h.const.value=t,this.updateApplicabilityState()}));return t.root.insertBefore(u.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Value of '${d}'`),t.nullable=!1,t})(),value:l},min:{input:(()=>{const t=e.floatInput(`${d} (min)`,n(s,"min"),(t=>{h.min.value=t,this.updateApplicabilityState()}));return t.addValidator((t=>Number(t)>p.max.value?"Greater than max":null)),t.root.insertBefore(o.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Min value '${d}'`),t.nullable=!1,t})(),value:n(s,"min")},max:{input:(()=>{const t=e.floatInput(`${d} (max)`,n(s,"max"),(t=>{h.max.value=t,this.updateApplicabilityState()}));return t.addValidator((t=>Number(t)<p.min.value?"Smaller than min":null)),t.addPostfix(s.options.units),t.setTooltip(`Max value of '${d}'`),t.nullable=!1,t})(),value:n(s,"max")},isChanging:new c.BehaviorSubject(!1)};[p.max.input].forEach((t=>{t.root.insertBefore(Bn(),t.captionLabel),a()(t.root).removeProp("display")})),t[s.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input]});const h=t[s.name];h.isChanging.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,u.notify=!1,u.value=t,u.notify=!0})),(0,c.combineLatest)([p.isChanging]).subscribe((([t])=>{t?(h.constForm.forEach((t=>a()(t.root).hide())),h.saForm.forEach((t=>a()(t.root).css("display","flex")))):(h.constForm.forEach((t=>a()(t.root).css("display","flex"))),h.saForm.forEach((t=>a()(t.root).hide())))}))}else{const n=Bn(),i={input:(()=>{var t;const o=e.input.forProperty(s);return o.caption=null!==(t=s.caption)&&void 0!==t?t:s.name,o.onInput((()=>{i.value=o.value,this.updateApplicabilityState()})),o.root.insertBefore(n,o.captionLabel),o.addPostfix(s.options.units),o.nullable=!1,o})(),value:l};i.input.value=l,t[s.name]={const:i,constForm:[i.input],saForm:[],type:s.propertyType,prop:s,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),r=t.outputs.filter((t=>Mn.includes(t.propertyType))).reduce(((t,n)=>{const s={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name,a=e.input.forProperty(n);a.addCaption(r),a.value=0,a.setTooltip(this.toSetSwitched?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.input.hidden=!this.toSetSwitched,a.nullable=!1,e.tooltip.bind(a.captionLabel,n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.onChanged((()=>{if(s.target=a.value,n.propertyType===o.TYPE.DATA_FRAME)if(s.target){const t=[];for(const e of a.value.columns)e.type!==o.COLUMN_TYPE.FLOAT&&e.type!==o.COLUMN_TYPE.INT||t.push(e.name);s.colNameInput.items=t,s.colNameInput.value=t[0]}else s.colNameInput.items=[null],s.colNameInput.value=null;this.updateApplicabilityState()})),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!this.toSetSwitched);const l=i(this.toSetSwitched,(t=>{s.isInterest.next(t),this.updateApplicabilityState(),a.input.hidden=!t,a.setTooltip(t?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!t,s.colNameInput.root.hidden=!t)}),!1).root;return a.root.insertBefore(l,a.captionLabel),a})(),colNameInput:(()=>{const t=e.choiceInput("argument",null,[null],(t=>s.colName=t));return t.setTooltip("Column with argument values"),t.root.insertBefore(Bn(),t.captionLabel),t.root.hidden=n.propertyType!==o.TYPE.DATA_FRAME||!this.toSetSwitched,this.toSetSwitched=!1,t.nullable=!1,t})(),isInterest:new c.BehaviorSubject(this.toSetSwitched),target:n.propertyType!==o.TYPE.DATA_FRAME?0:null,colName:""};return t[n.name]=s,t}),{});return{inputs:s,outputs:r}},this.readyToRun=!1,this.runIcon=e.iconFA("play",(()=>kn(this,void 0,void 0,(function*(){this.readyToRun&&(yield this.runOptimization())})))),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute/#input-parameter-optimization","_blank")}),"Open help in a new tab"),this.showFailsBtn=e.button("Issues",(()=>{if(this.method!==pn.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);this.showNelderMeadFails()}),"Show issues"),this.gridClickSubscription=null,this.gridCellChangeSubscription=null,this.failsDF=null,this.toSetSwitched=!0,this.samplesCount=bn.SAMPLES,this.samplesCountInput=e.input.forProperty(o.Property.fromOptions({name:gn.SAMPLES,inputType:"Int",defaultValue:this.samplesCount,min:1,max:1e3})),this.loss=fn.RMSE,this.lossInput=e.choiceInput(gn.LOSS_LOW,this.loss,[fn.MAD,fn.RMSE],(()=>{this.loss=this.lossInput.value,this.lossInput.setTooltip(mn.get(this.loss))})),this.similarity=bn.SIMILARITY_DEFAULT,this.similarityInput=e.input.forProperty(o.Property.fromOptions({name:gn.SIMILARITY,inputType:"Float",defaultValue:this.similarity,min:0})),this.helpDN=void 0,this.method=pn.NELDER_MEAD,this.methodInput=e.choiceInput(gn.METHOD,this.method,[pn.NELDER_MEAD],(()=>{this.method=this.methodInput.value,this.showHideSettingInputs(),this.methodInput.setTooltip(hn.get(this.method))})),this.nelderMeadSettings=new Map,this.gradDescentSettings={iterCount:10,learningRate:1e-4},this.settingsInputs=new Map,this.store=this.generateInputFields(this.func),this.fittingSettingsIcon=e.iconFA("cog",(()=>{const t=this.fittingSettingsDiv.hidden;this.fittingSettingsDiv.hidden=!t}),"Modify fitting settings"),this.fittingSettingsDiv=e.divV([]),!this.isOptimizationApplicable(n))return t.shell.warning("Fitting is not applicable: the function has no scalar outputs."),void i.close();const r=this.buildForm();this.comparisonView=i,this.comparisonView.dockManager.dock(r,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Fitting`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1,xn.forEach(((t,e)=>this.nelderMeadSettings.set(e,t.default)));const l=this.comparisonView.getRibbonPanels();l.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(l),this.fittingSettingsDiv.hidden=!0,this.comparisonView.name=this.comparisonView.name.replace("comparison","fitting"),this.comparisonView.helpUrl="https://datagrok.ai/help/compute/#input-parameter-optimization";const u=e.markdown(An);u.style.padding="10px",u.style.overflow="auto",this.helpDN=this.comparisonView.dockManager.dock(u,o.DOCK_TYPE.FILL,this.comparisonView.dockManager.findNode(this.comparisonView.grid.root),"About"),this.methodInput.setTooltip(hn.get(this.method)),e.tooltip.bind(this.methodInput.captionLabel,"Method for minimizing the loss function"),this.lossInput.setTooltip(mn.get(this.loss)),e.tooltip.bind(this.lossInput.captionLabel,"Loss function type"),this.showFailsBtn.style.padding="0px",this.samplesCountInput.addCaption(gn.SAMPLES),this.samplesCountInput.onChanged((()=>{this.samplesCount=this.samplesCountInput.value,this.updateApplicabilityState()})),this.samplesCountInput.setTooltip("Number of points to be found"),this.similarityInput.onChanged((()=>{this.similarity=this.similarityInput.value,this.updateApplicabilityState()})),this.similarityInput.addCaption(gn.SIMILARITY),this.similarityInput.setTooltip("The higher the value, the fewer points will be found"),e.tooltip.bind(this.similarityInput.captionLabel,"Max scaled deviation between similar fitted points"),this.updateRunIconStyle(),this.updateRunIconDisabledTooltip("Select inputs for fitting"),this.runIcon.classList.add("fas")}isOptimizationApplicable(t){for(const n of t.outputs)if((e=n).propertyType===o.TYPE.INT||e.propertyType===o.TYPE.FLOAT||e.propertyType===o.TYPE.DATA_FRAME)return!0;var e;return!1}generateNelderMeadSettingsInputs(){const t=[];xn.forEach(((n,i)=>{const s=e.input.forProperty(o.Property.fromOptions({name:Rn.get(i),inputType:"maxIter"!==i?"Float":"Int",defaultValue:n.default,min:n.min,max:n.max}));s.addCaption(Rn.get(i)),s.nullable=!1,s.onChanged((()=>{this.nelderMeadSettings.set(i,s.value),this.updateApplicabilityState()})),t.push(s)})),this.settingsInputs.set(pn.NELDER_MEAD,t)}areNelderMeadSettingsCorrect(){for(const[t,e]of this.nelderMeadSettings)if(null==e||e>xn.get(t).max||e<xn.get(t).min)return this.updateRunIconDisabledTooltip(`Invalid "${t}": check method settings`),!1;return!0}generateGradDescentSettingsInputs(){const t=e.input.forProperty(o.Property.fromOptions({name:"iterations",inputType:"Int",defaultValue:this.gradDescentSettings.iterCount,min:1,max:1e4}));t.onChanged((()=>this.gradDescentSettings.iterCount=t.value));const n=e.input.forProperty(o.Property.fromOptions({name:"Learning rate",inputType:"Float",defaultValue:this.gradDescentSettings.learningRate,min:1e-6,max:1e3}));n.onChanged((()=>this.gradDescentSettings.learningRate=n.value)),this.settingsInputs.set(pn.GRAD_DESC,[t,n])}areGradDescentSettingsCorrect(){return!1}areMethodSettingsCorrect(){switch(this.method){case pn.NELDER_MEAD:return this.areNelderMeadSettingsCorrect();case pn.GRAD_DESC:return this.areGradDescentSettingsCorrect();default:return!0}}generateSettingInputs(){this.generateNelderMeadSettingsInputs(),this.generateGradDescentSettingsInputs()}showHideSettingInputs(){this.settingsInputs.forEach(((t,e)=>t.forEach((t=>t.root.hidden=e!==this.method))))}buildForm(){const t=e.h1(gn.FIT);e.tooltip.bind(t,"Select inputs to be fitted");const n=new Map([["Misc",[]]]);Object.values(this.store.inputs).forEach((t=>{const e=t.prop.category,i=[...t.constForm.map((t=>t.root)),...t.saForm.map((t=>t.root))];n.has(e)?n.get(e).push(...i):n.set(e,i)}));const i=e.div([t],{style:{"overflow-y":"scroll",width:"100%"}});n.size>1?(n.forEach(((t,n)=>{"Misc"!==n&&(i.append(e.h3(n)),i.append(...t))})),n.get("Misc").length>0&&(i.append(e.h3("Misc")),i.append(...n.get("Misc")))):i.append(...n.get("Misc"));const o=e.h1(gn.TARGET);e.tooltip.bind(o,"Select target outputs"),i.appendChild(o);let s="Misc";Object.values(this.store.outputs).reduce(((t,n)=>{const i=n.prop;return i.category!==s&&(t.append(e.h3(i.category)),s=i.category),t.append(n.input.root),t.append(n.colNameInput.root),t}),i);let r=!1;for(const t of Object.keys(this.store.outputs))if(!0===this.store.outputs[t].isInterest.value){r=!0;break}r||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0);const l=e.h1("Using");e.tooltip.bind(l,"Specify fitting method"),i.appendChild(l),this.methodInput.root.insertBefore(this.fittingSettingsIcon,this.methodInput.captionLabel),this.fittingSettingsIcon.style.minWidth="50px",i.appendChild(this.methodInput.root);const u=e.h2("with settings");return e.tooltip.bind(u,(()=>`Settings of the ${this.method} method`)),this.fittingSettingsDiv.appendChild(u),this.generateSettingInputs(),this.showHideSettingInputs(),i.appendChild(this.fittingSettingsDiv),this.settingsInputs.forEach((t=>t.forEach((t=>{t.root.insertBefore(Bn(),t.captionLabel),this.fittingSettingsDiv.append(t.root)})))),[this.lossInput,this.samplesCountInput,this.similarityInput].forEach((t=>{t.root.insertBefore(Bn(),t.captionLabel),t.nullable=!1,i.appendChild(t.root)})),a()(i).addClass("ui-form"),this.updateApplicabilityState(),a()(i).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),i}updateRunIconDisabledTooltip(t){e.tooltip.bind(this.runIcon,(()=>{const n=e.label(t);return n.style.color="#FF0000",n}))}updateApplicabilityState(){this.readyToRun=this.canFittingBeRun(),this.updateRunIconStyle()}updateRunIconStyle(){this.readyToRun?(this.runIcon.style.color="var(--green-2)",e.tooltip.bind(this.runIcon,"Run fitting")):this.runIcon.style.color="var(--grey-3)"}areInputsReady(){var t;let e,n=!1,i=!0;for(const o of Object.keys(this.store.inputs)){const s=this.store.inputs[o],r=null!==(t=s.prop.caption)&&void 0!==t?t:s.prop.name;if(!0===s.isChanging.value){n=!0;const t=s.min.input,o=s.max.input,a=t.value,l=o.value;e=null!=a&&void 0!==l&&void 0!==l,e?a>l?(e=!1,this.updateRunIconDisabledTooltip(`Invalid min & max of "${r}"`),t.input.classList.add("d4-invalid"),o.input.classList.add("d4-invalid")):(t.input.classList.remove("d4-invalid"),o.input.classList.remove("d4-invalid")):this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}else{e=null!=s.const.input.value,e||this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}}return n||this.updateRunIconDisabledTooltip("No parameters for fitting selected"),n&&i}areOutputsReady(){let t,e=!1,n=!0;for(const i of Object.keys(this.store.outputs)){const s=this.store.outputs[i];if(!0===s.isInterest.value){e=!0;t=null!=s.input.value,s.prop.propertyType===o.TYPE.DATA_FRAME&&(t=t&&null!==s.colNameInput.value&&""!==s.colName),t||this.updateRunIconDisabledTooltip(`Incomplete the "${s.input.caption}" target`),n=n&&t}}return e||this.updateRunIconDisabledTooltip("No targets selected"),e&&n}isSamplesCountValid(){return this.samplesCount>0||(this.updateRunIconDisabledTooltip(`Invalid "${gn.SAMPLES}"`),!1)}isSimilarityValid(){return this.similarity>=bn.SIMILARITY_MIN||(this.updateRunIconDisabledTooltip(`Invalid "${gn.SIMILARITY}"`),!1)}canFittingBeRun(){return this.areInputsReady()&&this.areOutputsReady()&&this.isSamplesCountValid()&&this.areMethodSettingsCorrect()&&this.isSimilarityValid()}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!this.store.inputs[t].isChanging.value))}getFittedInputs(){return Object.keys(this.store.inputs).filter((t=>this.store.inputs[t].type===o.TYPE.FLOAT&&this.store.inputs[t].isChanging.value))}runOptimization(){return kn(this,void 0,void 0,(function*(){try{if(!this.canFittingBeRun())return;if(this.samplesCount<1)return;if(this.similarity<bn.SIMILARITY_MIN)return;this.failsDF=null;const n={},i=this.getFixedInputs();i.forEach((t=>n[t]=this.store.inputs[t].const.value));const s=this.getFittedInputs(),r=s.length,l=[],u=new Float32Array(r),c=new Float32Array(r),d=new Array(r);s.forEach(((t,e)=>{var n;const i=this.store.inputs[t];u[e]=i.min.value,c[e]=i.max.value,l.push(t),d[e]=null!==(n=i.prop.caption)&&void 0!==n?n:i.prop.name}));const p=this.getOutputsOfInterest();if(p.length<1)return void t.shell.error("No output is selected for optimization.");const h=p.map((t=>t.prop.propertyType)).filter((t=>t===o.TYPE.DATA_FRAME)).length>1,f=t=>kn(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n);return yield e.call()})),m=t=>kn(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0,r=0,a=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?(a=t.target,s+=Math.pow((a-i.getParamValue(t.prop.name))/(0!==a?a:1),2),++r):Tn(t.colName,t.target,i.getParamValue(t.prop.name),!0).forEach((t=>{s+=Math.pow(t,2),++r}))})),Math.sqrt(s/r)})),v=t=>kn(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?s=Math.max(s,Math.abs(t.target-i.getParamValue(t.prop.name))):Tn(t.colName,t.target,i.getParamValue(t.prop.name),!1).forEach((t=>s=Math.max(s,Math.abs(t))))})),s}));let g,y,b;if(this.loss===fn.MAD?(g=v,y="maximum absolute devation"):(g=m,y="root mean square error"),this.method!==pn.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);b=yield _n(g,u,c,this.nelderMeadSettings,this.samplesCount);const A=b.extremums,C=A.length;if(C<this.samplesCount){this.failsDF=b.fails;const t=this.failsDF.columns;d.forEach(((e,n)=>t.byIndex(n).name=t.getUnusedName(e))),i.forEach((e=>{var n,i;const s=this.store.inputs[e];s.prop.propertyType!==o.TYPE.DATA_FRAME&&t.add(o.Column.fromList(s.prop.propertyType,t.getUnusedName(null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name),new Array(null===(i=this.failsDF)||void 0===i?void 0:i.rowCount).fill(s.const.value)))}))}const w=[],I=this.similarity;A.forEach((t=>{let e=!0;w.forEach((n=>e&&(e=function(t,e,n,i){const o=t.length;if(o!==e.length||o!==n.length||o!==i.length)throw new Error("Inconsistent found points");return t.reduce(((t,o,s)=>{const r=i[s]-n[s];return r>0?Math.max(t,Math.abs(o-e[s])/r):t}),0)}(n.point,t.point,u,c)>I))),e&&w.push(t)}));const T=w.length;if(C<this.samplesCount){if(C<1)return void t.shell.warning(e.divV([e.label(`Failed to find ${this.samplesCount} point${this.samplesCount>1?"s":""}`),e.div([this.showFailsBtn])]));t.shell.info(e.divV([e.label(`Found ${T} point${T>1?"s":""}`),e.div([this.showFailsBtn])]))}else t.shell.info(`Found ${T} point${T>1?"s":""}`);this.clearPrev(),w.sort(((t,e)=>t.cost-e.cost));const E=new Float32Array(T),x=this.comparisonView.grid,R=new Array(T),S=new Array(T),O=new Array(T),P=new Map([[gn.LOSS,`The final loss obtained: ${y}`]]);let F=!0;const _=[];w.forEach(((t,e)=>kn(this,void 0,void 0,(function*(){E[e]=t.cost;const n=this.getLossGraph(t);O[e]=n;const i=new Map,s=yield f(t.point);S[e]=s,p.forEach((t=>{this.getOutputGof(t.prop,t.target,s,t.colName,h).forEach((t=>i.set(t.caption,t.root)))})),R[e]=i,F&&(i.forEach(((t,e)=>{var n;P.set(e,"Goodness of fit"),null===(n=this.comparisonView.table)||void 0===n||n.columns.addNew(e,o.COLUMN_TYPE.STRING);const i=this.comparisonView.grid.columns.byName(e);i.cellType="html",i.width=vn.GOF_VIEWER_WIDTH,_.push(e)})),F=!1)}))));const k=o.DataFrame.fromColumns([o.Column.fromFloat32Array(gn.LOSS,E)]);this.comparisonView.dataFrame=k;const M=k.columns;d.forEach(((t,e,n)=>{t=M.getUnusedName(t),n[e]=t;const i=new Float32Array(T);for(let t=0;t<T;++t)i[t]=w[t].point[e];M.add(o.Column.fromFloat32Array(t,i)),P.set(t,`Obtained values of '${t}'`)})),x.props.rowHeight=vn.ROW_HEIGHT,x.props.showAddNewRowIcon=!1,x.props.allowEdit=!1;const B=M.getUnusedName(`${this.loss} by iterations`);P.set(B,`Minimizing ${y}`),M.addNew(B,o.COLUMN_TYPE.STRING);const L=x.columns.byName(B);L.cellType="html",L.width=vn.LOSS_GRAPH_WIDTH;let D=!0;x.onCellPrepare((t=>kn(this,void 0,void 0,(function*(){D&&(x.columns.setOrder(M.names().filter((t=>t!==B)).concat([B])),D=!1),t.isColHeader||t.isRowHeader||(t.isTableCell&&t.gridColumn.name===B&&null!==t.cell.value&&(t.style.element=O[t.gridRow]),_.forEach((n=>{var i;t.isTableCell&&t.gridColumn.name===n&&null!==t.cell.value&&void 0!==R[t.gridRow]&&(t.style.element=null!==(i=R[t.gridRow].get(n))&&void 0!==i?i:e.label(""))})))})))),x.columns.byName(gn.LOSS).format="scientific",x.columns.byName(gn.LOSS).width=vn.LOSS_COL_WIDTH,x.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,s=P.get(o);return e.tooltip.show(null!=s?s:"",n,i),!0}})),k.currentCell=k.cell(0,gn.LOSS);const N=n=>kn(this,void 0,void 0,(function*(){var i;if(null==n)return;const s=null!==(i=n.tableRowIndex)&&void 0!==i?i:0,r=S[s],l=[...r.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),u=o.HtmlTable.create(l,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,r.outputs[t.property.name],t.property.options.units]})).root,c=[...r.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,s=r.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,s);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d;d=l.length>0?Object.assign({"Output scalars":[u]},c):Object.assign({},c);const p=e.accordion();if(a()(p.root).css({width:"100%"}),Object.entries(d).map((t=>{p.addPane(t[0],(()=>e.divV(t[1])))})),p.panes.length-1<0)throw new Error("Function has no outputs");p.panes[p.panes.length-1].expanded=!0,t.shell.o=p.root}));this.gridClickSubscription=x.onCellClick.subscribe(N),this.gridCellChangeSubscription=x.onCurrentCellChanged.subscribe(N)}catch(e){t.shell.error(e instanceof Error?e.message:"The platform issue")}}))}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];n.isInterest.value&&t.push(n)}return t}getLossGraph(t){return o.Viewer.lineChart(o.DataFrame.fromColumns([o.Column.fromList(o.COLUMN_TYPE.INT,gn.ITER,[...Array(t.iterCount).keys()].map((t=>t+1))),o.Column.fromList(o.COLUMN_TYPE.FLOAT,gn.LOSS,t.iterCosts.slice(0,t.iterCount))]),{showYAxis:!0,showXAxis:!0,showXSelector:!0,showYSelector:!0,lineColoringType:"custom",lineColor:15274e3,markerColor:15274e3}).root}getOutputGof(t,e,n,i,s){var r;const a=t.propertyType,l=t.name,u=null!==(r=t.caption)&&void 0!==r?r:l;switch(a){case o.TYPE.FLOAT:case o.TYPE.INT:case o.TYPE.BIG_INT:return[{caption:u,root:o.Viewer.barChart(o.DataFrame.fromColumns([o.Column.fromStrings(u,["obtained","target"]),o.Column.fromList(a,gn.VALUE,[n.getParamValue(l),e])]),{valueColumnName:gn.VALUE,splitColumnName:u,valueAggrType:o.AGG.AVG,showValueSelector:!1,showCategorySelector:!1,showStackSelector:!1,showEmptyBars:!0}).root}];case o.TYPE.DATA_FRAME:const r=[],c=n.getParamValue(l),d=e,p=c.col(i),h=d.col(i),f=Dt(t).config;if(null===p||null===h)throw new Error("Creating viewer fails: incorrect argument column name");const m=p.getRawData(),v=In(h,p),g=v.length,y=Array(g);v.forEach(((t,e)=>y[e]=m[t]));let b,A,C=null;return f.filter((t=>t.type===o.VIEWER.LINE_CHART)).forEach((t=>{const e=t.segmentColumnName;if(e){const t=Array(g);v.forEach(((n,i)=>t[i]=c.col(e).get(n))),C=o.Column.fromStrings(e,t)}})),d.columns.names().forEach((t=>{if(t!==i){if(A=c.col(t),null===A)throw new Error(`Creating viewer fails: no '${t}' column in the output dataframe`);b=A.getRawData();const e=Array(g);if(v.forEach(((t,n)=>e[n]=b[t])),A=d.col(t),null===A)throw new Error(`Creating viewer fails: no '${t}' column in the target dataframe`);b=A.getRawData();const n=Array(g);v.forEach(((t,e)=>n[e]=b[e]));const i={multiAxis:!0,yGlobalScale:!0},a=o.DataFrame.fromColumns([h,o.Column.fromList(A.type,gn.OBTAINED,e),o.Column.fromList(A.type,gn.TARGET,n)]);C&&(a.columns.add(C),i.segmentColumnName=C.name),r.push({caption:s?`${u}: [${t}]`:`[${t}]`,root:o.Viewer.lineChart(a,i).root})}})),r;default:throw new Error("Unsupported output type")}}clearPrev(){void 0!==this.helpDN&&(this.comparisonView.dockManager.close(this.helpDN),this.helpDN=void 0),this.gridClickSubscription&&(this.gridClickSubscription.unsubscribe(),this.gridClickSubscription=null),this.gridCellChangeSubscription&&(this.gridCellChangeSubscription.unsubscribe(),this.gridCellChangeSubscription=null)}showNelderMeadFails(){if(null===this.failsDF)return;const n=t.shell.addTableView(this.failsDF);n.addViewer(o.Viewer.form(o.DataFrame.fromColumns(Object.entries(this.nelderMeadSettings).map((t=>{var e;return o.Column.fromFloat32Array(null!==(e=Rn.get(t[0]))&&void 0!==e?e:t[0],new Float32Array([t[1]]))})))),{description:"The Nelder-Mead method settings",showNavigation:!1});const i=this.getFittedInputs().length,s=new Map;this.failsDF.columns.names().forEach(((t,e)=>{e<i?s.set(t,`Initial value of "${t}" used in the Nelder-Mead method`):e>i?s.set(t,`Value of "${t}" (fixed input)`):s.set(t,"Error message raised")})),n.grid.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,r=s.get(o);return e.tooltip.show(null!=r?r:"",n,i),!0}}))}}var Dn,Nn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};!function(t){t.INPUTS="inputs",t.OUTPUTS="outputs"}(Dn||(Dn={}));const Vn={[Dn.INPUTS]:"inputParams",[Dn.OUTPUTS]:"outputParams"},jn=()=>e.divText("[No data to display]",{style:{"text-align":"center","align-content":"center",width:"100%",height:"100%"}});class $n extends be{static fromFuncCall(t,e={historyEnabled:!0,isTabbed:!1}){return new this(t,e)}constructor(t,n={historyEnabled:!0,isTabbed:!1}){super(t,n),this.options=n,this.validationRequests=new c.Subject,this.validationUpdates=new c.Subject,this.runRequests=new c.Subject,this.isRunning=new c.BehaviorSubject(!1),this.isUploadMode=new c.BehaviorSubject(!1),this.inputsOverride={},this.inputsMap={},this.validators={},this.validationState={},this.externalValidatorsUpdates=new c.Subject,this.externalValidatorsState={},this.pendingValidations=this.validationUpdates.pipe((0,s.startWith)(null),(0,s.map)((()=>this.validationState))),this._isOutputOutdated=new c.BehaviorSubject(!0),this.isOutputOutdated=this._isOutputOutdated.pipe((0,s.distinctUntilChanged)()),this.blockRuns=new c.BehaviorSubject(!1),this.prevOpenedTab=null,this.beforeInputPropertyRender=new c.Subject,this.afterInputPropertyRender=new c.Subject,this.afterOutputPropertyRender=new c.Subject,this.afterOutputSacalarTableRender=new c.Subject,this.formButtons=e.div(),this.additionalBtns=[],this.navBtns=[],this.tabsElem=e.tabControl(),this.dfToViewerMapping={},this.focusedInput=null,this.foldedCategoryInputs={},this.sheetNamesCache={},this.richFunctionExport=t=>Nn(this,void 0,void 0,(function*(){if("Excel"===t)try{const e=this.lastCall;if(!e)throw new Error("Function was not called");if(!this.exportConfig.supportedFormats.includes(t))throw new Error(`Format "${t}" is not supported.`);if(!this.func)throw new Error("The correspoding function is not specified");yield o.Utils.loadJsCss(["/js/common/exceljs.min.js"]);const n=window.ExcelJS,i="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",s=new n.Workbook,r=t=>o.TYPES_SCALAR.has(t),a=t=>t.propertyType===o.TYPE.DATA_FRAME,l=this.func.inputs.filter((t=>a(t))),u=this.func.inputs.filter((t=>r(t.propertyType))),c=this.func.outputs.filter((t=>a(t))),d=this.func.outputs.filter((t=>r(t.propertyType)));if(l.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.inputs[t.name];st(o,r)})),u.length){const t=s.addWorksheet("Input scalars");it(t,u.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.inputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}if(c.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.outputs[t.name];st(o,r)})),d.length){const t=s.addWorksheet("Output scalars");it(t,d.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.outputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}const p=this.tabsElem;for(const t of this.inputTabsLabels)for(const n of this.categoryToDfParamMap.inputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.inputs[n.name];for(const[t,e]of i.entries())yield rt(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}for(const t of this.outputTabsLabels)for(const n of this.categoryToDfParamMap.outputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.outputs[n.name];for(const[t,e]of i.entries())if(e.type===o.VIEWER.STATISTICS){const e=a.columns.length,n=o.DataFrame.fromColumns([o.Column.string("Name",e).init((t=>a.columns.byIndex(t).name)),o.Column.int("Values",e).init((t=>a.columns.byIndex(t).stats.valueCount)),o.Column.int("Nulls",e).init((t=>a.columns.byIndex(t).stats.missingValueCount)),o.Column.float("Min",e).init((t=>a.columns.byIndex(t).stats.min)),o.Column.float("Max",e).init((t=>a.columns.byIndex(t).stats.max)),o.Column.float("Avg",e).init((t=>a.columns.byIndex(t).stats.avg)),o.Column.float("Stdev",e).init((t=>a.columns.byIndex(t).stats.stdev))]);st(s.getWorksheet(this.getSheetName(r,s)),n,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}else yield rt(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}const h=yield s.xlsx.writeBuffer();return new Blob([h],{type:i})}catch(t){console.log(t)}if("DataUrl images"===t){const t={},e=t=>t.propertyType===o.TYPE.DATA_FRAME,n=this.tabsElem;yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const i=window.html2canvas;for(const s of this.tabsLabels.filter((t=>this.inputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.inputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}for(const s of this.tabsLabels.filter((t=>this.outputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.outputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}return new Blob([JSON.stringify(t)],{type:"text/plain"})}throw new Error("Format is not supported")})),this.exportConfig={supportedExtensions:this.richFunctionViewExportExtensions(),supportedFormats:this.richFunctionViewSupportedFormats(),export:this.richFunctionExport,filename:this.defaultExportFilename}}onFuncCallReady(){const n=Object.create(null,{onFuncCallReady:{get:()=>super.onFuncCallReady}});return Nn(this,void 0,void 0,(function*(){yield this.loadInputsOverrides(),yield this.loadInputsValidators(),yield n.onFuncCallReady.call(this);const i=this.funcCallReplaced.subscribe((()=>this.validationRequests.next({isRevalidation:!1})));this.subs.push(i);const o=this.validationRequests.pipe((0,s.groupBy)((t=>t.field)),(0,s.mergeMap)((t=>t.pipe((0,s.tap)((t=>this.setValidationPending(t.field))),(0,s.switchMap)((t=>{const e=new AbortController,n=e.signal;let i=!1;return new c.Observable((o=>{const s=(0,c.from)(this.runValidation(Object.assign({},t),n)).subscribe((t=>{i=!0,o.next(t)}));return()=>{i||e.abort(),s.unsubscribe()}})).pipe((0,s.tap)((e=>{this.setValidationResults(e),this.runRevalidations(t,e),this.validationUpdates.next(null)})),(0,s.mapTo)(t))})))))).subscribe((t=>{t.field&&this.runningOnInput&&this.isRunnable()&&this.doRun()}));this.subs.push(o);const r=this.externalValidatorsUpdates.subscribe((t=>{this.updateInputValidationReuslts(t)}));this.subs.push(r);const a=(0,c.combineLatest)([this.runRequests.pipe((0,s.switchMap)((()=>(0,c.of)(!1).pipe((0,s.delay)(500),(0,s.startWith)(!0))))),this.validationUpdates.pipe((0,s.debounceTime)(0))]).pipe((0,s.filter)((([t])=>t&&this.isRunnable()))).subscribe((()=>this.doRun()));this.subs.push(a);const l=this.options.isTabbed?null:yield this.loadLastInputs();if(l)t.shell.info(e.div([e.divText("Do you want to load last inputs?"),e.divH([e.bigButton("Load",(()=>{for(const[t,e]of Object.entries(l)){const n=this.getInput(t);n.notify=!1,n.value=e,n.notify=!0}t.shell.info(e.divText("Change the loaded inputs to run computations"))}))])]));else{const t=new AbortController,e=yield this.runValidation({isRevalidation:!1},t.signal);this.setValidationResults(e),this.runRevalidations({isRevalidation:!1},e),this.validationUpdates.next(null),this.runningOnStart&&this.isRunnable()&&(yield this.doRun())}}))}onBeforeRun(){return this.tabsElem.currentPane&&(this.prevOpenedTab=this.inputTabsLabels.includes(this.tabsElem.currentPane.name)?null:this.tabsElem.currentPane),Promise.resolve()}onAfterRun(){if(this.showOutput(),this.tabsElem.panes.forEach((t=>{a()(t.header).show()})),this.prevOpenedTab)return this.tabsElem.currentPane=this.prevOpenedTab,Promise.resolve();const t=this.tabsElem.panes.find((t=>this.outputTabsLabels.includes(t.name)));return t&&(this.tabsElem.currentPane=t),Promise.resolve()}getRunButton(t="Run"){var n;const i=e.bigButton(null!==(n=this.func.options.runLabel)&&void 0!==n?n:t,(()=>Nn(this,void 0,void 0,(function*(){return yield this.doRun()})))),o=(0,c.merge)(this.validationUpdates,this.externalValidatorsUpdates,this.isRunning,this.blockRuns).subscribe((()=>{const t=this.isRunnable();i.disabled=!t}));return this.subs.push(o),i}loadInputsOverrides(){return Nn(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>Nn(this,void 0,void 0,(function*(){if(e.property.options.input){const n=(yield t.functions.eval(e.property.options.input)).prepare({params:JSON.parse(e.property.options.inputOptions||"{}")});yield n.call(),this.inputsOverride[e.name]=n.outputs.input}})))))}))}loadInputsValidators(){return Nn(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>Nn(this,void 0,void 0,(function*(){if(e.property.options.validatorFunc){const n=(yield t.functions.eval(e.property.options.validatorFunc)).prepare({params:JSON.parse(e.property.options.validatorFuncOptions||"{}")});yield n.call(),this.validators[e.name]=n.outputs.validator}})))))}))}keepOutput(){var t;return"true"===(null===(t=this.func)||void 0===t?void 0:t.options.keepOutput)}getSaveButton(t="Save"){const n=e.bigButton(t,(()=>Nn(this,void 0,void 0,(function*(){return yield this.saveExperimentalRun(this.funcCall)}))),"Save uploaded data"),i=this.isUploadMode.subscribe((t=>{this.buildRibbonPanels(),t?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}getStandardButtons(){const t=this.getRunButton(),n=e.div([t]);e.tooltip.bind(n,(()=>t.disabled?this.isRunning.value?"Computations are in progress":this.getValidationMessage():""));const i=this.getSaveButton();return[...this.isHistoryEnabled&&!this.options.isTabbed?[i]:[],...this.runningOnInput?[]:[n]]}buildFormButtons(){var t;const n=this.getStandardButtons(),i=e.buttonsInput();return a()(i.firstChild).css({display:"none"}),null===(t=i.lastChild)||void 0===t||t.replaceWith(e.div([...this.navBtns,...this.additionalBtns,...n],"ui-input-editor")),a()(i).addClass("rfv-buttons"),a()(i).css({"max-width":"100%"}),this.formButtons.replaceWith(i),this.formButtons=i,i}setAdditionalButtons(t){this.additionalBtns=t,this.buildFormButtons()}setNavigationButtons(t){this.navBtns=t}buildIO(){const{inputBlock:t,inputForm:n,outputForm:i,controlsWrapper:o}=this.buildInputBlock(),s=[...Array.from(n.childNodes),...this.isUploadMode.value?[Array.from(i.childNodes)]:[]];e.tools.handleResize(t,(()=>{a()(t).width()<300?(a()(n).addClass("ui-form-condensed"),a()(i).addClass("ui-form-condensed"),a()(o).addClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100px")))):(a()(n).removeClass("ui-form-condensed"),a()(i).removeClass("ui-form-condensed"),a()(o).removeClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100%"))))}));const r=this.buildOutputBlock();r.style.height="100%",r.style.width="100%",this.hideOutput();const l=e.splitH([t,e.panel([r],{style:{"padding-top":"0px"}})],null,!0);return l.style.padding="0 12px",t.style.maxWidth="360px",l}buildInputBlock(){const t=this.renderInputForm(),n=this.renderOutputForm();this.buildFormButtons();const i=e.div(this.formButtons,"ui-form ui-form-wide");a()(i).css({"padding-left":"0px","padding-bottom":"0px","padding-right":"6px","max-width":"100%","min-height":"50px"});const o=e.switchInput("",this.isUploadMode.value,(t=>this.isUploadMode.next(t))),s=this.isUploadMode.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,t?a()(n).show():a()(n).hide()}));return this.subs.push(s),{inputBlock:e.divV([t,...this.hasUploadMode&&!this.uploadFunc?[e.divH([e.h2("Experimental data"),o.root],{style:{"flex-grow":"0"}}),n]:[],i],"ui-box rfv-form"),inputForm:t,outputForm:n,controlsWrapper:i}}processCustomDataUpload(){return Nn(this,void 0,void 0,(function*(){const n=()=>{const t=o.Dialog.create({title:"Select to compare"}),n=new Wt(p.length>0?p:[...this.historyBlock.history.values()],{fallbackText:"No historical runs found",showActions:!(p.length>0),showBatchActions:!(p.length>0)}),i=new Wt(d,{fallbackText:"No runs uploaded",showActions:!1,showBatchActions:!1});t.add(e.divV([e.divV([e.label("Uploaded runs"),e.element("div","splitbar-horizontal"),i.root],{style:{height:"50%","overflow-y":"hidden"}}),e.divV([e.label(p.length>0?"Simulated":"History",{style:{padding:"0px 10px 0px 9px"}}),e.element("div","splitbar-horizontal"),n.root],{style:{height:"50%","overflow-y":"hidden"}})],{style:{"justify-content":"space-between",gap:"10px","overflow-y":"scroll",height:"100%"}})),a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const s="Compare selected";return 0===p.length?t.addButton(s,(()=>Nn(this,void 0,void 0,(function*(){const e=yield Promise.all([...n.selected].map((t=>dt.loadRun(t.id))));this.onComparisonLaunch([...e,...i.selected.values()]),t.close()})))):t.addButton(s,(()=>Nn(this,void 0,void 0,(function*(){this.onComparisonLaunch([...n.selected.values(),...i.selected.values()]),t.close()})))),t.getButton(s).disabled=!0,this.subs.push((0,c.merge)(n.onSelectedChanged,i.onSelectedChanged).subscribe((()=>{n.selected.size+i.selected.size>1?t.getButton(s).disabled=!1:t.getButton(s).disabled=!0}))),this.isHistorical.value&&t.addButton(g,(()=>Nn(this,void 0,void 0,(function*(){this.onComparisonLaunch([this.funcCall,...i.selected.values()]),t.close()})))),a()(t.getButton("CANCEL")).hide(),t},i=yield t.functions.eval(this.uploadFunc),r=yield i.prepare({params:{func:this.func}}).call(),l=r.outputs.uploadWidget,u=r.outputs.uploadFuncCall;let d=[],p=[];const h=o.Dialog.create({title:"Upload"});a()(h.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const m=o.Dialog.create({title:"Review uploaded runs"});a()(m.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const v="Save to history",g="Compare w/ current";h.add(l.root),h.addButton(v,(()=>Nn(this,void 0,void 0,(function*(){return Lt(h.root,!0),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(C):t.options.immutable_tags=[C]})),Promise.all(d.map((t=>Nn(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);return dt.saveRun(e)}))))).then((t=>Promise.all(t.map((t=>dt.loadRun(t.id)))))).then((t=>{t.forEach((t=>this.historyBlock.addRun(t)))})).catch((e=>{t.shell.error(e)})).finally((()=>{Lt(h.root,!1),h.close();const t=new Wt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});m.add(t),m.show({modal:!0,fullScreen:!0})}))})))),h.addButton("Next",(()=>{h.close(),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(C):t.options.immutable_tags=[C]}));const t=new Wt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});m.add(t.root),m.show({modal:!0,fullScreen:!0})})),a()(h.getButton("CANCEL")).hide(),h.getButton(v).disabled=!0,h.getButton("Next").disabled=!0,a()(m.getButton("CANCEL")).hide(),m.addButton("Simulate w/ same inputs",(()=>{Lt(h.root,!0),Promise.all(d.map((t=>this.func.prepare((t=>{const e=t.clone(),n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e})(t).inputs).call()))).then((t=>{p=t,m.close(),n().show({modal:!0,fullScreen:!0})})).catch((e=>{t.shell.error(e)})).finally((()=>{Lt(h.root,!1)}))})),m.addButton("Compare w/ history",(()=>{m.close(),n().show({modal:!0,fullScreen:!0})}));const y=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===u.id))).subscribe((()=>{d=u.outputs.uploadedCalls,h.getButton(v).disabled=!1,h.getButton("Next").disabled=!1})),b=h.onClose.subscribe((()=>{this.isUploadMode.next(!1)}));h.subs.push(b,y),h.show({modal:!0,center:!0,resizable:!0})}))}onSaveClick(){return Nn(this,void 0,void 0,(function*(){this.isUploadMode.value?yield this.saveExperimentalRun(this.funcCall):yield this.saveRun(this.funcCall)}))}buildRibbonPanels(){super.buildRibbonPanels();const n=e.iconFA("play",(()=>Nn(this,void 0,void 0,(function*(){return yield this.doRun()}))),"Run computations");n.classList.add("fas");const i=e.iconFA("arrow-to-top",(()=>Nn(this,void 0,void 0,(function*(){this.uploadFunc?yield this.processCustomDataUpload():(this.isUploadMode.next(!this.isUploadMode.value),i.classList.toggle("d4-current"))}))),"Upload experimental data");i.classList.add("d4-toggle-button",...this.isUploadMode.value?["d4-current"]:[]);const o=e.iconFA("analytics",(()=>Nn(this,void 0,void 0,(function*(){return yield this.onSALaunch()}))),"Run sensitivity analysis"),s=e.iconFA("chart-line",(()=>Nn(this,void 0,void 0,(function*(){return yield this.onFittingLaunch()}))),"Fit inputs"),r=e.iconFA("info",(()=>Nn(this,void 0,void 0,(function*(){this.hasContextHelp&&(t.shell.windows.help.visible=!0,yield new Promise((t=>setTimeout(t,100))),t.shell.windows.help.showHelp(e.markdown(yield this.getContextHelp())))})))),a=[[...super.buildRibbonPanels().flat(),...this.runningOnInput||this.options.isTabbed?[]:[n],...this.hasUploadMode?[i]:[],...this.isSaEnabled?[o]:[],...this.isFittingEnabled?[s]:[],...this.hasContextHelp?[r]:[]]];return this.setRibbonPanels(a),a}showOutput(){e.setDisplay(this.tabsElem.root,!0),this._isOutputOutdated.next(!1)}buildOutputBlock(){this.tabsElem.root.style.width="100%",this.tabsLabels.forEach((n=>{const[i,r]=this.categoryToDfParamMap.outputs[n]?[this.categoryToDfParamMap.outputs[n],!1]:[this.categoryToDfParamMap.inputs[n],!0],l=i.filter((t=>t.propertyType===o.TYPE.DATA_FRAME||t.propertyType===o.TYPE.GRAPHICS)),u=i.filter((t=>t.propertyType!==o.TYPE.DATA_FRAME&&t.propertyType!==o.TYPE.GRAPHICS)),d=l.map((t=>nt(t).config));let p="";const h=l.reduce(((n,i,l)=>{var u,c;this.dfToViewerMapping[i.name]=[];const h=d[l].map(((n,s)=>Nn(this,void 0,void 0,(function*(){var s,r,a,l;const u=null!==(l=null!==(r=null===(s=this.funcCall.outputs[i.name])||void 0===s?void 0:s.value)&&void 0!==r?r:null===(a=this.funcCall.inputParams[i.name])||void 0===a?void 0:a.value)&&void 0!==l?l:t.data.demo.demog(0),c=n.type,d=Object.values(m).includes(c)?o.Viewer.fromType(c,u):yield u.plot.fromType(c);d.setOptions(n),this.dfToViewerMapping[i.name].push(d),this.afterOutputPropertyRender.next({prop:i,output:d});const p=jn();return 0===u.rowCount&&"demog 0"===u.name&&(e.setDisplay(d.root,!1),e.setDisplay(p,!0)),{viewer:d,stub:p}})))).map(((t,n)=>t.then((({viewer:t,stub:o})=>{const r=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe((()=>Nn(this,void 0,void 0,(function*(){var s;const r=null!==(s=this.funcCall.outputParams[i.name])&&void 0!==s?s:this.funcCall.inputParams[i.name];if(r.value){if(e.setDisplay(t.root,!0),e.setDisplay(o,!1),Object.values(m).includes(t.type))t.dataFrame=r.value;else{const e=yield r.value.plot.fromType(t.type);t.root.replaceWith(e.root),t=e}Object.keys(d[l][n]).includes("color")&&t.setOptions({color:d[l][n].color}),this.afterOutputPropertyRender.next({prop:i,output:t})}else e.setDisplay(t.root,!1),e.setDisplay(o,!0)}))));return this.subs.push(r),{loadedViewer:t,stub:o}})))),f=p!==(null!==(u=i.options.caption)&&void 0!==u?u:i.name)?null!==(c=i.options.caption)&&void 0!==c?c:i.name:" ";if(p=f,r){const t=this.funcCallReplaced.pipe((0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged}))).subscribe((()=>{this.showOutput(),this.inputTabsLabels.forEach((t=>{a()(this.tabsElem.getPane(t).header).show()}))}));this.subs.push(t)}const v=h.map(((t,n)=>{const i=d[l][n].block,o=e.wait((()=>Nn(this,void 0,void 0,(function*(){const n=yield t;return a()(n.loadedViewer.root).css({height:"100%",width:"100%"}),e.divV([n.loadedViewer.root,n.stub],{style:{width:"100%"}})}))));return a()(o).css({"min-height":"300px","flex-grow":"1"}),e.divV([e.h2(0===n?f:" ",{style:{"white-space":"pre"}}),o],{style:Object.assign({},i?{width:`${i}%`,"max-width":`${i}%`,"max-height":"100%"}:{"flex-grow":"1"})})}));if(i.propertyType===o.TYPE.GRAPHICS){const t=i.options.block,o=jn();o.classList.add("grok-scripting-image-container");const r=e.divV([e.h2(f,{style:{"white-space":"pre"}}),o],{style:Object.assign({},t?{width:`${t}%`,"max-width":`${t}%`,"max-height":"100%"}:{"flex-grow":"1"})}),a=()=>{var t;const e=null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name];e.value?(o.style.backgroundImage=`url("data:image/png;base64,${e.value}")`,o.textContent=""):(o.style.removeProperty("background-image"),o.textContent="[No data to display]")},l=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe(a);this.subs.push(l),n.append(r)}return n.append(...v),n}),e.divH([],{style:{"flex-wrap":"wrap","flex-grow":"1","max-height":"100%"}})),f=()=>{const t=o.HtmlTable.create(u,(t=>{var e;const n=t.options.precision,i=n&&t.propertyType===o.TYPE.FLOAT&&this.funcCall.outputs[t.name]?this.funcCall.outputs[t.name].toPrecision(n):this.funcCall.outputs[t.name],s=t.options.units?` [${t.options.units}]`:"";return[`${null!==(e=t.caption)&&void 0!==e?e:t.name}${s}`,null!=i?i:"[No value]"]})).root;return a()(t).addClass("rfv-scalar-table"),this.afterOutputSacalarTableRender.next(t),t};let v=f();const g=(0,c.merge)(this.funcCallReplaced,this.isRunning.pipe((0,s.filter)((t=>!1===t)),(0,s.skip)(1))).subscribe((()=>{const t=f();v.replaceWith(t),v=t,a()(this.tabsElem.getPane(n).header).show()}));this.subs.push(g),this.tabsElem.addPane(n,(()=>e.divV([...l.length?[h]:[],...u.length?[v]:[]])))}));const n=e.box();return n.append(this.tabsElem.root),n}onAfterLoadRun(t){return Nn(this,void 0,void 0,(function*(){this.showOutput()}))}get tabsLabels(){return[...this.inputTabsLabels,...this.outputTabsLabels]}get outputTabsLabels(){return Object.keys(this.categoryToDfParamMap.outputs)}get inputTabsLabels(){return Object.keys(this.categoryToDfParamMap.inputs)}get categoryToDfParamMap(){const t={inputs:{},outputs:{}};return this.func.inputs.filter((t=>t.propertyType===o.TYPE.DATA_FRAME&&0!==nt(t).config.length)).forEach((e=>{const n="Misc"===e.category?"Input":e.category;t.inputs[n]?t.inputs[n].push(e):t.inputs[n]=[e]})),this.func.outputs.forEach((e=>{const n="Misc"===e.category?"Output":e.category;e.propertyType===o.TYPE.DATA_FRAME&&0===nt(e).config.length||(t.outputs[n]?t.outputs[n].push(e):t.outputs[n]=[e])})),t}get inputsStorage(){return`RFV_LastInputs_${this.funcCall.func.name}`}saveLastInputs(){return Nn(this,void 0,void 0,(function*(){try{const e=yield f()(this.funcCall.inputParams.values()).reduce(((e,n)=>Nn(this,void 0,void 0,(function*(){const i=n.property.propertyType!==o.TYPE.DATA_FRAME?this.funcCall.inputs[n.name]:yield t.dapi.tables.uploadDataFrame(this.funcCall.inputs[n.name]);return Object.assign(Object.assign({},yield e),{[n.name]:JSON.stringify(i)})}))),Promise.resolve({}));return yield t.dapi.userDataStorage.put(this.inputsStorage,e)}catch(e){t.shell.error(e.toString())}}))}loadLastInputs(){return Nn(this,void 0,void 0,(function*(){try{const e=yield t.dapi.userDataStorage.get(this.inputsStorage);return 0===Object.keys(e).length?null:yield f()(this.funcCall.inputParams.values()).reduce(((n,i)=>Nn(this,void 0,void 0,(function*(){const s=i.property.propertyType!==o.TYPE.DATA_FRAME?JSON.parse(e[i.name]):yield t.dapi.tables.getTable(JSON.parse(e[i.name]));return Object.assign(Object.assign({},yield n),{[i.name]:s})}))),Promise.resolve({}))}catch(e){t.shell.error(e.toString())}}))}deleteLastInputs(){return Nn(this,void 0,void 0,(function*(){try{return yield t.dapi.userDataStorage.put(this.inputsStorage,{})}catch(e){t.shell.error(e.toString())}}))}doRun(){return Nn(this,void 0,void 0,(function*(){this.isRunning.next(!0);try{this.options.isTabbed||(yield this.saveLastInputs()),yield this.run(),this.options.isTabbed||(yield this.deleteLastInputs())}catch(e){t.shell.error(e.toString()),console.log(e)}finally{this.isRunning.next(!1),this.validationRequests.next({isRevalidation:!1,isNewOutput:!0})}}))}setExternalValidationResults(t,e){this.externalValidatorsState[t]=e,this.externalValidatorsUpdates.next(t)}saveInputLockState(t,e,n){"restricted"===n&&(this.funcCall.options[y]=Object.assign(Object.assign({},this.funcCall.options[y]),{[t]:e})),n&&(this.funcCall.options[b]=Object.assign(Object.assign({},this.funcCall.options[b]),{[t]:n})),this.updateConsistencyState()}getInputLockState(t){var e;return null===(e=this.funcCall.options[b])||void 0===e?void 0:e[t]}updateConsistencyState(){const t=Object.values(this.funcCall.options[b]).some((t=>"inconsistent"===t));this.consistencyState.next(t?"inconsistent":"consistent")}getInput(t){return this.inputsMap[t]}setInput(t,e,n){const i=this.getInput(t);if(!i)throw new Error(`No input named ${t}`);if(this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME&&"restricted"===n)throw new Error(`Param ${t} is dataframe. Restricted state is not supported for them.`);n||(n=this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME?"disabled":"restricted"),this.funcCall.inputs[t]=e,this.setInputLockState(i,t,e,n)}getParamChanges(t){const e=this.funcCall.inputParams[t]?"inputParams":"outputParams";return this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.filter)((()=>!!this.funcCall)),(0,s.switchMap)((()=>this.funcCall[e][t].onChanged.pipe((0,s.startWith)(null)))),(0,s.map)((()=>this.funcCall[e][t].value)))}getParamValue(t){var e,n;const i=(null===(e=this.funcCall)||void 0===e?void 0:e.inputParams[t])?"inputParams":"outputParams";return null===(n=this.funcCall)||void 0===n?void 0:n[i][t].value}setInputLockState(t,e,n,i){i&&this.saveInputLockState(e,n,i),j(t)&&("disabled"===i&&t.setDisabled(),"restricted"===i&&t.setRestricted(),"restricted unlocked"===i&&t.setRestrictedUnlocked(),"inconsistent"===i&&t.setInconsistent(),"user input"===i&&t.setUserInput())}getRestrictedValue(t){var e;return null===(e=this.funcCall.options[y])||void 0===e?void 0:e[t]}renderOutputForm(){return this.renderIOForm(Dn.OUTPUTS)}onSALaunch(){return Nn(this,void 0,void 0,(function*(){yield dn.fromEmpty(this.func)}))}onFittingLaunch(){return Nn(this,void 0,void 0,(function*(){yield Ln.fromEmpty(this.func)}))}renderInputForm(){return this.renderIOForm(Dn.INPUTS)}renderIOForm(t){const n=e.divH([],"ui-form ui-form-wide");a()(n).css({"flex-wrap":"wrap","flex-grow":"0","padding-right":"12px","padding-top":"0px","padding-left":"0px","max-width":"100%",gap:"4px"});let i="Misc";const o=this.funcCall[Vn[t]].values();return f()(o).filter((t=>!!t)).forEach((e=>{const o=e.property;this.beforeInputPropertyRender.next(o);const s=this.getInputForVal(e);s?(this.inputsMap[e.property.name]=s,t===Dn.INPUTS&&(this.syncInput(e,s,t),this.checkForMapping(e,s),this.runningOnInput||this.disableInputsOnRun(e.property.name,s),this.bindOnHotkey(s)),this.renderCategory(n,e.property.category,i),this.renderInput(n,e,s),this.afterInputPropertyRender.next({prop:o,input:s}),i=o.category):i=o.category})),Object.keys(this.foldedCategoryInputs).forEach((t=>this.foldedCategoryInputs[t].forEach((t=>a()(t.input.root).hide())))),n.classList.remove("ui-panel"),n}saveFocusedElement(t){this.focusedInput=t}restoreFocusedElement(){var t;null===(t=this.focusedInput)||void 0===t||t.focus()}disableInputsOnRun(t,e){const n=this.isRunning.subscribe((n=>{"user input"!==this.getInputLockState(t)&&this.getInputLockState(t)||(n?(tt(e)&&a()(e.input).is(":focus")&&this.saveFocusedElement(e.input),e.enabled=!1):(e.enabled=!0,tt(e)&&this.restoreFocusedElement()))}));this.subs.push(n)}checkForMapping(t,e){if(!e.hasOwnProperty("_chosenRun"))return;const n=t.property.options.funccallMapping;if(!n)return;const i=JSON.parse(n),o=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>this.funcCall.inputParams[t.property.name].onChanged))).subscribe((()=>{Object.entries(i).forEach((([t,n])=>this.setInput(t,e.chosenRun?(t=>{var n,i,o,s,r,a;return null!==(a=null!==(s=null!==(i=null===(n=e.chosenRun)||void 0===n?void 0:n.inputs[t])&&void 0!==i?i:null===(o=e.chosenRun)||void 0===o?void 0:o.outputs[t])&&void 0!==s?s:null===(r=e.chosenRun)||void 0===r?void 0:r.options[t])&&void 0!==a?a:null})(n):Bt(this.funcCall.inputParams[t].property),e.chosenRun?"restricted":"user input")))}));this.subs.push(o)}getInputForVal(t){var n,i;const s=t.property;if(this.inputsOverride[t.property.name])return this.inputsOverride[t.property.name];if(s.propertyType===o.TYPE.STRING&&s.options.choices&&!s.options.propagateChoice)return e.choiceInput(null!==(n=s.caption)&&void 0!==n?n:s.name,Bt(s),JSON.parse(s.options.choices));switch(s.propertyType){case"file":return te.fileInput(null!==(i=s.caption)&&void 0!==i?i:s.name,null,null,null);case o.TYPE.FLOAT:const t=e.input.forProperty(s),n=s.options.format;return n&&(t.format=n),t;default:return e.input.forProperty(s)}}bindOnHotkey(t){tt(t)&&(t.input.onkeydown=t=>Nn(this,void 0,void 0,(function*(){"Enter"==t.key&&this.runRequests.next()})))}get foldedCategories(){var t;return JSON.parse(null!==(t=this.func.options.foldedCategories)&&void 0!==t?t:"[]")}getCategoryWarningIcon(t){const n=e.iconFA("exclamation-circle",null,"This category has inconsistent inputs");a()(n).css({color:"var(--orange-2)","padding-left":"5px"}).hide();const i=this.funcCallReplaced.subscribe((()=>{this.foldedCategoryInputs[t].some((t=>"inconsistent"===this.getInputLockState(t.paramName)&&t.input.value!==this.getRestrictedValue(t.paramName)))?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}renderCategory(t,n,i){if(n!==i)if(this.foldedCategories.includes(n)){const i=this.getCategoryWarningIcon(n),o=e.iconFA("chevron-right",(()=>{var t;a()(s).show(),a()(o).hide(),a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).css({display:""})))}),"Open category");a()(o).css("padding-right","5px");const s=e.iconFA("chevron-down",(()=>{var t;a()(s).hide(),a()(o).show(),this.foldedCategoryInputs[n].some((t=>"inconsistent"===this.getInputLockState(t.paramName)))?a()(i).show():a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).hide()))}),"Close category");a()(s).css("padding-right","5px"),t.append(e.h2([o,s,e.h2(n,{style:{display:"inline"}}),i],{style:{width:"100%"}})),a()(s).hide()}else t.append(e.h2(n,{style:{width:"100%"}}))}renderInput(t,n,i){var o;const s=n.property;this.foldedCategories.includes(s.category)&&(this.foldedCategoryInputs[s.category]=[...null!==(o=this.foldedCategoryInputs[s.category])&&void 0!==o?o:[],{paramName:n.property.name,input:i}]),this.injectLockIcons(n,i),(t=>{if(j(t))return;const e=t;e.setDisabled=function(){t.enabled=!1,a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input")},e.setRestricted=function(){t.enabled=!1,tt(t)&&(t.input.disabled=!1),a()(t.root).addClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setRestrictedUnlocked=function(){t.enabled=!0,a()(t.root).addClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setInconsistent=function(){t.enabled=!0,a()(t.root).addClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")},e.setUserInput=function(){t.enabled=!0,a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")}})(i),tt(i)&&(((t,e)=>{var n;const i=t.property;a()(e.root).css({width:`calc(${null!==(n=i.options.block)&&void 0!==n?n:"100"}% - ${i.options.block?"2":"0"}px)`,"box-sizing":"border-box"})})(n,i),this.bindTooltips(n,i),(t=>{const n=e.element("i");t.addOptions(n),t.setValidation=function(i){for(;n.firstChild&&n.removeChild(n.firstChild););const[o,s]=function(t){let n,i;return(null==t?void 0:t.pending)&&(i=e.iconFA("spinner",(()=>{z(t,i,n)}))),(null==t?void 0:t.errors)&&t.errors.length?(i=e.iconFA("exclamation-circle",(()=>{z(t,i,n)})),i.style.color="var(--red-3)"):(null==t?void 0:t.warnings)&&t.warnings.length?(i=e.iconFA("exclamation-circle",(()=>{z(t,i,n)})),i.style.color="var(--orange-2)"):(null==t?void 0:t.notifications)&&t.notifications.length&&(i=e.iconFA("info-circle",(()=>{z(t,i,n)})),i.style.color="var(--blue-1)"),i&&(i.classList.remove("fal"),i.classList.add("far"),n=function(t){const n=e.div([],"d4-tooltip");return function(t){t.popover="auto",t.style.fontStyle="normal",t.style.pointerEvents="all"}(n),t.appendChild(n),n}(i)),[i,n]}(i);o&&s&&(n.appendChild(o),n.appendChild(s)),t.input.classList.remove("d4-invalid"),t.input.classList.remove("d4-partially-invalid"),(null==i?void 0:i.errors)&&i.errors.length||(null==i?void 0:i.warnings)&&i.warnings.length||(null==i?void 0:i.notifications)&&i.notifications.length||(null==i?void 0:i.pending)?a()(n).css("display","flex"):a()(n).hide(),(null==i?void 0:i.errors)&&i.errors.length?t.input.classList.add("d4-invalid"):(null==i?void 0:i.warnings)&&i.warnings.length&&t.input.classList.add("d4-partially-invalid")}})(i)),t.append(i.root)}bindTooltips(t,n){const i=t.property.name,o=()=>{var n,o;const s=`${null!==(o=null!==(n=t.property.description)&&void 0!==n?n:t.property.caption)&&void 0!==o?o:t.property.name}.`,r=(()=>"disabled"===this.getInputLockState(i)?"Input is disabled to prevent inconsistency.":"inconsistent"===this.getInputLockState(i)?"The entered value is inconsistent to the computed value.":"restricted"===this.getInputLockState(i)?"The value is dependent and computed automatically. Click to edit":null)();return s||r?e.divV([...s?[e.divText(s)]:[],...r?[e.divText(r)]:[]],{style:{"max-width":"300px"}}):null};e.tooltip.bind(n.captionLabel,o),e.tooltip.bind(n.input,o)}injectLockIcons(t,n){const i=t.property.name;n.root.addEventListener("click",(()=>{"restricted"===this.getInputLockState(i)&&this.setInputLockState(n,t.name,t.value,"restricted unlocked")}));const s=e.iconFA("lock");a()(s).addClass("rfv-icon-lock"),a()(s).css({color:"var(--grey-2)"});const r=e.iconFA("lock-open");a()(r).addClass("rfv-icon-unlock"),a()(r).css({color:"var(--grey-2)"});const l=e.iconFA("undo",(e=>{this.setInput(t.name,this.getRestrictedValue(i),"restricted"),e.stopPropagation()}),"Reset value to computed value");a()(l).addClass("rfv-icon-undo"),a()(l).css({color:"var(--blue-2)"});const u=e.iconFA("exclamation-circle",null);e.tooltip.bind(u,(()=>`Current value is incosistent. Computed value was ${o.TYPES_SCALAR.has(t.property.propertyType)?this.getRestrictedValue(i):"different"}`)),a()(u).addClass("rfv-icon-warning"),a()(u).css({color:"var(--orange-2)"});const c=n;c.placeLockStateIcons||(c.placeLockStateIcons=function(t,e,i,o){tt(n)&&(n.addOptions(t),n.addOptions(e),n.addOptions(i),n.addOptions(o))}),c.placeLockStateIcons(s,r,l,u)}syncInput(t,e,n){const i=t.name;let r=!1;const a=this.funcCallReplaced.pipe((0,s.startWith)(!0)).subscribe((()=>{var t,o;const s=this.funcCall[Vn[n]][i],r=null!==(o=null!==(t=this.funcCall[n][i])&&void 0!==t?t:Bt(s.property))&&void 0!==o?o:null;e.notify=!1,e.value=r,e.notify=!0,this.funcCall[n][i]=r,this.setInputLockState(e,i,r,this.getInputLockState(i))}));this.subs.push(a);const l=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[Vn[n]][i];return t.onChanged.pipe((0,s.mapTo)(t))}))).subscribe((t=>{const i=this.funcCall[n][t.name];if(r||(e.notify=!1,e.value=i,e.notify=!0),n===Dn.INPUTS){this.isHistorical.next(!1),this.hideOutput(),this.validationRequests.next({field:t.name,isRevalidation:!1});const n=this.getInputLockState(t.name);"restricted unlocked"!==n&&"inconsistent"!==n||this.setInputLockState(e,t.name,i,i===this.getRestrictedValue(t.name)?"restricted unlocked":"inconsistent")}}));this.subs.push(l);const u=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[Vn[n]][i];return t.onChanged.pipe((0,s.mapTo)(t),(0,s.startWith)(t))})),(0,s.filter)((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&t.value)),(0,s.switchMap)((t=>t.value.onDataChanged.pipe((0,s.mapTo)(t))))).subscribe((t=>{this.validationRequests.next({field:t.name,isRevalidation:!1})}));this.subs.push(u);const d=(p=e.onInput.bind(e),new c.Observable((t=>{const e=p((e=>{t.next(e)}));return()=>e.unsubscribe()}))).pipe((0,s.debounceTime)(250)).subscribe((()=>{try{r=!0,this.funcCall[n][t.name]=e.value}finally{r=!1}}));var p;this.subs.push(d)}isRunnable(){return!this.isRunning.value&&!this.blockRuns.value&&this.isValid()}isValid(){for(const[t,e]of Object.entries(this.validationState))if(!Y(e))return!1;for(const[t,e]of Object.entries(this.externalValidatorsState))if(!Y(e))return!1;return!0}getValidationState(){return this.validationState}getValidationMessage(){const t=[];for(const[e,n]of Object.entries(this.validationState))Y(n)||t.push(`${e}: ${U(n)}`);return t.join("\n")}runValidation(t,e){return Nn(this,void 0,void 0,(function*(){const n=t.field,i=this.getValidatedNames(n),o=yield Promise.all(i.map((n=>Nn(this,void 0,void 0,(function*(){const i=this.funcCall.inputs[n],o=yield(u=i,this._funcCall,this.lastCall,t.isNewOutput,t.isRevalidation,s=void 0,r=void 0,a=void 0,l=function*(){if(null==u)return W({errors:["Missing value"]})},new(a||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())})));var s,r,a,l,u;let c;const d=this.validators[n];return d&&(c=yield d(i,{param:n,funcCall:this._funcCall,lastCall:this.lastCall,signal:e,isNewOutput:!!t.isNewOutput,isRevalidation:t.isRevalidation,context:t.context,view:this})),[n,G(...this.funcCall.inputParams[n].property.options.nullable?[]:[o],c)]})))));return Object.fromEntries(o)}))}setValidationPending(t){const e=this.getValidatedNames(t);for(const t of e){this.validationState[t]={pending:!0};const e=this.inputsMap[t];V(e)&&e.setValidation({pending:!0})}this.validationUpdates.next(null)}setValidationResults(t){for(const[e,n]of Object.entries(t))this.validationState[e]=n,this.updateInputValidationReuslts(e)}updateInputValidationReuslts(t){const e=G(this.validationState[t],this.externalValidatorsState[t]),n=this.inputsMap[t];V(n)&&n.setValidation(e)}runRevalidations(t,e){if(!t.isRevalidation)for(const[,t]of Object.entries(e))if(null==t?void 0:t.revalidate)for(const e of t.revalidate)this.validationRequests.next({field:e,context:t.context,isRevalidation:!0})}getValidatedNames(t){return t?[t]:[...this.funcCall.inputs.keys()]}getValidExpRun(e){return Nn(this,void 0,void 0,(function*(){const n=yield(yield t.functions.eval("Sin")).prepare({x:1}).call();e.dart.r2=n.dart.r2;const i=e.options.immutable_tags||[];return e.options.immutable_tags=i.includes(C)?i:[...i,C],e.newId(),e}))}saveExperimentalRun(t){return Nn(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);yield this.saveRun(e)}))}hideOutput(){if(this._isOutputOutdated.next(!0),this.keepOutput())return;this.outputTabsLabels.forEach((t=>a()(this.tabsElem.getPane(t).header).hide()));const t=this.tabsElem.panes.find((t=>this.inputTabsLabels.includes(t.name)));t?this.tabsElem.currentPane=t:a()(this.tabsElem.root).hide()}getSheetName(t,e){if(this.sheetNamesCache[t])return this.sheetNamesCache[t];let n=`${t}`;n.length>31&&(n=`${n.slice(0,31)}`);let i=1;for(;e.worksheets.some((t=>t.name===n));){let e=`${t}`;e.length>31-`-${i}`.length&&(e=`${t.slice(0,31-`-${i}`.length)}`),n=`${e}-${i}`,i++}return this.sheetNamesCache[t]=n,n}richFunctionViewSupportedFormats(){return["Excel","DataUrl images"]}richFunctionViewExportExtensions(){return{Excel:"xlsx","DataUrl images":"txt"}}}n(693),Error;var Yn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};function Hn(e){return()=>Yn(this,void 0,void 0,(function*(){try{const n=yield t.dapi.groups.filter(`friendlyName="${e}"`).list();if(0===n.length)throw new Error("group with specified name is not found");if(n.length>1)throw new Error("found more than one group with specified name");const i=n[0];fetch(`${window.location.origin}/api/groups/${i.id}/requests/${t.shell.user.group.id}`,{method:"POST"})}catch(e){t.shell.error(e.toString())}}))}class Un extends o.ObjectHandler{get type(){return"Model"}getById(e){return Yn(this,void 0,void 0,(function*(){return yield t.dapi.functions.find(e)}))}refresh(t){return Yn(this,void 0,void 0,(function*(){return yield this.getById(t.id)}))}static openHelp(n){return Yn(this,void 0,void 0,(function*(){if(null!=n.options.readme){t.shell.windows.showHelp=!0,yield new Promise((t=>setTimeout(t,100)));const i=`System:AppData/${n.package.name}/${n.options.readme}`;t.dapi.files.readAsText(i).then((n=>{t.shell.windows.help.showHelp(e.markdown(n))}))}}))}static openModel(t){t.prepare().edit()}static openModelFromFunccall(t){t.edit()}isApplicable(t){const e=o.toJs(t);return e instanceof o.Func&&e.hasTag("model")}constructor(){super(),this.userGroups=new c.BehaviorSubject(void 0)}getLanguageIcon(t){return"grok"==t?e.iconSvg("project"):e.iconImage("script",`/images/entities/${t}.png`)}renderMarkup(n){const i=e.divH([],{style:{"justify-content":"space-between",width:"100%"}});return setTimeout((()=>Yn(this,void 0,void 0,(function*(){const o=yield this.awaitUserGroups(),s=JSON.parse(n.options.mandatoryUserGroups?`${n.options.mandatoryUserGroups}`:"[]").filter((t=>!o.map((t=>t.friendlyName)).includes(t.name))),r=s.length>0,a=e.iconFA("exclamation-triangle",null);a.classList.remove("grok-icon");const l=()=>{const t=e.iconFA("times");return t.style.marginRight="6px",t.classList.remove("grok-icon"),t},u=e.div(e.divV([e.label("You should be a member of the following group(s):",{style:{marginLeft:"0px"}}),...s.map((t=>e.divV([e.span([l(),t.name],{style:{"font-weight":600}}),...t.help?[e.span([t.help],{style:{marginLeft:"16px"}})]:[],e.link("Request group membership",Hn(t.name),void 0,{style:{marginLeft:"16px"}})])))],{style:{gap:"10px"}})),c=e.span([this.renderIcon(n),e.label(n.friendlyName)]);var d;i.onclick=()=>{t.shell.windows.help.visible&&Un.openHelp(n)},r?c.classList.add("d4-disabled"):i.ondblclick=()=>{Un.openModel(n)},r&&(function(t){t.popover="auto",t.style.cursor="default",t.style.padding="10px",t.style.background="#fdffe5",t.style.border="1px solid #E4E6CE",t.style.borderRadius="2px",t.style.boxShadow="0 0 5px #E4E6CE",t.style.maxWidth="500px",t.style.color="var(--gray-6)"}(d=u),document.body.append(d),i.addEventListener("click",(()=>{!function(t,e){!function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(t,e),e.showPopover()}(a,u)}))),i.append(c),r&&i.append(e.span([a]))})))),i}renderIcon(t){if(null!=t.options.icon&&(t.options.icon.startsWith("http://")||t.options.icon.startsWith("https://")))return e.iconImage("model-icon",t.options.icon);if(t instanceof o.Script)return this.getLanguageIcon(t.language);let n=(t=o.Func.find({package:t.package.name,name:t.name})[0]).package.getIconUrl();if(null!=t.options.icon){const e=n.split("/");e.pop(),e.push(t.options.icon),n=e.join("/")}return e.iconImage(t.package.name,n)}renderPreview(e){const n=Object.create(null,{renderPreview:{get:()=>super.renderPreview}});return Yn(this,void 0,void 0,(function*(){var i;const s=null!==(i=e.options.editor)&&void 0!==i?i:"Compute:RichFunctionViewEditor",r=yield t.functions.find(s);if(null!==r&&r instanceof o.Func){const t=r.prepare({call:e.prepare()});yield t.call(!1,void 0,{processed:!0});const n=t.getOutputParamValue();if(n instanceof o.View)return n}return n.renderPreview.call(this,e)}))}renderProperties(t){const n=e.accordion("ComputeModel");n.context=t;const i=e.div([e.span([this.renderIcon(t),e.label(t.friendlyName),e.contextActions(t),e.star(t.id)])]);return n.addTitle(i),null!=t.description&&i.appendChild(e.div([e.markdown(t.description)],"model-catalog-description")),i.appendChild(e.tags(t)),null!=t.options["dev.status"]&&i.appendChild(e.tableFromMap({Status:t.options["dev.status"]})),n.end(),n.root}renderTooltip(t){const n=e.span([this.renderIcon(t),e.label(t.friendlyName)]);return n.classList.add("d4-link-label"),e.bind(t,e.divV([e.h2(n),e.divV([e.divText(t.description,"ui-description")],{style:{lineHeight:"150%"}})]))}renderCard(t){const n=this.renderMarkup(t);return n.classList.add("d4-link-label"),e.bind(t,e.h2(n))}init(){this.registerParamFunc("Help",(t=>{Un.openHelp(o.toJs(t))})),setTimeout((()=>Yn(this,void 0,void 0,(function*(){const t=yield(yield fetch(`${window.location.origin}/api/groups/all_parents`)).json();this.userGroups.next(t)}))))}awaitUserGroups(){return Yn(this,void 0,void 0,(function*(){return this.userGroups.pipe((0,s.filter)((t=>!!t)),(0,s.map)((t=>t)),(0,s.take)(1)).toPromise()}))}}var Wn=n(847),Gn={};Gn.styleTagTransform=It(),Gn.setAttributes=bt(),Gn.insert=gt().bind(null,"head"),Gn.domAPI=mt(),Gn.insertStyleElement=Ct(),ht()(Wn.A,Gn),Wn.A&&Wn.A.locals&&Wn.A.locals;class zn extends o.CustomCardView{static findOrCreateCatalogView(t,e,n){var i;return null!==(i=this.findModelCatalogView(e))&&void 0!==i?i:this.createModelCatalogView(t,e,n)}static createModelCatalogView(t,e,n){const i=o.Func.find({package:n.name,name:e})[0].prepare(),s=new this(t,e);return s.parentCall=i,s}static findModelCatalogView(e){return f()(t.shell.views).find((t=>{var n;return(null===(n=t.parentCall)||void 0===n?void 0:n.func.name)==e}))}bindModel(t){var e;t.aux.showOnTaskBar=!1;const n=this.parentCall;null!=n&&(n.aux.view=null!==(e=zn.findModelCatalogView(this.funcName))&&void 0!==e?e:this,t.parentCall=n)}constructor(e,n){if(super({dataSource:t.dapi.functions,permanentFilter:"#model"}),this.funcName=n,this.isHelpOpen=!1,this.root.classList.add("model-catalog-view"),this.meta=new Un,this.name=e,this.permanentFilter="#model",this.renderMode=o.RENDER_MODE.BRIEF,this.objectType="Func",this.categoryFilters={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process",tag:"Tags"},this.filters={All:"",Favorites:"starredBy = @current","Used by me":"usedBy = @current"},this.hierarchy=["options.department","options.HL_process","options.process"],this.hierarchyProperties={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process"},this.showTree=!0,this.initRibbon(),this.initMenu(),t.shell.windows.showProperties=!1,t.shell.windows.showHelp=this.isHelpOpen,!zn.findModelCatalogView(this.funcName)){const e=t.functions.onBeforeRunAction.subscribe((t=>{var e,n;t.func.hasTag("model")?this.bindModel(t):(null===(n=null===(e=t.inputs)||void 0===e?void 0:e.call)||void 0===n?void 0:n.func)instanceof o.Func&&t.inputs.call.func.hasTag("model")&&this.bindModel(t.inputs.call)})),n=t.events.onCurrentViewChanged.subscribe((()=>{return e=this,n=void 0,o=function*(){t.shell.v===this&&(t.shell.windows.showHelp=this.isHelpOpen)},new((i=void 0)||(i=Promise))((function(t,s){function r(t){try{l(o.next(t))}catch(t){s(t)}}function a(t){try{l(o.throw(t))}catch(t){s(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((o=o.apply(e,n||[])).next())}));var e,n,i,o}));this.subs.push(e,n)}}initRibbon(){}initMenu(){this.ribbonMenu.group("Help").item("Compute Engine",(()=>window.open("https://github.com/datagrok-ai/public/tree/master/packages/Compute","_blank"))).item("Developing Models",(()=>window.open("https://datagrok.ai/help/compute/scripting","_blank"))).endGroup()}}var Jn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};let qn=!1;const Kn=new o.Package;function Zn(t){Un.openModelFromFunccall(t)}function Xn(){return new u}function Qn(t){return $n.fromFuncCall(t,{historyEnabled:!0,isTabbed:!1})}function ti(t){return $n.fromFuncCall(t,{historyEnabled:!1,isTabbed:!0})}function ei(n){return Jn(this,void 0,void 0,(function*(){let i={};n.inputs.forEach((t=>i[t.name]=null));let s=`\ncurl --location --request POST '${t.settings.apiUrl}/v1/func/${n.nqName}/run' \\\n--header 'Authorization: ${ni("auth")}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '${JSON.stringify(i)}'`,r=`\nvar myHeaders = new Headers();\nmyHeaders.append("Authorization", "${ni("auth")}");\nmyHeaders.append("Content-Type", "application/json");\n\nvar raw = JSON.stringify(${JSON.stringify(i)});\n\nvar requestOptions = {\n method: 'POST',\n headers: myHeaders,\n body: raw,\n redirect: 'follow'\n};\n\nfetch("${t.settings.apiUrl}/v1/func/${n.nqName}/run", requestOptions)\n .then(response => response.text())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));`,a=e.tabControl({CURL:e.div([e.divText(s)]),JS:e.div([e.divText(r)])});return o.Widget.fromRoot(a.root)}))}function ni(t){let e=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0}function ii(t){return Jn(this,void 0,void 0,(function*(){return yield new Promise((t=>setTimeout(t,1e3))),[yield t.prepare({ambTemp:22,initTemp:100,desiredTemp:30,area:.06,heatCap:4200,heatTransferCoeff:8.3,simTime:21600}).call()]}))}function oi(n){return Jn(this,void 0,void 0,(function*(){const i=(yield t.functions.eval("Compute:CustomDataUploader")).prepare({func:n.func}),r=e.bigButton("Click me to get mock calls",(()=>i.call())),a=o.Widget.fromRoot(e.panel([e.divV([e.label("This part of dialog comes from my custom data uploader"),e.divH([r],{style:{"justify-content":"center"}})])])),l=t.functions.onBeforeRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!0)})),u=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!1)}));return a.subs.push(l,u),{uploadWidget:a,uploadFuncCall:i}}))}function si(t){t.defaultView.scatterPlot({xColumnName:"Initial temperature",yColumnName:"Time to cool"})}function ri(){qn||(o.ObjectHandler.list().find((t=>"Model"===t.type))||o.ObjectHandler.register(new Un),t.events.onAccordionConstructed.subscribe((t=>{const n=t.context;null!=n&&"script"==n.type&&(t.getPane("REST")||t.addPane("REST",(()=>e.wait((()=>Jn(this,void 0,void 0,(function*(){return(yield ei(n)).root})))))))})),qn=!0)}let ai=!1;function li(){const e=t.shell.startUri.indexOf("?"),n=t.shell.startUri.substring(8,e>0?e:void 0).split("/");if(!ai&&n.includes("Compute")){const e=zn.findOrCreateCatalogView("Model Catalog","modelCatalog",Kn);return t.shell.addView(e),ai=!0,void(n.length>3&&t.dapi.functions.filter(`shortName = "${n[3]}" and #model`).list().then((t=>{1==t.length&&Un.openModel(t[0])})))}const i=window.location.href.indexOf("?"),o=window.location.href.substring(8,i>0?i:void 0).split("/");if(o.includes("browse")){const e=zn.findModelCatalogView("modelCatalog");return e&&(t.shell.v=e),zn.createModelCatalogView("Model Catalog","modelCatalog",Kn)}if(o.includes("apps")){const e=zn.findModelCatalogView("modelCatalog");if(e)t.shell.v=e;else{const e=zn.createModelCatalogView("Model Catalog","modelCatalog",Kn);t.shell.addView(e)}}}function ci(t){const{reasonableMin:e,reasonableMax:n}=t;return t=>W({warnings:t<e||t>n?[`Minimum reasonable time is ${e}. Maximum reasonable time is ${n}`]:void 0,errors:t<0?["Time should be strictly positive"]:void 0})}function di(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp,i=e.funcCall.inputs.initTemp;return W({errors:[...t<n?[H(`Desired temperature cannot be less than ambient temperature (${n}). \n`,[{actionName:"Set desired equal to ambient",action:()=>e.funcCall.inputs.desiredTemp=n}])]:[],...t>i?[`Desired temperature cannot be higher than initial temperature (${i})`]:[]]})}}function pi(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp;return W({errors:[...t<n?[`Initial temperature cannot be less than ambient temperature (${n}).`]:[]]})}}function hi(t){return(t,e)=>{const n=e.funcCall.inputs.initTemp;return W({errors:[...t>n?[`Ambient temperature cannot be higher than initial temperature (${n})`]:[]]})}}function fi(t){return(t,e)=>W({errors:[...t<=0?["Heat capacity must be greater than zero."]:[]],notifications:[H("Heat capacity is only dependent on the object material.",[{actionName:"Google it",action:()=>{window.open("http://google.com")}}])]})}function mi(t){const n=e.stringInput("Custom input","");return n.root.style.backgroundColor="aqua",n.input.style.backgroundColor="aqua",n}function vi(t){return te.historyInputJSON("Previous run","ObjectCooling")}})(),compute=i})();
|
|
1
|
+
var compute;(()=>{var t={933:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/pipeline-view.css"],names:[],mappings:"AAAA;EACE;AACF;;AAEA;EACE,oBAAoB;EACpB,gBAAgB;EAChB,mBAAmB;EACnB,qBAAqB;AACvB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,eAAe;EACf,oBAAoB;EACpB,oBAAoB;AACtB;;AAEA;EACE;AACF",sourcesContent:[".pipeline-view .d4-ribbon-name.selected {\n color: var(--grey-6)\n}\n\n.pipeline-view .d4-ribbon-name {\n color: var(--blue-1);\n margin: 12px 6px;\n font-weight: normal;\n place-content: center;\n}\n\n.pipeline-view .d4-ribbon-name + .d4-ribbon-name::before {\n color: var(--grey-3);\n}\n\n.pipeline-view .d4-ribbon-name.d4-disabled {\n cursor: default;\n pointer-events: none;\n color: var(--grey-3);\n}\n\n.ui-input-editor button.ui-btn-nav.ui-btn.d4-disabled {\n color: var(--grey-3)\n}"],sourceRoot:""}]);const a=r},362:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/rich-function-view.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,gBAAgB;AACpB;;AAEA;IACI,eAAe;AACnB;;AAEA;IACI,mBAAmB;IACnB,yBAAyB;AAC7B;;AAEA,oCAAoC;AACpC;;;;IAII,aAAa;AACjB;;AAEA,mDAAmD;AACnD;IACI,gBAAgB;AACpB;;AAEA,+DAA+D;AAC/D;IACI,gBAAgB;AACpB;;AAEA,+CAA+C;AAC/C;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;AACA;IACI,aAAa;AACjB;AACA;IACI,gBAAgB;AACpB;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,QAAQ;IACR,yBAAyB;AAC7B;;AAEA;IACI,2BAA2B;AAC/B;;AAEA;IACI,yBAAyB;IACzB,YAAY;AAChB;;AAEA;IACI,kBAAkB;IAClB,mBAAmB;AACvB;;AAEA;IACI,gBAAgB;IAChB,uCAAuC;AAC3C;;AAEA;IACI,+BAA+B;AACnC;;AAEA;IACI,WAAW;AACf",sourcesContent:[".ui-form .ui-input-buttons.rfv-buttons {\n margin-top: 0px;\n position: sticky;\n}\n\n.ui-form .ui-input-buttons.rfv-buttons .ui-input-editor {\n flex-wrap: wrap;\n}\n\n.ui-input-root.rfv-restricted-input.d4-disabled {\n pointer-events: all;\n cursor: pointer!important;\n}\n\n/* Hide all state icons by default */\n.ui-input-root > .ui-input-options .rfv-icon-lock,\n.ui-input-root > .ui-input-options .rfv-icon-unlock,\n.ui-input-root > .ui-input-options .rfv-icon-undo,\n.ui-input-root > .ui-input-options .rfv-icon-warning {\n display: none;\n}\n\n/* Show warning icon if input is on warning state */\n.ui-input-root.rfv-inconsistent-input > .ui-input-options .rfv-icon-warning {\n display: inherit;\n}\n\n/* Show undo icon if input is on inconstent state and hovered */\n.ui-input-root.rfv-restricted-unlocked-input:hover .rfv-icon-undo, .ui-input-root.rfv-inconsistent-input:hover .rfv-icon-undo {\n display: inherit;\n}\n\n/* Show/hide lock-unlock icons on input hover */\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-lock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-lock {\n display: inherit;\n}\n.ui-input-root.rfv-restricted-input .rfv-icon-unlock {\n display: none;\n}\n.ui-input-root.rfv-restricted-input:hover .rfv-icon-unlock {\n display: inherit;\n}\n\n.ui-form-condensed .rfv-buttons > .ui-label {\n margin-right: 0px!important;\n}\n\n.rfv-form .ui-form .rfv-buttons > .ui-input-editor {\n gap: 5px;\n justify-content: flex-end;\n}\n\ndiv.ui-box > div.ui-box.rfv-form > div.ui-div {\n overflow: visible!important;\n}\n\n.rfv-scalar-table {\n border-collapse: collapse;\n margin: 10px;\n}\n\n.rfv-scalar-table td {\n width: max-content;\n white-space: nowrap;\n}\n\n.rfv-scalar-table tr{\n min-height: 30px;\n border-bottom: 1pt solid var(--grey-12);\n}\n\n.rfv-scalar-table tr:nth-child(odd) {\n background-color: var(--grey-1);\n}\n\n.rfv-scalar-table td:last-child {\n width: 100%;\n}"],sourceRoot:""}]);const a=r},993:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/function-views/css/sens-analysis.css"],names:[],mappings:"AAAA;IACI,eAAe;IACf,eAAe;AACnB;;AAEA;IACI,SAAS;IACT,SAAS;IACT,kBAAkB;AACtB;;AAEA;IACI,YAAY;AAChB;;AAEA;IACI,iBAAiB;AACrB",sourcesContent:[".ui-form .ui-input-root .sa-switch-input {\n max-width: 50px;\n min-width: 50px;\n}\n\n.ui-form.ui-form-condensed .ui-input-root .sa-switch-input {\n order: -3;\n top: -5px;\n position: relative;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input + label.ui-input-label:not(:empty) {\n width: unset;\n}\n\n.ui-form.ui-form-condensed .ui-input-root > .sa-switch-input ~ .ui-input-editor {\n margin-left: 50px;\n}"],sourceRoot:""}]);const a=r},847:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,'.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}',"",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/model-catalog/css/model-card.css"],names:[],mappings:"AAAA;IACI,YAAY;IACZ,WAAW;IACX,iBAAiB;IACjB,cAAc;AAClB;;AAEA;IACI,gBAAgB;IAChB,mBAAmB;IACnB,oBAAoB;IACpB,mBAAmB;AACvB;;AAEA;IACI,cAAc;IACd,mBAAmB;IACnB,aAAa;IACb,SAAS;IACT,YAAY;AAChB;;AAEA;IACI,6BAA6B;AACjC;;AAEA;IACI,WAAW;IACX,YAAY;IACZ,iBAAiB;AACrB;;AAEA;IACI,gBAAgB;AACpB;;AAEA;IACI,gBAAgB;IAChB,kBAAkB;IAClB,oBAAoB;IACpB,aAAa;IACb,cAAc;AAClB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,eAAe;IACf,cAAc;IACd,oBAAoB;AACxB;;AAEA;IACI,UAAU;IACV,SAAS;IACT,mBAAmB;IACnB,qBAAqB;IACrB,+BAA+B;IAC/B,kBAAkB;IAClB,sBAAsB;IACtB,4BAA4B;AAChC;;AAEA;IACI,kBAAkB;IAClB,QAAQ;IACR,OAAO;IACP,SAAS;IACT,MAAM;IACN,aAAa;IACb,mBAAmB;IACnB,uBAAuB;IACvB,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;AACnB;;AAEA;IACI,oBAAoB;AACxB;;AAEA;IACI,mBAAmB;AACvB",sourcesContent:['.model-catalog-view .d4-gallery-card.entity-model i.grok-icon {\n height: 64px;\n width: 64px;\n position: initial;\n flex-shrink: 0;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model .d4-link-label i.grok-icon + label {\n margin-left: 6px;\n align-items: center;\n display: inline-flex;\n white-space: normal;\n}\n\n.model-catalog-view .d4-gallery-card.entity-model {\n padding: 0 8px;\n align-items: center;\n display: flex;\n margin: 0;\n height: 94px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid {\n flex-direction: row!important;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label i.grok-icon {\n width: 32px;\n height: 32px;\n position: initial;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .d4-link-label label {\n margin-left: 8px;\n}\n\n.model-catalog-view .grok-gallery-grid[mode="Brief"] .grok-gallery-grid .d4-link-label {\n min-width: 250px;\n margin-bottom: 9px;\n color: var(--grey-6);\n padding: 10px;\n width: initial;\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 20px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-node {\n font-size: 16px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-view .d4-tree-view-root > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group > .d4-tree-view-group-host > .d4-tree-view-group .d4-tree-view-node {\n font-size: 14px;\n padding: 4px 0;\n color: var(--grey-6);\n}\n\n.model-catalog-video {\n width: 80%;\n height: 0;\n padding-bottom: 50%;\n margin: 10px 10px 0 0;\n border: 1px solid var(--grey-2);\n position: relative;\n background-size: cover;\n background-repeat: no-repeat;\n}\n\n.model-catalog-video i {\n position: absolute;\n right: 0;\n left: 0;\n bottom: 0;\n top: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n font-weight: 600;\n color: var(--grey-2);\n font-size: 42px;\n}\n\n.model-catalog-video i:hover {\n color: var(--grey-1);\n}\n\n.model-catalog-description {\n padding: 10px 0 0 0;\n}'],sourceRoot:""}]);const a=r},911:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/file-input.css"],names:[],mappings:"AAAA;EACE,kBAAkB;AACpB;;AAEA;EACE,oBAAoB;AACtB;;AAEA;EACE,gCAAgC;EAChC,gCAAgC;EAChC,oBAAoB;AACtB;;AAEA;EACE,mBAAmB;AACrB;;AAEA;EACE,oBAAoB;AACtB",sourcesContent:[".fi-drop-area {\n position: relative;\n}\n\n.fi-drop-area .default {\n color: var(--grey-2);\n}\n\n.fi-drop-area .drag-n-dropping {\n background-color: var(--steel-1);\n border: 1px dashed var(--blue-1);\n color: var(--grey-3);\n}\n\n.fi-drop-area .error {\n color: var(--red-3);\n}\n\n.fi-drop-area .success {\n color: var(--grey-6);\n}\n"],sourceRoot:""}]);const a=r},703:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,"","",{version:3,sources:[],names:[],mappings:"",sourceRoot:""}]);const a=r},565:(t,e,n)=>{"use strict";n.d(e,{A:()=>a});var i=n(354),o=n.n(i),s=n(314),r=n.n(s)()(o());r.push([t.id,".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n","",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/compute-utils/shared-components/css/history-panel.css"],names:[],mappings:"AAAA;IACI,YAAY;AAChB;;AAEA;IACI,oBAAoB;IACpB,YAAY;AAChB;;AAEA;IACI,aAAa;AACjB;;AAEA;IACI,aAAa;IACb,uBAAuB;AAC3B;;AAEA;IACI,eAAe;IACf,YAAY;IACZ,8BAA8B;AAClC;;AAEA;IACI,6BAA6B;IAC7B,gBAAgB;AACpB;;AAEA;IACI,kBAAkB;AACtB;;AAEA;IACI,kBAAkB;IAClB,oBAAoB;AACxB;;AAEA;IACI,oBAAoB;IACpB,gBAAgB;AACpB",sourcesContent:[".hp-no-elements-label {\n margin: 12px;\n}\n\n.grok-icon.hp-disabled {\n pointer-events: none;\n opacity: 0.6;\n}\n\n.hp-funccall-card-hover-icon {\n display: none;\n}\n\n.hp-funccall-card:hover .hp-funccall-card-hover-icon {\n display: flex;\n margin: 0px 0px 0px 5px;\n}\n\n.hp-funccall-card {\n margin: 2px 1px;\n padding: 5px;\n justify-content: space-between;\n}\n\n.hp-funccall-card .hp-card-content {\n justify-content: space-around;\n margin-left: 5px;\n}\n\n.hp-funccall-card .hp-card-content * {\n margin-bottom: 3px;\n}\n\n.hp-funccall-card .description {\n margin-bottom: 2px;\n color: var(--grey-3);\n}\n\n.hp-funccall-card .date {\n color: var(--grey-3);\n margin-left: 5px;\n}\n"],sourceRoot:""}]);const a=r},314:t=>{"use strict";t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var n="",i=void 0!==e[5];return e[4]&&(n+="@supports (".concat(e[4],") {")),e[2]&&(n+="@media ".concat(e[2]," {")),i&&(n+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),n+=t(e),i&&(n+="}"),e[2]&&(n+="}"),e[4]&&(n+="}"),n})).join("")},e.i=function(t,n,i,o,s){"string"==typeof t&&(t=[[null,t,void 0]]);var r={};if(i)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(r[l]=!0)}for(var u=0;u<t.length;u++){var c=[].concat(t[u]);i&&r[c[0]]||(void 0!==s&&(void 0===c[5]||(c[1]="@layer".concat(c[5].length>0?" ".concat(c[5]):""," {").concat(c[1],"}")),c[5]=s),n&&(c[2]?(c[1]="@media ".concat(c[2]," {").concat(c[1],"}"),c[2]=n):c[2]=n),o&&(c[4]?(c[1]="@supports (".concat(c[4],") {").concat(c[1],"}"),c[4]=o):c[4]="".concat(o)),e.push(c))}},e}},354:t=>{"use strict";t.exports=function(t){var e=t[1],n=t[3];if(!n)return e;if("function"==typeof btoa){var i=btoa(unescape(encodeURIComponent(JSON.stringify(n)))),o="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(i),s="/*# ".concat(o," */");return[e].concat([s]).join("\n")}return[e].join("\n")}},826:function(t){t.exports=function(){"use strict";var t="minute",e=/[+-]\d\d(?::?\d\d)?/g,n=/([+-]|\d\d)/g;return function(i,o,s){var r=o.prototype;s.utc=function(t){return new o({date:t,utc:!0,args:arguments})},r.utc=function(e){var n=s(this.toDate(),{locale:this.$L,utc:!0});return e?n.add(this.utcOffset(),t):n},r.local=function(){return s(this.toDate(),{locale:this.$L,utc:!1})};var a=r.parse;r.parse=function(t){t.utc&&(this.$u=!0),this.$utils().u(t.$offset)||(this.$offset=t.$offset),a.call(this,t)};var l=r.init;r.init=function(){if(this.$u){var t=this.$d;this.$y=t.getUTCFullYear(),this.$M=t.getUTCMonth(),this.$D=t.getUTCDate(),this.$W=t.getUTCDay(),this.$H=t.getUTCHours(),this.$m=t.getUTCMinutes(),this.$s=t.getUTCSeconds(),this.$ms=t.getUTCMilliseconds()}else l.call(this)};var u=r.utcOffset;r.utcOffset=function(i,o){var s=this.$utils().u;if(s(i))return this.$u?0:s(this.$offset)?u.call(this):this.$offset;if("string"==typeof i&&(i=function(t){void 0===t&&(t="");var i=t.match(e);if(!i)return null;var o=(""+i[0]).match(n)||["-",0,0],s=o[0],r=60*+o[1]+ +o[2];return 0===r?0:"+"===s?r:-r}(i),null===i))return this;var r=Math.abs(i)<=16?60*i:i,a=this;if(o)return a.$offset=r,a.$u=0===i,a;if(0!==i){var l=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(a=this.local().add(r+l,t)).$offset=r,a.$x.$localOffset=l}else a=this.utc();return a};var c=r.format;r.format=function(t){var e=t||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,e)},r.valueOf=function(){var t=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*t},r.isUTC=function(){return!!this.$u},r.toISOString=function(){return this.toDate().toISOString()},r.toString=function(){return this.toDate().toUTCString()};var d=r.toDate;r.toDate=function(t){return"s"===t&&this.$offset?s(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var p=r.diff;r.diff=function(t,e,n){if(t&&this.$u===t.$u)return p.call(this,t,e,n);var i=this.local(),o=s(t).local();return p.call(i,o,e,n)}}}()},693:(t,e,n)=>{t=n.nmd(t);var i="__lodash_hash_undefined__",o=9007199254740991,s="[object Arguments]",r="[object Boolean]",a="[object Date]",l="[object Function]",u="[object GeneratorFunction]",c="[object Map]",d="[object Number]",p="[object Object]",h="[object Promise]",f="[object RegExp]",m="[object Set]",v="[object String]",g="[object Symbol]",y="[object WeakMap]",b="[object ArrayBuffer]",A="[object DataView]",C="[object Float32Array]",w="[object Float64Array]",I="[object Int8Array]",T="[object Int16Array]",E="[object Int32Array]",x="[object Uint8Array]",R="[object Uint8ClampedArray]",S="[object Uint16Array]",O="[object Uint32Array]",P=/\w*$/,F=/^\[object .+?Constructor\]$/,_=/^(?:0|[1-9]\d*)$/,k={};k[s]=k["[object Array]"]=k[b]=k[A]=k[r]=k[a]=k[C]=k[w]=k[I]=k[T]=k[E]=k[c]=k[d]=k[p]=k[f]=k[m]=k[v]=k[g]=k[x]=k[R]=k[S]=k[O]=!0,k["[object Error]"]=k[l]=k[y]=!1;var M="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g,B="object"==typeof self&&self&&self.Object===Object&&self,L=M||B||Function("return this")(),D=e&&!e.nodeType&&e,N=D&&t&&!t.nodeType&&t,V=N&&N.exports===D;function j(t,e){return t.set(e[0],e[1]),t}function $(t,e){return t.add(e),t}function Y(t,e,n,i){var o=-1,s=t?t.length:0;for(i&&s&&(n=t[++o]);++o<s;)n=e(n,t[o],o,t);return n}function H(t){var e=!1;if(null!=t&&"function"!=typeof t.toString)try{e=!!(t+"")}catch(t){}return e}function U(t){var e=-1,n=Array(t.size);return t.forEach((function(t,i){n[++e]=[i,t]})),n}function W(t,e){return function(n){return t(e(n))}}function G(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t})),n}var z,J=Array.prototype,q=Function.prototype,K=Object.prototype,Z=L["__core-js_shared__"],X=(z=/[^.]+$/.exec(Z&&Z.keys&&Z.keys.IE_PROTO||""))?"Symbol(src)_1."+z:"",Q=q.toString,tt=K.hasOwnProperty,et=K.toString,nt=RegExp("^"+Q.call(tt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),it=V?L.Buffer:void 0,ot=L.Symbol,st=L.Uint8Array,rt=W(Object.getPrototypeOf,Object),at=Object.create,lt=K.propertyIsEnumerable,ut=J.splice,ct=Object.getOwnPropertySymbols,dt=it?it.isBuffer:void 0,pt=W(Object.keys,Object),ht=Lt(L,"DataView"),ft=Lt(L,"Map"),mt=Lt(L,"Promise"),vt=Lt(L,"Set"),gt=Lt(L,"WeakMap"),yt=Lt(Object,"create"),bt=$t(ht),At=$t(ft),Ct=$t(mt),wt=$t(vt),It=$t(gt),Tt=ot?ot.prototype:void 0,Et=Tt?Tt.valueOf:void 0;function xt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Rt(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function St(t){var e=-1,n=t?t.length:0;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}function Ot(t){this.__data__=new Rt(t)}function Pt(t,e,n){var i=t[e];tt.call(t,e)&&Yt(i,n)&&(void 0!==n||e in t)||(t[e]=n)}function Ft(t,e){for(var n=t.length;n--;)if(Yt(t[n][0],e))return n;return-1}function _t(t,e,n,i,o,h,y){var F;if(i&&(F=h?i(t,o,h,y):i(t)),void 0!==F)return F;if(!zt(t))return t;var _=Ht(t);if(_){if(F=function(t){var e=t.length,n=t.constructor(e);return e&&"string"==typeof t[0]&&tt.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!e)return function(t,e){var n=-1,i=t.length;for(e||(e=Array(i));++n<i;)e[n]=t[n];return e}(t,F)}else{var M=Nt(t),B=M==l||M==u;if(Wt(t))return function(t,e){if(e)return t.slice();var n=new t.constructor(t.length);return t.copy(n),n}(t,e);if(M==p||M==s||B&&!h){if(H(t))return h?t:{};if(F=function(t){return"function"!=typeof t.constructor||jt(t)?{}:zt(e=rt(t))?at(e):{};var e}(B?{}:t),!e)return function(t,e){return Mt(t,Dt(t),e)}(t,function(t,e){return t&&Mt(e,Jt(e),t)}(F,t))}else{if(!k[M])return h?t:{};F=function(t,e,n,i){var o,s=t.constructor;switch(e){case b:return kt(t);case r:case a:return new s(+t);case A:return function(t,e){var n=e?kt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,i);case C:case w:case I:case T:case E:case x:case R:case S:case O:return function(t,e){var n=e?kt(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}(t,i);case c:return function(t,e,n){return Y(e?n(U(t),!0):U(t),j,new t.constructor)}(t,i,n);case d:case v:return new s(t);case f:return function(t){var e=new t.constructor(t.source,P.exec(t));return e.lastIndex=t.lastIndex,e}(t);case m:return function(t,e,n){return Y(e?n(G(t),!0):G(t),$,new t.constructor)}(t,i,n);case g:return o=t,Et?Object(Et.call(o)):{}}}(t,M,_t,e)}}y||(y=new Ot);var L=y.get(t);if(L)return L;if(y.set(t,F),!_)var D=n?function(t){return function(t,e,n){var i=e(t);return Ht(t)?i:function(t,e){for(var n=-1,i=e.length,o=t.length;++n<i;)t[o+n]=e[n];return t}(i,n(t))}(t,Jt,Dt)}(t):Jt(t);return function(t,e){for(var n=-1,i=t?t.length:0;++n<i&&!1!==e(t[n],n););}(D||t,(function(o,s){D&&(o=t[s=o]),Pt(F,s,_t(o,e,n,i,s,t,y))})),F}function kt(t){var e=new t.constructor(t.byteLength);return new st(e).set(new st(t)),e}function Mt(t,e,n,i){n||(n={});for(var o=-1,s=e.length;++o<s;){var r=e[o],a=i?i(n[r],t[r],r,n,t):void 0;Pt(n,r,void 0===a?t[r]:a)}return n}function Bt(t,e){var n,i,o=t.__data__;return("string"==(i=typeof(n=e))||"number"==i||"symbol"==i||"boolean"==i?"__proto__"!==n:null===n)?o["string"==typeof e?"string":"hash"]:o.map}function Lt(t,e){var n=function(t,e){return null==t?void 0:t[e]}(t,e);return function(t){return!(!zt(t)||(e=t,X&&X in e))&&(Gt(t)||H(t)?nt:F).test($t(t));var e}(n)?n:void 0}xt.prototype.clear=function(){this.__data__=yt?yt(null):{}},xt.prototype.delete=function(t){return this.has(t)&&delete this.__data__[t]},xt.prototype.get=function(t){var e=this.__data__;if(yt){var n=e[t];return n===i?void 0:n}return tt.call(e,t)?e[t]:void 0},xt.prototype.has=function(t){var e=this.__data__;return yt?void 0!==e[t]:tt.call(e,t)},xt.prototype.set=function(t,e){return this.__data__[t]=yt&&void 0===e?i:e,this},Rt.prototype.clear=function(){this.__data__=[]},Rt.prototype.delete=function(t){var e=this.__data__,n=Ft(e,t);return!(n<0||(n==e.length-1?e.pop():ut.call(e,n,1),0))},Rt.prototype.get=function(t){var e=this.__data__,n=Ft(e,t);return n<0?void 0:e[n][1]},Rt.prototype.has=function(t){return Ft(this.__data__,t)>-1},Rt.prototype.set=function(t,e){var n=this.__data__,i=Ft(n,t);return i<0?n.push([t,e]):n[i][1]=e,this},St.prototype.clear=function(){this.__data__={hash:new xt,map:new(ft||Rt),string:new xt}},St.prototype.delete=function(t){return Bt(this,t).delete(t)},St.prototype.get=function(t){return Bt(this,t).get(t)},St.prototype.has=function(t){return Bt(this,t).has(t)},St.prototype.set=function(t,e){return Bt(this,t).set(t,e),this},Ot.prototype.clear=function(){this.__data__=new Rt},Ot.prototype.delete=function(t){return this.__data__.delete(t)},Ot.prototype.get=function(t){return this.__data__.get(t)},Ot.prototype.has=function(t){return this.__data__.has(t)},Ot.prototype.set=function(t,e){var n=this.__data__;if(n instanceof Rt){var i=n.__data__;if(!ft||i.length<199)return i.push([t,e]),this;n=this.__data__=new St(i)}return n.set(t,e),this};var Dt=ct?W(ct,Object):function(){return[]},Nt=function(t){return et.call(t)};function Vt(t,e){return!!(e=null==e?o:e)&&("number"==typeof t||_.test(t))&&t>-1&&t%1==0&&t<e}function jt(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||K)}function $t(t){if(null!=t){try{return Q.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Yt(t,e){return t===e||t!=t&&e!=e}(ht&&Nt(new ht(new ArrayBuffer(1)))!=A||ft&&Nt(new ft)!=c||mt&&Nt(mt.resolve())!=h||vt&&Nt(new vt)!=m||gt&&Nt(new gt)!=y)&&(Nt=function(t){var e=et.call(t),n=e==p?t.constructor:void 0,i=n?$t(n):void 0;if(i)switch(i){case bt:return A;case At:return c;case Ct:return h;case wt:return m;case It:return y}return e});var Ht=Array.isArray;function Ut(t){return null!=t&&function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=o}(t.length)&&!Gt(t)}var Wt=dt||function(){return!1};function Gt(t){var e=zt(t)?et.call(t):"";return e==l||e==u}function zt(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}function Jt(t){return Ut(t)?function(t,e){var n=Ht(t)||function(t){return function(t){return function(t){return!!t&&"object"==typeof t}(t)&&Ut(t)}(t)&&tt.call(t,"callee")&&(!lt.call(t,"callee")||et.call(t)==s)}(t)?function(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}(t.length,String):[],i=n.length,o=!!i;for(var r in t)!e&&!tt.call(t,r)||o&&("length"==r||Vt(r,i))||n.push(r);return n}(t):function(t){if(!jt(t))return pt(t);var e=[];for(var n in Object(t))tt.call(t,n)&&"constructor"!=n&&e.push(n);return e}(t)}t.exports=function(t,e){return _t(t,!0,!0,e)}},72:t=>{"use strict";var e=[];function n(t){for(var n=-1,i=0;i<e.length;i++)if(e[i].identifier===t){n=i;break}return n}function i(t,i){for(var s={},r=[],a=0;a<t.length;a++){var l=t[a],u=i.base?l[0]+i.base:l[0],c=s[u]||0,d="".concat(u," ").concat(c);s[u]=c+1;var p=n(d),h={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==p)e[p].references++,e[p].updater(h);else{var f=o(h,i);i.byIndex=a,e.splice(a,0,{identifier:d,updater:f,references:1})}r.push(d)}return r}function o(t,e){var n=e.domAPI(e);return n.update(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap&&e.supports===t.supports&&e.layer===t.layer)return;n.update(t=e)}else n.remove()}}t.exports=function(t,o){var s=i(t=t||[],o=o||{});return function(t){t=t||[];for(var r=0;r<s.length;r++){var a=n(s[r]);e[a].references--}for(var l=i(t,o),u=0;u<s.length;u++){var c=n(s[u]);0===e[c].references&&(e[c].updater(),e.splice(c,1))}s=l}}},659:t=>{"use strict";var e={};t.exports=function(t,n){var i=function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(t){n=null}e[t]=n}return e[t]}(t);if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");i.appendChild(n)}},540:t=>{"use strict";t.exports=function(t){var e=document.createElement("style");return t.setAttributes(e,t.attributes),t.insert(e,t.options),e}},56:(t,e,n)=>{"use strict";t.exports=function(t){var e=n.nc;e&&t.setAttribute("nonce",e)}},825:t=>{"use strict";t.exports=function(t){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=t.insertStyleElement(t);return{update:function(n){!function(t,e,n){var i="";n.supports&&(i+="@supports (".concat(n.supports,") {")),n.media&&(i+="@media ".concat(n.media," {"));var o=void 0!==n.layer;o&&(i+="@layer".concat(n.layer.length>0?" ".concat(n.layer):""," {")),i+=n.css,o&&(i+="}"),n.media&&(i+="}"),n.supports&&(i+="}");var s=n.sourceMap;s&&"undefined"!=typeof btoa&&(i+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),e.styleTagTransform(i,t,e.options)}(e,t,n)},remove:function(){!function(t){if(null===t.parentNode)return!1;t.parentNode.removeChild(t)}(e)}}}},113:t=>{"use strict";t.exports=function(t,e){if(e.styleSheet)e.styleSheet.cssText=t;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(t))}}}},e={};function n(i){var o=e[i];if(void 0!==o)return o.exports;var s=e[i]={id:i,loaded:!1,exports:{}};return t[i].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var i in e)n.o(e,i)&&!n.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),n.nc=void 0;var i={};(()=>{"use strict";n.r(i),n.d(i,{AmbTempValidator:()=>hi,CustomCustomizer:()=>si,CustomDataUploader:()=>ii,CustomStringInput:()=>mi,CustomUploader:()=>oi,DesiredTempValidator:()=>di,HeatCapValidator:()=>fi,InitialTempValidator:()=>pi,ObjectCoolingSelector:()=>vi,OutliersSelection:()=>Xn,PipelineStepEditor:()=>ti,RichFunctionViewEditor:()=>Qn,SimTimeValidator:()=>ci,_package:()=>Kn,init:()=>ri,modelCatalog:()=>li,openModelFromFuncall:()=>Zn,renderRestPanel:()=>ei});const t=grok,e=ui,o=DG,s=rxjs.operators,r=$;var a=n.n(r);const l=()=>document.querySelector(".d4-balloon-container");class u extends o.JsViewer{constructor(){super()}onFrameAttached(t){this.render()}onTableAttached(){this.render()}render(){if(!this.dataFrame||this.dataFrame.rowCount<=0)return void(this.root.innerHTML="");const n=this.dataFrame,i="isOutlier",s="Rationale",r="Count",u="isConfirmed";n.columns.byName(i)||n.columns.add(o.Column.fromBitSet(i,o.BitSet.create(n.rowCount,(()=>!1)))),n.columns.byName(s)||n.columns.add(o.Column.fromStrings(s,Array.from({length:n.rowCount},(()=>""))));const c=()=>o.DataFrame.fromColumns([o.Column.fromStrings(s,[]),o.Column.fromInt32Array(r,new Int32Array([])),o.Column.fromStrings("Actions",[]),o.Column.fromBitSet(u,o.BitSet.create(0,(()=>!1)))]),d=o.Viewer.grid(c());d.root.style.width="100%",d.root.style.minWidth="230px",d.columns.setVisible([s,r,"Actions"]),this.root.append(e.divV([e.divV([d.root],{style:{height:"75%"}})],{style:{height:"100%"}}));const p=()=>{var t,e;if(!d.dataFrame)return;null===(t=n.col(i))||void 0===t||t.markers.assign("true",o.MARKER_TYPE.OUTLIER);const r=null===(e=d.dataFrame)||void 0===e?void 0:e.cell(d.dataFrame.rowCount-1,s).value;n.selection.getSelectedIndexes().forEach((t=>{n.col(i).set(t,!0,!1),n.col(s).set(t,r,!1)})),n.selection.setAll(!1),n.fireValuesChanged(),a()(l()).empty()},h=()=>{d.dataFrame&&(d.dataFrame.rows.removeAt(d.dataFrame.rowCount-1),n.selection.setAll(!1),a()(l()).empty())};d.onCellPrepare((t=>{var o,r,a;t.isTableCell&&("Actions"===t.gridColumn.name&&(t.gridColumn.cellType="html",t.style.element=e.divH([...(null===(o=t.grid.dataFrame)||void 0===o?void 0:o.get(u,t.gridRow))?[(a=null===(r=t.grid.dataFrame)||void 0===r?void 0:r.get(s,t.gridRow),e.div(e.icons.delete((()=>{for(let t=0;t<n.rowCount;t++)n.columns.byName(s).get(t)===a&&(n.columns.byName(s).set(t,"",!1),n.columns.byName(i).set(t,!1,!1));n.fireValuesChanged()}),"Remove the outliers group"),{style:{"text-align":"center",margin:"6px"}}))]:[e.div(e.iconFA("check",p,"Confirm the outliers"),{style:{"text-align":"center",margin:"6px"}}),e.div(e.iconFA("times",h,"Cancel the outliers"),{style:{"text-align":"center",margin:"6px"}})]])))})),d.onCellValueEdited.subscribe((t=>{var e,i;if(!d.dataFrame||t.gridColumn.name!==s)return;if(!d.dataFrame.columns.byName(u).get(t.gridRow))return;const o=new Set;for(let t=0;t<(null===(e=d.dataFrame)||void 0===e?void 0:e.rowCount);t++){const e=null===(i=d.dataFrame)||void 0===i?void 0:i.columns.byName(s).get(t);o.add(e)}for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e);""==i||o.has(i)||n.columns.byName(s).set(e,t.cell.value)}}));const f=()=>{if(n.columns.byName(s))for(let t=0;t<n.rowCount;t++)n.columns.byName(i).get(t)?""===n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"Manual",!1):""!==n.columns.byName(s).get(t)&&n.columns.byName(s).set(t,"",!1);const t={};if(n.columns.byName(s))for(let e=0;e<n.rowCount;e++){const i=n.columns.byName(s).get(e),o=t[i];""!=i&&(o?t[i]++:t[i]=1)}d.dataFrame=c(),d.columns.setVisible([s,r,"Actions"]),Object.keys(t).map((e=>{var n;null===(n=d.dataFrame)||void 0===n||n.rows.addNew([e,t[e],"",!0])}))};n.onDataChanged.subscribe(f),n.onSelectionChanged.subscribe((()=>{if(!d.dataFrame||!n.selection.trueCount)return;const i=l();if(i&&!a()(i).is(":empty")||t.shell.info(e.div([e.divText("Confirm selected points as outliers?"),e.divH([e.bigButton("Confirm",p),e.button("Cancel",h)])])),d.dataFrame.columns.byName(u).toList().some((t=>!1===t)))d.dataFrame.set(r,d.dataFrame.rowCount-1,n.selection.trueCount);else{const t=d.dataFrame.rows.addNew(["Manual",n.selection.trueCount,"",!1]);d.dataFrame.currentCell=d.dataFrame.cell(t.idx,s)}})),n.selection.setAll(!1),f()}}const c=rxjs,d=dayjs;var p=n.n(d);const h=wu;var f=n.n(h);const m={barchart:o.VIEWER.BAR_CHART,boxplot:o.VIEWER.BOX_PLOT,calendar:o.VIEWER.CALENDAR,corrplot:o.VIEWER.CORR_PLOT,densityplot:o.VIEWER.DENSITY_PLOT,filters:o.VIEWER.FILTERS,form:o.VIEWER.FORM,globe:o.VIEWER.GLOBE,googlemap:o.VIEWER.GOOGLE_MAP,grid:o.VIEWER.GRID,heatmap:o.VIEWER.HEAT_MAP,histogram:o.VIEWER.HISTOGRAM,linechart:o.VIEWER.LINE_CHART,markup:o.VIEWER.MARKUP,matrixplot:o.VIEWER.MATRIX_PLOT,networkdiagram:o.VIEWER.NETWORK_DIAGRAM,pcplot:o.VIEWER.PC_PLOT,piechart:o.VIEWER.PIE_CHART,scatterplot:o.VIEWER.SCATTER_PLOT,"3dscatterplot":o.VIEWER.SCATTER_PLOT_3D,shapemap:o.VIEWER.SHAPE_MAP,statistics:o.VIEWER.STATISTICS,tileviewer:o.VIEWER.TILE_VIEWER,timelines:o.VIEWER.TIMELINES,treemap:o.VIEWER.TREE_MAP,trellisplot:o.VIEWER.TRELLIS_PLOT,wordcloud:o.VIEWER.WORD_CLOUD},v="JsCardView",g="viewer",y="restrictedValues",b="editState";var A;!function(t){t.INPUT="Input",t.OUTPUT="Output"}(A||(A={}));const C="experimental",w="Run name",I="RunId";var T,E,x,R;(R=T||(T={})).HIDDEN="hidden",R.VISIBLE="visible",(x=E||(E={})).ENABLED="enabled",x.DISABLED="disabled";const S="ModelStorage",O="Source",P="Is favorite",F="Is complete",_="Delete",k="Author",M="Date",B="Title",L="Desc.",D="Tags";function N(t){return t&&t.root&&t.onInput}function V(t){return(null==t?void 0:t.setValidation)&&N(t)}function j(t){return(null==t?void 0:t.setDisabled)&&(null==t?void 0:t.setRestricted)&&(null==t?void 0:t.setRestrictedUnlocked)&&(null==t?void 0:t.setInconsistent)&&(null==t?void 0:t.setUserInput)&&N(t)}function Y(t){var e;return!(null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.length)&&!(null==t?void 0:t.pending)}function H(t,e){return{description:t,actions:e}}function U(t){if(null==t?void 0:t.errors)return t.errors.map((t=>t.description)).join("; ")}function W(t){var e,n,i;const o=t=>"string"==typeof t?H(t):t;return{errors:null===(e=null==t?void 0:t.errors)||void 0===e?void 0:e.map((t=>o(t))),warnings:null===(n=null==t?void 0:t.warnings)||void 0===n?void 0:n.map((t=>o(t))),notifications:null===(i=null==t?void 0:t.notifications)||void 0===i?void 0:i.map((t=>o(t)))}}function G(...t){var e,n,i,o,s;const r=[],a=[],l=[],u=[];let c={};for(const d of t)d&&(r.push(...null!==(e=d.errors)&&void 0!==e?e:[]),a.push(...null!==(n=d.warnings)&&void 0!==n?n:[]),l.push(...null!==(i=d.notifications)&&void 0!==i?i:[]),u.push(...null!==(o=d.revalidate)&&void 0!==o?o:[]),c=Object.assign(Object.assign({},c),null!==(s=d.context)&&void 0!==s?s:{}));return{errors:r,warnings:a,notifications:l,revalidate:u,context:c}}function z(t,n,i){if(i&&n){for(function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(n,i);i.firstChild&&i.removeChild(i.firstChild););const o=function(t){var n;const i=e.divV([],{style:{gap:"10px"}});for(const o of["errors","warnings","notifications"]){const s=t[o];if(null==s?void 0:s.length)for(const t of s){const s=J(o);s.style.marginRight="4px",i.appendChild(e.divV([e.divH([s,e.span([t.description])]),...(null!==(n=t.actions)&&void 0!==n?n:[]).map((t=>e.link(t.actionName,t.action,void 0,{style:{paddingLeft:"20px"}})))]))}}return i}(t);i.appendChild(o),i.showPopover()}}function J(t){let n;return"errors"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--red-3)"):"warnings"===t?(n=e.iconFA("exclamation-circle"),n.style.color="var(--orange-2)"):"notifications"===t&&(n=e.iconFA("info-circle"),n.style.color="var(--blue-1)"),n&&(n.classList.remove("fal"),n.classList.add("far")),n}var q=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const K=t=>!Z(t)||!t.id,Z=t=>{try{return t.started}catch(t){return null}},X=(e,n)=>{var i,o,s,r,a,l,u;if(n===k)return null!==(o=null===(i=e.author)||void 0===i?void 0:i.friendlyName)&&void 0!==o?o:t.shell.user.friendlyName;const c=null!==(l=null!==(a=null!==(r=null!==(s=e[n])&&void 0!==s?s:e.inputs[n])&&void 0!==r?r:e.outputs[n])&&void 0!==a?a:e.options[n])&&void 0!==l?l:null;return null!==(u=null==c?void 0:c.toString())&&void 0!==u?u:""},Q=t=>t.options.mainParams?JSON.parse(t.options.mainParams):null;function tt(t){const e=t;return e.dart&&o.toJs(e.dart)instanceof o.InputBase}const et=t=>{const e=t.clone();t.options.forEach((n=>e.options[n]=t.options[n]));const n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e},nt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},it=(t,e)=>{t.addRow(["Parameter","Value","Units"]).font={bold:!0},e.forEach((e=>{t.addRow([e.caption,e.value,e.units])})),t.getColumn(1).width=1.2*Math.max(...e.map((t=>t.caption.toString().length)),9),t.getColumn(2).width=1.2*Math.max(...e.map((t=>t.value.toString().length)),5),t.getColumn(3).width=1.2*Math.max(...e.map((t=>t.units.toString().length)),5)};let ot=0;const st=(t,e,n,i)=>{const o=t.getColumn(null!=n?n:1).letter,s={name:`ID_${ot.toString()}`,ref:`${o}${null!=i?i:1}`,columns:e.columns.toList().map((t=>({name:t.name,filterButton:!1}))),rows:new Array(e.rowCount).fill(0).map(((t,n)=>[...e.row(n).cells].map((t=>t.value))))};t.addTable(s),t.columns.forEach((t=>{t.width=25,t.alignment={wrapText:!0}})),ot++},rt=(t,e,n,i,...s)=>q(void 0,[t,e,n,i,...s],void 0,(function*(t,e,n,i,s=0){yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const r=window.html2canvas,a=yield r(n,{logging:!1}),l=a.toDataURL("image/png"),u=t.addImage({base64:l,extension:"png"});e.addImage(u,{tl:{col:i,row:s},ext:{width:a.width,height:a.height}})}));function at(t,e,n){return q(this,void 0,void 0,(function*(){return"file"===t.propertyType&&n.getInput?n.getInput(t.name).value.arrayBuffer():e}))}function lt(t,e){return q(this,void 0,void 0,(function*(){return"file"===t?new File([e],""):e}))}var ut=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ct=t=>{switch(t){case"Today":return"started > -1d";case"Yesterday":return"started > -2d and started < -1d";case"Any time":return"";case"Last year":return"started > -2y and started < -1y";case"This year":return"started > -1y";case"Last month":return"started > -2m and started < -1m";case"This month":return"started > -1m";case"Last week":return"started > -2w and started < -1w";case"This week":return"started > -1w"}};var dt;!function(e){const n={},i=new o.LruCache;function s(e){return ut(this,arguments,void 0,(function*(e,i=!0){var o;const s=e.func.id,r=t.dapi.functions.include("package").allPackageVersions().find(s),a=i&&null!==(o=n[s])&&void 0!==o?o:yield r;n[s]||(n[s]=a),e.func=a}))}e.augmentCallWithFunc=s,e.loadChildRuns=function(e){return ut(this,void 0,void 0,(function*(){const n=yield t.dapi.functions.calls.allPackageVersions().find(e);yield s(n);const i=yield t.dapi.functions.calls.allPackageVersions().include("func").filter(`options.parentCallId="${e}"`).list();return yield Promise.all(i.map((t=>ut(this,void 0,void 0,(function*(){return s(t)}))))),{parentRun:n,childRuns:i}}))},e.loadRun=function(e){return ut(this,arguments,void 0,(function*(e,n=!1){const i=yield t.dapi.functions.calls.allPackageVersions().include("session.user, inputs, outputs").find(e);if(yield s(i),!n){const e=f()(i.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.outputs[t.name]));yield Promise.all(e.map((e=>ut(this,void 0,void 0,(function*(){return i.outputs[e.name]=yield t.dapi.tables.getTable(i.outputs[e.name]),Promise.resolve()})))));const n=f()(i.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!i.inputs[t.name]));yield Promise.all(n.map((e=>ut(this,void 0,void 0,(function*(){return i.inputs[e.name]=yield t.dapi.tables.getTable(i.inputs[e.name]),Promise.resolve()})))))}return i}))},e.saveRun=function(e){return ut(this,void 0,void 0,(function*(){let n=i.get("All users");n||(n=yield t.dapi.groups.find(o.Group.defaultGroupsIds["All users"]),i.set("All users",n));const s=et(e);K(s)&&(s.options.createdOn=p()().unix());const r=f()(s.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.outputs[t.name]));yield Promise.all(r.map((e=>ut(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.outputs[e.name]),yield t.dapi.permissions.grant(s.outputs[e.name].getTableInfo(),n,!1)})))));const a=f()(s.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!s.inputs[t.name]));return yield Promise.all(a.map((e=>ut(this,void 0,void 0,(function*(){yield t.dapi.tables.uploadDataFrame(s.inputs[e.name]),yield t.dapi.permissions.grant(s.inputs[e.name].getTableInfo(),n,!1)}))))),yield t.dapi.functions.calls.allPackageVersions().save(s)}))},e.deleteRun=function(e){return ut(this,void 0,void 0,(function*(){e.options.isDeleted=!0,yield t.dapi.functions.calls.allPackageVersions().save(e)}))},e.pullRuns=function(e){return ut(this,arguments,void 0,(function*(e,n={},i={}){let o=`func.id="${e}"`;return o+=n.author?` and session.user.id="${n.author.id}"`:"",o+=n.date?ct(n.date):"",t.dapi.functions.calls.allPackageVersions().filter(o).include("session.user, options").list(i)}))},e.pullRunsByName=function(e){return ut(this,arguments,void 0,(function*(e,n=[],i={},r=[],a=!1){let l="";for(const t of n){const e=[];t.author&&e.push(`session.user.id="${t.author.id}"`),t.date&&e.push(ct(t.date)),t.text&&e.push(`((options.title like "${t.text}") or (options.annotation like "${t.text}"))`),t.includeDeleted||e.push('((options.isDeleted != "true") or (options.isDeleted = null))');const n=e.join(" and ");""!==n&&(l+=""===l?`(${n})`:` or (${n})`)}""!==l&&(l=` and (${l})`);const u=yield t.dapi.functions.calls.allPackageVersions().filter(`func.name="${e}"${l}`).include(`${r.join(",")}`).list(i);for(const t of u)yield s(t);if((r.includes("inputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.inputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.inputs[t.name]));for(const i of n)e.inputs[i.name]=yield t.dapi.tables.getTable(e.inputs[i.name])}if((r.includes("outputs")||r.includes("func.params"))&&!a)for(const e of u){const n=f()(e.outputParams.values()).filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&!!e.outputs[t.name]));for(const i of n)e.outputs[i.name]=yield t.dapi.tables.getTable(e.outputs[i.name])}return u}))}}(dt||(dt={}));var pt=n(72),ht=n.n(pt),ft=n(825),mt=n.n(ft),vt=n(659),gt=n.n(vt),yt=n(56),bt=n.n(yt),At=n(540),Ct=n.n(At),wt=n(113),It=n.n(wt),Tt=n(911),Et={};Et.styleTagTransform=It(),Et.setAttributes=bt(),Et.insert=gt().bind(null,"head"),Et.domAPI=mt(),Et.insertStyleElement=Ct(),ht()(Tt.A,Et),Tt.A&&Tt.A.locals&&Tt.A.locals;var xt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Rt="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";class St extends o.InputBase{get value(){return this.fileValue}set value(t){this.stringValue=(null==t?void 0:t.name)||"Drag-n-drop your file",this.fileValue=t,this.notify&&this.fireInput()}constructor(t="Drag-n-drop here",n=null,i=null,o=Rt){super(e.stringInput("Input file","",null).dart),this.initialText=t,this.initialValue=n,this.onValueChanged=i,this.fileType=o,this.uploadedFile$=new c.Subject,this.onFileUploaded=this.uploadedFile$,this.fileValue=null,this.isValid=new c.BehaviorSubject(!0),this.hiddenInput=document.createElement("input"),this.icon=e.iconFA("cloud-upload",(()=>this.hiddenInput.click())),this.subscribeOnEvents(),this.root.style.display="flex",this.isValid.subscribe((t=>{if(t){this.input.classList.remove("error"),this.input.classList.add("success");const t=e.iconFA("times",(()=>this.reset()),"Reset uploaded file");this.icon.replaceWith(t),this.icon=t}else{this.input.classList.remove("success"),this.input.classList.add("error");const t=e.iconFA("redo",(()=>this.hiddenInput.click()),"Re-upload a file");this.icon.replaceWith(t),this.icon=t}})),this.uploadedFile$.subscribe((t=>{if(this.onValueChanged&&this.onValueChanged(t),!t){const t=e.iconFA("cloud-upload",(()=>this.hiddenInput.click()),"Choose a file to upload");this.icon.replaceWith(t),this.icon=t}this.value=t})),this.reset()}subscribeOnEvents(){this.input.readOnly=!0,this.input.classList.add("default");const t=t=>xt(this,void 0,void 0,(function*(){if(t&&t.length&&this.enabled){if(t.length>1)throw this.isValid.next(!1),new Error("Please specify single input file");if(this.fileType&&t[0].type!==this.fileType)throw this.isValid.next(!1),new Error("File type is not supported");this.isValid.value?this.uploadedFile$.next(t[0]):this.uploadedFile$.next(null)}}));this.root.classList.add("fi-drop-area"),this.root.style.width="100%",this.hiddenInput.type="file",this.hiddenInput.addEventListener("change",(()=>xt(this,void 0,void 0,(function*(){return yield t(this.hiddenInput.files)}))),!1),["dragenter","dragover","dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(t=>{t.preventDefault(),t.stopPropagation()}),!1)})),["dragenter","dragover"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.add("drag-n-dropping")}),!1)})),["dragleave","drop"].forEach((t=>{this.input.addEventListener(t,(()=>{this.input.classList.remove("drag-n-dropping")}),!1)})),this.input.addEventListener("drop",(e=>xt(this,void 0,void 0,(function*(){const n=e.dataTransfer.files;t(n)}))),!1),this.input.addEventListener("click",(()=>this.hiddenInput.click()),!1),this.addOptions(this.icon),["drag","dragenter"].forEach((t=>{document.getElementsByClassName("layout-workarea")[0].addEventListener(t,(t=>{t.stopPropagation()}),!1)}))}reset(){this.input.classList.value="ui-input-editor default",this.hiddenInput.value="",this.uploadedFile$.next(null)}}var Ot=n(703),Pt={};Pt.styleTagTransform=It(),Pt.setAttributes=bt(),Pt.insert=gt().bind(null,"head"),Pt.domAPI=mt(),Pt.insertStyleElement=Ct(),ht()(Ot.A,Pt),Ot.A&&Ot.A.locals&&Ot.A.locals;var Ft=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class _t extends o.Dialog{constructor(n,i){var s,r,a;super(e.dialog({title:"Edit run metadata"}).dart),this._onMetadataEdit=new c.Subject,this.onMetadataEdit=this._onMetadataEdit.asObservable();let l=null!==(s=n.options.title)&&void 0!==s?s:"",u=null!==(r=n.options.description)&&void 0!==r?r:"",d=i;const p=e.stringInput("Title",l,(t=>l=t)),h=e.stringInput(" ",""),f=o.TagEditor.create();(null!==(a=n.options.tags)&&void 0!==a?a:[]).forEach((t=>{f.addTag(t)})),h.input.replaceWith(f.root);const m=()=>{""===v.value||f.tags.includes(v.value)||(f.addTag(v.value),v.value="")},v=e.stringInput("Tag","").addOptions(e.iconFA("plus",m,"Add this tag")),g=(0,c.fromEvent)(v.input,"onkeydown").subscribe((t=>{"Enter"==t.key&&(t.stopPropagation(),m())}));this.sub(g),this.add(e.form([p,e.stringInput("Description",u,(t=>u=t)),e.boolInput("Favorites",d,(t=>d=t)),v,h])),this.addButton("Save",(()=>Ft(this,void 0,void 0,(function*(){if(""!==v.value)return void t.shell.info(`Dialog has unsaved tags: ${v.value}`);let e="same";d&&!i&&(e="favorited"),!d&&i&&(e="unfavorited");const n={title:""!==l?l:null,description:""!==u?u:null,tags:f.tags.map((t=>t)),favorite:e};this._onMetadataEdit.next(n),this.close()}))))}}class kt extends o.Dialog{constructor(t){super(e.dialog({title:`Delete ${t.size>1?t.size:""} ${t.size>1?"runs":"run"}`}).dart),this._onFuncCallDelete=new c.Subject,this.onFuncCallDelete=this._onFuncCallDelete.asObservable(),this.add(e.divText(`Deleted ${t.size>1?t.size:""} ${t.size>1?"runs":"run"} ${t.size>1?"are":"is"} impossible to restore. Are you sure?`)),this.onOK((()=>Ft(this,void 0,void 0,(function*(){return this._onFuncCallDelete.next(t)}))))}}var Mt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Bt=t=>{var e,n;if(null===(e=t.options)||void 0===e?void 0:e.default)return JSON.parse(null===(n=t.options)||void 0===n?void 0:n.default);const i=t.defaultValue;return t.propertyType===o.TYPE.STRING&&i?i.substring(1,i.length-1):i};function Lt(t,n){n?(a()(t).addClass("ui-box").css({width:"auto",height:"auto"}),e.setUpdateIndicator(t,!0)):(e.setUpdateIndicator(t,!1),a()(t).removeClass("ui-box"))}const Dt=t=>{const e=t.options[g];return void 0!==e?{name:t.name,config:JSON.parse(e,((t,e)=>{if("true"===e)return!0;if("false"===e)return!1;if("type"===t)return m[e]||e;if(!t.toLowerCase().includes("color")){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}return e}))}:{name:t.name,config:[]}},Nt=t=>{try{return t.started.toDate().toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}catch(t){return"Not completed"}};var Vt=n(826),jt=n.n(Vt),$t=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};p().extend(jt());const Yt=Object.values(o.COLUMN_TYPE).filter((t=>t!==o.TYPE.DATA_FRAME)),Ht=t=>t.replace(/([A-Z])/g,(t=>` ${t.toLowerCase()}`)).trim().replace(/^./,(t=>t.toUpperCase())),Ut=new o.LruCache;class Wt extends o.Widget{storageName(t){return`${S}_${[...t.values()][0].func.name}_Fav`}get onRunsDfChanged(){return this._onRunsDfChanged.asObservable()}get onChosen(){return this._onChosen.asObservable()}get chosen(){return this._onChosen.value}set chosen(t){var e;this.chosenById=null!==(e=null==t?void 0:t.id)&&void 0!==e?e:null}set chosenById(t){if(t){for(let e=0;e<this.currentDf.rowCount;e++)if(this.currentDf.getCol(Jt).get(e)===t){this.currentDf.currentRowIdx=e;break}}else this.currentDf.currentRowIdx=-1}get selected(){return this._onSelectedChanged.value}get runs(){return this.onRunsChanged.value}get onSelectedChanged(){return this._onSelectedChanged.asObservable()}saveIsFavorite(e,n){return $t(this,void 0,void 0,(function*(){const i=`${S}_${e.func.name}_Fav`;return n?t.dapi.userDataStorage.postValue(i,e.id,""):t.dapi.userDataStorage.remove(i,e.id)}))}getRunByIdx(t){return this.runs.get(this.currentDf.get(Jt,t))}showEditDialog(e,n){const i=new _t(e,n),o=i.onMetadataEdit.subscribe((n=>$t(this,void 0,void 0,(function*(){var i;if(null===(i=this.options)||void 0===i?void 0:i.isHistory)return("same"!==n.favorite?this.saveIsFavorite(e,"favorited"===n.favorite):Promise.resolve()).then((()=>dt.loadRun(e.id,!1))).then((t=>(n.title&&(t.options.title=n.title),n.description&&(t.options.description=n.description),n.tags&&(t.options.tags=n.tags),[dt.saveRun(t),t]))).then((([,t])=>{this.updateRun(t),this.onMetadataEdit.next(t),o.unsubscribe()})).catch((e=>{t.shell.error(e)}));this.updateRun(e)}))));i.show({center:!0,width:500})}visibleProps(t){var e,n,i;return null!==(i=null!==(n=null===(e=this.options)||void 0===e?void 0:e.visibleProps)&&void 0!==n?n:Q(t))&&void 0!==i?i:t.inputs.filter((t=>Yt.includes(t.propertyType))).map((t=>t.name))}constructor(n,i){var s,r,l,u,d,h,m;super(e.div([],{style:{height:"100%",width:"100%"}})),this.initialRuns=n,this.options=i,this.onRunsChanged=new c.BehaviorSubject(this.initialRuns.reduce(((t,e)=>(t.set(e.id,e),t)),new Map)),this._onRunsDfChanged=new c.BehaviorSubject(o.DataFrame.fromColumns([o.Column.bool(O,0),...(null===(s=this.options)||void 0===s?void 0:s.isHistory)?[o.Column.bool(P,0)]:[],...(null===(r=this.options)||void 0===r?void 0:r.showActions)?[o.Column.string(_,0)]:[],o.Column.bool(F,0),o.Column.dateTime(M,0),o.Column.string(k,0),o.Column.string(D,0),o.Column.string(B,0),o.Column.string(L,0),o.Column.fromStrings(Jt,[])])),this._historyFilters=o.Viewer.filters(this._onRunsDfChanged.value,{title:"Filters",columnNames:[]}),this._historyGrid=o.Viewer.grid(this._onRunsDfChanged.value,{showRowHeader:!1,showColumnGridlines:!1,allowEdit:!1}),this.onComparisonCalled=new c.Subject,this.onMetadataEdit=new c.Subject,this._onChosen=new c.BehaviorSubject(null),this.onDelete=new c.Subject,this._onSelectedChanged=new c.BehaviorSubject(new Set([])),this.layout=e.splitH([],null,!0),this.defaultGridText=e.divText(null!==(u=null===(l=this.options)||void 0===l?void 0:l.fallbackText)&&void 0!==u?u:"No historical runs found","hp-no-elements-label"),this.defaultFiltersText=e.divText("No filters to show","hp-no-elements-label"),this.filterWithText=e.divH([this.defaultFiltersText,this._historyFilters.root],"ui-box"),this.trashIcon=e.div(e.iconFA("trash-alt",(()=>{const t=this.currentDf.selection.getSelectedIndexes(),e=new Set;t.forEach((t=>e.add(this.getRunByIdx(t))));const n=new kt(e),i=n.onFuncCallDelete.subscribe((t=>$t(this,void 0,void 0,(function*(){yield Promise.all(f()(t.values()).map((t=>$t(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()}))))),i.unsubscribe()}))));n.show({center:!0,width:500,modal:!0})}),"Delete selected runs"),{style:{"padding-top":"5px"}}),this.compareIcon=e.div(e.iconFA("exchange",(()=>$t(this,void 0,void 0,(function*(){const t=this.currentDf.selection.getSelectedIndexes(),e=[];t.forEach((t=>{e.push(this.currentDf.getCol(Jt).get(t))})),this.onComparisonCalled.next(e)}))),"Compare selected runs"),{style:{"padding-top":"5px"}}),this._isFilterHidden=new c.BehaviorSubject(!1),this.showFiltersIcon=e.div(e.iconFA("filter",(()=>{this._isFilterHidden.next(!this._isFilterHidden.value)}),"Toggle filters"),{style:{"padding-top":"4px"}}),this._compactMode=new c.BehaviorSubject(null!==(h=null===(d=this.options)||void 0===d?void 0:d.isHistory)&&void 0!==h&&h),this.toggleCompactMode=e.div(e.iconFA("expand-alt",(()=>{this.compactMode=!this.compactMode}),"Toggle compact mode"),{style:{"padding-top":"4px"}}),this.showMetadataIcon=e.switchInput("Metadata",!0,(()=>{this.styleHistoryGrid(),this.styleHistoryFilters()})),this.showInputsIcon=e.switchInput("Params",!1,(t=>$t(this,void 0,void 0,(function*(){var e;0!==this.runs.size&&(t&&(null===(e=this.options)||void 0===e?void 0:e.isHistory)?((yield Promise.all([...this.runs.values()].map((t=>$t(this,void 0,void 0,(function*(){if(Ut.has(t.id))return Ut.get(t.id);{const e=yield dt.loadRun(t.id,!0);return Ut.set(e.id,e),e}})))))).forEach((t=>{this.runs.set(t.id,t)})),this.onRunsChanged.next(this.runs)):(this.styleHistoryGrid(),this.styleHistoryFilters()))}))));const v=e.divH([e.divH([...(null==i?void 0:i.isHistory)?[this.toggleCompactMode]:[],this.showFiltersIcon,this.showMetadataIcon.root,this.showInputsIcon.root],{style:{gap:"5px",padding:"5px"}}),e.divH((null===(m=this.options)||void 0===m?void 0:m.showBatchActions)?[this.trashIcon,this.compareIcon]:[],{style:{gap:"5px",padding:"5px"}})],{style:{"justify-content":"space-between",padding:"0px 5px"}});v.style.setProperty("overflow-y","hidden","important");const g=e.divV([this.defaultGridText,v,this._historyGrid.root],"ui-box");a()(g).removeClass("ui-div"),a()(g).css("width","100%"),this.root.appendChild(this.layout),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1),this.setGridCellRendering();const y=this.onRunsChanged.subscribe((n=>$t(this,void 0,void 0,(function*(){var i,s,r;const a=[...n.values()],l=t=>{var e,n;return t.propertyType===o.TYPE.DATE_TIME?o.Column.dateTime(null!==(e=t.caption)&&void 0!==e?e:Ht(t.name),a.length).init((e=>window.grok_DayJs_To_DateTime(a[e].inputs[t.name]))):o.Column.fromType(t.propertyType,null!==(n=t.caption)&&void 0!==n?n:Ht(t.name),a.length).init((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t.name])||void 0===o?void 0:o.call(i,a[e]))&&void 0!==s?s:X(a[e],t.name)}))},u=t=>t===M?o.Column.dateTime(Ht(t),a.length).init((t=>window.grok_DayJs_To_DateTime(Z(a[t])?a[t].started.utc(!0):p().unix(a[t].options.createdOn)))):t===F?o.Column.bool(Ht(t),a.length).init((t=>Z(a[t]))):o.Column.fromStrings(Ht(t),a.map((e=>{var n,i,o,s;return null!==(s=null===(o=null===(i=null===(n=this.options)||void 0===n?void 0:n.propFuncs)||void 0===i?void 0:i[t])||void 0===o?void 0:o.call(i,e))&&void 0!==s?s:X(e,t)})));if(n.size>0){const c=null!==(i=yield t.dapi.userDataStorage.get(this.storageName(n)))&&void 0!==i?i:{},d=Object.keys(c),p=[...this.runs.values()][0].func,h=t=>{var e;const n=null!==(e=p.inputs.find((e=>e.name===t)))&&void 0!==e?e:p.outputs.find((e=>e.name===t));return n?l(n):u(t)},f=o.DataFrame.fromColumns([o.Column.string(O,a.length).init((t=>{const e=a[t].options.immutable_tags;return e&&e.includes(C)?"Experimental":"Simulated"})),...(null===(s=this.options)||void 0===s?void 0:s.isHistory)?[o.Column.bool(P,a.length).init((t=>d.includes(a[t].id)))]:[],...(null===(r=this.options)||void 0===r?void 0:r.showActions)?[o.Column.string(_,a.length).init("")]:[],u(M),u(F),u(k),o.Column.string(D,a.length).init((t=>a[t].options.tags?a[t].options.tags.join(","):"")),o.Column.string(B,a.length).init((t=>a[t].options.title)),o.Column.string(L,a.length).init((t=>a[t].options.description))]);this.visibleProps(p).map((t=>h(t))).forEach((t=>{t.name=f.columns.getUnusedName(t.name),f.columns.add(t,!1)})),f.columns.add(o.Column.fromStrings(Jt,a.map((t=>t.id)))),e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!1),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.toggleCompactMode,this.showMetadataIcon.root,this.trashIcon,this.compareIcon,this.showFiltersIcon],!0),e.setDisplay(this.showInputsIcon.root,this.visibleProps(p).length>0),this._onRunsDfChanged.next(f)}else e.setDisplayAll([this.defaultGridText,this.defaultFiltersText],!0),e.setDisplayAll([this._historyGrid.root,this._historyFilters.root,this.showMetadataIcon.root,this.showInputsIcon.root,this.toggleCompactMode,this.trashIcon,this.compareIcon,this.showFiltersIcon],!1)})))),b=this._onRunsDfChanged.subscribe((t=>{this._historyFilters.dataFrame=t,this._historyGrid.dataFrame=t,this.currentDf.getCol(D).setTag(o.TAGS.MULTI_VALUE_SEPARATOR,","),this.styleHistoryGrid(),this.styleHistoryFilters();const e=t.onCurrentRowChanged.subscribe((()=>{var t;this.currentDf.rows.select((()=>!1)),this._onChosen.next(null!==(t=this.getRunByIdx(this.currentDf.currentRowIdx))&&void 0!==t?t:null)})),n=t.onSelectionChanged.subscribe((()=>{const e=[...t.selection.getSelectedIndexes()].map((t=>this.getRunByIdx(t)));this._onSelectedChanged.next(new Set(e)),this.redrawSelectionState()}));this.redrawSelectionState(),this.subs.push(e,n)})),A=this._isFilterHidden.subscribe((t=>{t?(a()(this.showFiltersIcon.firstChild).addClass("fal"),a()(this.showFiltersIcon.firstChild).removeClass("fad"),e.setDisplay(this.filterWithText,!1)):(a()(this.showFiltersIcon.firstChild).addClass("fad"),a()(this.showFiltersIcon.firstChild).removeClass("fal"),a()(this.filterWithText).css(this.compactMode?"height":"width","320px"),a()(this.filterWithText).css(this.compactMode?"width":"height","100%"),e.setDisplay(this.filterWithText,!0))})),w=this._compactMode.subscribe((t=>{const n=[g,this.filterWithText];a()(this.filterWithText).removeClass("ui-div");const i={style:{width:"100%",height:"100%"}};a()(this.toggleCompactMode.firstChild).addClass(t?"fa-expand-alt":"fa-compress-alt"),a()(this.toggleCompactMode.firstChild).removeClass(t?"fa-compress-alt":"fa-expand-alt");const o=t?e.splitV(n,i,!0):e.splitH(n,i,!0);this.layout.replaceWith(o),this.layout=o,e.tools.waitForElementInDom(this.layout).then((t=>{a()(t).css(this.compactMode?"height":"width","100%"),a()(this._historyFilters.root).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),a()(this.filterWithText).css(Object.assign({},this.compactMode?{height:"310px",width:"100%"}:{width:"310px",height:"100%"})),a()(g).css(Object.assign({},this.compactMode?{width:"100%"}:{height:"100%"})),setTimeout((()=>{this.styleHistoryGrid(),this.styleHistoryFilters()}),100)}))}));this.subs.push(y,w,b,A)}setGridColumnsRendering(){const t=this._historyGrid.columns.byName(_);t&&(t.cellType="html",t.width=35);const e=this._historyGrid.columns.byName(P);e&&(e.cellType="html",e.width=20);const n=this._historyGrid.columns.byName(O);n.cellType="html",n.width=20;const i=this._historyGrid.columns.byName(D);i.cellType="html",i.width=90,this._historyGrid.columns.byName(M).width=110,this._historyGrid.columns.byName(Jt).cellType="html"}isFavoriteByIndex(t){return this.currentDf.get(P,t)}setGridCellRendering(){this._historyGrid.onCellPrepare((n=>{var i,o,s,r,l,u,c,d,p,h,m;if(n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.name)&&[_,O,P].includes(n.tableColumn.name)&&(n.customText=""),!n.isColHeader){if((null===(o=n.tableColumn)||void 0===o?void 0:o.name)===_){n.customText="";const t=this.getRunByIdx(n.tableRowIndex);n.element=e.divH([e.iconFA("trash",(()=>{const t=new Set([this.getRunByIdx(n.tableRowIndex)]),e=new kt(t),i=e.onFuncCallDelete.subscribe((()=>$t(this,void 0,void 0,(function*(){yield Promise.all(f()(t.values()).map((t=>$t(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()}))))),i.unsubscribe()}))));e.show({center:!0,width:500})}),"Remove run from history"),e.iconFA("edit",(()=>this.showEditDialog(t,this.isFavoriteByIndex(n.tableRowIndex))),"Edit run metadata")],{style:{padding:"6px 0px",gap:"6px","justify-content":"space-between"}})}if((null===(s=n.tableColumn)||void 0===s?void 0:s.name)===P){n.customText="";const t=this.getRunByIdx(n.tableRowIndex),i=e.iconFA("star",(()=>this.saveIsFavorite(t,!1).then((()=>this.updateRun(t)))),"Unfavorite");a()(i).addClass("fas"),n.element=e.div(n.cell.value?i:e.iconFA("star",(()=>this.saveIsFavorite(t,!0).then((()=>this.updateRun(t)))),"Favorite"),{style:{padding:"5px 0px"}})}if((null===(r=n.tableColumn)||void 0===r?void 0:r.name)===O){n.customText="";const t=e.iconFA("flask",null,"Experimental run");a()(t).addClass("fad fa-sm"),a()(t).removeClass("fal"),n.element=n.cell.value&&"Experimental"===n.cell.value?e.div(t,{style:{padding:"5px"}}):e.div()}if((null===(l=n.tableColumn)||void 0===l?void 0:l.name)===D){n.customText="";const t=n.cell.value.length>0?e.div(null===(u=n.cell.value)||void 0===u?void 0:u.split(",").map((t=>e.span([t],"d4-tag"))),"d4-tag-editor"):e.div();a()(t).css({padding:"3px","background-color":"transparent"}),n.element=t}if((null===(c=n.tableColumn)||void 0===c?void 0:c.name)===Jt){n.customText="";const i=this.getRunByIdx(n.tableRowIndex);if(!i)return;const o=i.author.picture;a()(o).css({width:"25px",height:"25px",fontSize:"20px"}),e.bind(i.author,o);const s=e.iconFA("flask",null,"Experimental run");s.classList.add("fad","fa-sm"),s.classList.remove("fal"),s.style.marginLeft="3px";const r=i.options.immutable_tags,l=e.span([e.label(null!==(h=null!==(d=i.options.title)&&void 0!==d?d:null===(p=i.author)||void 0===p?void 0:p.friendlyName)&&void 0!==h?h:t.shell.user.friendlyName,{style:{color:"var(--blue-1)"}}),...r&&r.includes(C)?[s]:[]]),u=e.iconFA("edit",(t=>{t.stopPropagation(),this.showEditDialog(i,this.isFavoriteByIndex(n.tableRowIndex))}),"Edit run metadata");u.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const c=e.iconFA("trash-alt",(t=>$t(this,void 0,void 0,(function*(){t.stopPropagation();const e=new Set([this.getRunByIdx(n.tableRowIndex)]),i=new kt(e),o=i.onFuncCallDelete.subscribe((()=>$t(this,void 0,void 0,(function*(){yield Promise.all(f()(e.values()).map((t=>$t(this,void 0,void 0,(function*(){return yield this.deleteRun(t.id),Promise.resolve()}))))),o.unsubscribe()}))));i.show({center:!0,width:500})}))),"Delete run");c.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon");const v=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!1).then((()=>this.updateRun(i)))}),"Unfavorite");v.classList.add("fas","hp-funccall-card-icon");const g=e.iconFA("star",(t=>{t.stopPropagation(),this.saveIsFavorite(i,!0).then((()=>this.updateRun(i)))}),"Favorite");g.classList.add("hp-funccall-card-icon","hp-funccall-card-hover-icon"),this.isFavoriteByIndex(n.tableRowIndex)?(e.setDisplay(g,!1),e.setDisplay(v,!0)):(e.setDisplay(v,!1),e.setDisplay(g,!0));const y=Nt(i),b=e.divH([e.divH([o,e.divV([l,e.span([y]),...i.options.tags&&i.options.tags.length>0?[e.div(i.options.tags.map((t=>e.span([t],"d4-tag"))))]:[]],"hp-card-content")]),e.divH([...(null===(m=this.options)||void 0===m?void 0:m.showActions)?[v,g,u,c]:[]])],"hp-funccall-card"),A=n.tableRowIndex;b.addEventListener("mouseover",(()=>{n.grid.dataFrame.mouseOverRowIdx=A})),b.addEventListener("click",(t=>{t.shiftKey?n.grid.dataFrame.selection.set(A,!0):t.ctrlKey?n.grid.dataFrame.selection.set(A,!1):n.grid.dataFrame.currentRowIdx=A})),n.element=b}}}))}deleteRun(e){return $t(this,void 0,void 0,(function*(){return dt.loadRun(e,!0).then((t=>{var e;return[(null===(e=this.options)||void 0===e?void 0:e.isHistory)?dt.deleteRun(t):Promise.resolve(),t]})).then((([,t])=>{var n;return this.runs.delete(e),this.onRunsChanged.next(this.runs),(null===(n=this.options)||void 0===n?void 0:n.isHistory)&&this.onDelete.next(t),t})).then((t=>{this.saveIsFavorite(t,!1)})).catch((e=>{t.shell.error(e)}))}))}editRun(t){this.showEditDialog(t,!1)}updateRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}addRun(t){this.runs.set(t.id,t),this.onRunsChanged.next(this.onRunsChanged.value)}updateRuns(t){this.onRunsChanged.next(t.reduce(((t,e)=>(t.set(e.id,e),t)),new Map))}get isFilterHidden(){return this._isFilterHidden.value}set isFilterHidden(t){this._isFilterHidden.next(t)}get compactMode(){return this._compactMode.value}set compactMode(t){this._compactMode.next(t)}get onCompactModeChanged(){return this._compactMode.asObservable()}styleHistoryGrid(){var t;this._historyGrid.setOptions({showCurrentRowIndicator:!0,showCurrentCellOutline:!1,allowEdit:!1,allowBlockSelection:!1,showRowHeader:!1,showColumnLabels:!this.compactMode,extendLastColumn:this.compactMode}),this._historyGrid.sort([M],[!1]);for(let e=0;e<this._historyGrid.columns.length;e++){const n=this._historyGrid.columns.byIndex(e);n&&(null===(t=n.column)||void 0===t?void 0:t.type)===o.TYPE.DATE_TIME&&(n.format="MMM d, h:mm tt")}if(this.setGridColumnsRendering(),0!==this.runs.size)if(this.compactMode)this._historyGrid.columns.setVisible([Jt]),this._historyGrid.props.rowHeight=70,this._historyGrid.invalidate();else{this._historyGrid.props.rowHeight=28;const t=[...this.runs.values()][0].func,e=this.showMetadataIcon.value,n=this.currentDf.getCol(D);this._historyGrid.columns.setVisible([O,P,_,...e?[M]:[],...e?[k]:[],...e&&n.stats.missingValueCount<n.length?[D]:[],...e?[B]:[],...e?[L]:[],...this.showInputsIcon.value?this.visibleProps(t).map((e=>{var n,i;const o=null!==(n=t.inputs.find((t=>t.name===e)))&&void 0!==n?n:t.outputs.find((t=>t.name===e));return o?null!==(i=o.caption)&&void 0!==i?i:Ht(o.name):Ht(e)})):[]])}}get currentDf(){return this._onRunsDfChanged.value}styleHistoryFilters(){var t,n;if(this.runs.size>0){const i=[...this.runs.values()][0].func,o=this.currentDf.getCol(D),s=this.showMetadataIcon.value,r=[...s&&this.currentDf.getCol(O).categories.length>1?[O]:[],...s&&(null!==(n=null===(t=this.currentDf.col(P))||void 0===t?void 0:t.categories.length)&&void 0!==n?n:0)>1?[P]:[],...s?[M,F]:[],...s&&this.currentDf.getCol(k).categories.length>1?[k]:[],...s&&o.stats.missingValueCount<o.length?[D]:[],...s&&this.currentDf.getCol(B).categories.length>1?[B]:[],...s&&this.currentDf.getCol(L).categories.length>1?[L]:[],...this.showInputsIcon.value?this.visibleProps(i).map((t=>{var e,n;const o=null!==(e=i.inputs.find((e=>e.name===t)))&&void 0!==e?e:i.outputs.find((e=>e.name===t));return o?null!==(n=o.caption)&&void 0!==n?n:Ht(o.name):Ht(t)})).filter((t=>{var e;return!(null===(e=this.options)||void 0===e?void 0:e.isHistory)||this.currentDf.getCol(t).categories.length>1})).map((t=>t)):[]];r.length>0?(a()(this.filterWithText).css({paddingTop:"10px"}),e.setDisplay(this.defaultFiltersText,!1),e.setDisplay(this._historyFilters.root,!0),this._historyFilters.setOptions({columnNames:r,showHeader:!1,showBoolCombinedFitler:!1})):(e.setDisplay(this.defaultFiltersText,!0),e.setDisplay(this._historyFilters.root,!1))}}redrawSelectionState(){const t=this.currentDf.selection.trueCount;t<2?this.compareIcon.firstChild.classList.add("hp-disabled"):this.compareIcon.firstChild.classList.remove("hp-disabled"),0===t?this.trashIcon.firstChild.classList.add("hp-disabled"):this.trashIcon.firstChild.classList.remove("hp-disabled")}}var Gt=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};class zt{static getHistoryRuns(e){return(0,c.from)((()=>Gt(this,void 0,void 0,(function*(){return yield dt.pullRunsByName(e,[{author:t.shell.user}],{order:"started"},["func.params","session.user","options"],!0)})))())}}const Jt="ID";class qt extends o.InputBase{constructor(t,n,i){var o,r;const a=e.stringInput(t,"",null);super(a.dart),this.label=t,this._funcName=n,this.options=i,this.onHistoricalRunChosen=new c.BehaviorSubject(null),this.experimentRunsUpdate=new c.Subject,this.store={experimentRuns:new c.Observable,isExperimentRunsLoading:new c.Subject,experimentRunData:new c.BehaviorSubject("")},this._historyList=new Wt([],{fallbackText:"No runs are found in history",showActions:!1,showBatchActions:!1,isHistory:!1,visibleProps:null===(o=this.options)||void 0===o?void 0:o.mainProps,propFuncs:null===(r=this.options)||void 0===r?void 0:r.propFuncs}),this._historyDialog=this.getHistoryDialog(),this._visibleInput=e.stringInput(this.label,"",null),this._visibleIcon=e.iconFA("search",(()=>this.showSelectionDialog())),this._chosenRun=null,this._chosenRunId=null,this._visibleInput=a,this._visibleInput.readOnly=!0,this._visibleInput.input.addEventListener("click",(()=>this.showSelectionDialog())),this._visibleInput.addOptions(this._visibleIcon),this.store.experimentRuns=this.experimentRunsUpdate.pipe((0,s.tap)((()=>this.toggleLoaderExpRuns(!0))),(0,s.switchMap)((()=>zt.getHistoryRuns(this._funcName).pipe((0,s.catchError)((t=>(console.error(t),c.EMPTY))),(0,s.finalize)((()=>this.toggleLoaderExpRuns(!1)))))),(0,s.shareReplay)(1)),this.store.experimentRuns.subscribe((t=>{this._historyList.updateRuns(t.filter((t=>!K(t))))})),this.store.isExperimentRunsLoading.subscribe((t=>{e.setUpdateIndicator(this._visibleInput.root,t),e.setUpdateIndicator(this._historyList.root,t)})),this.experimentRunsUpdate.next()}setCurrentRow(){this.getValue()?this._historyList.chosen=this.getValue():this.chosenRunId&&(this._historyList.chosenById=this.chosenRunId)}showSelectionDialog(){this.renderGridAndFilters(),this._historyDialog.getButton("OK").disabled=1!==this._historyList.selected.size,this._historyDialog.show({modal:!0,fullScreen:!0,center:!0,width:window.innerWidth-50,height:window.innerHeight-50})}renderGridAndFilters(){var t,e;const n=new Wt([...this._historyList.runs.values()],Object.assign(Object.assign({},this.options),{visibleProps:null===(t=this.options)||void 0===t?void 0:t.mainProps,propFuncs:null===(e=this.options)||void 0===e?void 0:e.propFuncs}));this._historyList.root.replaceWith(n.root),this._historyList=n,this._historyList.onChosen.subscribe((t=>{this._historyDialog.getButton("OK").disabled=!t})),this._historyList.onRunsDfChanged.pipe((0,s.filter)((t=>t.rowCount>0)),(0,s.take)(1)).subscribe((t=>{this.setCurrentRow()}))}getHistoryDialog(){const t=e.dialog();return a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form"),t.onOK((()=>Gt(this,void 0,void 0,(function*(){const t=this._historyList.chosen;t&&this.setValue(t),this.fireInput()})))),t.addButton("Refresh",(()=>{this.experimentRunsUpdate.next()}),2,"Reload list of runs"),t.addButton("Discard",(()=>{this.setValue(null),this.fireInput(),t.close()}),1,"Discard the previous choice"),a()(t.getButton("CANCEL")).hide(),t.add(this._historyList.root),t}setValue(t){var e,n,i,o,s,r,a;this._chosenRun=t,this._chosenRunId=null!==(n=null===(e=this._chosenRun)||void 0===e?void 0:e.id)&&void 0!==n?n:null,this.onHistoricalRunChosen.next(t),this.stringValue=t?(null===(i=this.options)||void 0===i?void 0:i.stringValueFunc)?null===(o=this.options)||void 0===o?void 0:o.stringValueFunc(t):[`${Nt(t)} \\ ${t.author.name}`,(null!==(a=null!==(r=null===(s=this.options)||void 0===s?void 0:s.mainProps)&&void 0!==r?r:Q(t.func))&&void 0!==a?a:[]).map((e=>X(t,e))).join(" \\ ")].join(" \\ "):"No run chosen",this.notify&&this.fireChanged()}getValue(){return this._chosenRun}get chosenRun(){return this._chosenRun}get chosenRunId(){return this._chosenRunId}set chosenRunId(t){this._chosenRunId=t}get root(){return this._visibleInput.root}set stringValue(t){this._visibleInput.value=t,this._visibleInput.setTooltip(this._visibleInput.value)}get stringValue(){return this._visibleInput.value}get iconRoot(){return this._visibleIcon}toggleLoaderExpRuns(t){this.store.isExperimentRunsLoading.next(t)}}class Kt extends qt{set value(t){this.setValue(t)}get value(){return this.getValue()}}class Zt extends qt{get value(){const t=this.getValue();return t?JSON.stringify({visualValue:this.stringValue,id:t.id.split("-")}):null}set value(t){this.setValue(null),this.stringValue=t?JSON.parse(t).visualValue:"No run is chosen",this.chosenRunId=t?JSON.parse(t).id.join("-"):""}}var Xt=n(565),Qt={};Qt.styleTagTransform=It(),Qt.setAttributes=bt(),Qt.insert=gt().bind(null,"head"),Qt.domAPI=mt(),Qt.insertStyleElement=Ct(),ht()(Xt.A,Qt),Xt.A&&Xt.A.locals&&Xt.A.locals;var te;class ee extends o.Widget{updateHistoryPane(t){this.historyList.updateRuns(t)}showEditDialog(t){this.historyList.editRun(t)}addRun(t){this.historyList.addRun(t)}get history(){return this.historyList.runs}get onCompactModeChanged(){return this.historyList.onCompactModeChanged}get compactMode(){return this.historyList.compactMode}constructor(n){super(e.box(e.divText("No historical runs loaded","hp-no-elements-label"),{style:{width:"100%",height:"100%"}})),this.func=n,this.onRunChosen=new c.Subject,this.onComparison=new c.Subject,this.afterRunEdited=new c.Subject,this.afterRunDeleted=new c.Subject,this.allRunsFetch=new c.Subject,this.historyList=new Wt([],{fallbackText:"No runs are found in history",showActions:!0,showBatchActions:!0,isHistory:!0}),this.panel=this.historyList.root;const i=this.historyList.onChosen.pipe((0,s.filter)((t=>!!t))).subscribe((t=>this.onRunChosen.next(t.id))),o=this.historyList.onComparisonCalled.subscribe((t=>this.onComparison.next(t))),r=this.allRunsFetch.subscribe((()=>{return n=this,i=void 0,s=function*(){e.setUpdateIndicator(this.root,!0),dt.pullRunsByName(this.func.name,[{author:t.shell.user}],{},["session.user","options"]).then((t=>{e.empty(this.root),this.root.appendChild(this.panel),this.updateHistoryPane(t)})).catch((e=>t.shell.error(e))).finally((()=>e.setUpdateIndicator(this.root,!1)))},new((o=void 0)||(o=Promise))((function(t,e){function r(t){try{l(s.next(t))}catch(t){e(t)}}function a(t){try{l(s.throw(t))}catch(t){e(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof o?n:new o((function(t){t(n)}))).then(r,a)}l((s=s.apply(n,i||[])).next())}));var n,i,o,s})),a=this.historyList.onMetadataEdit.subscribe((t=>{this.afterRunEdited.next(t)})),l=this.historyList.onDelete.subscribe((t=>{this.afterRunDeleted.next(t)}));this.subs.push(i,r,a,o,l),this.allRunsFetch.next()}}!function(t){t.fileInput=function(t="Drag-n-drop here",e=null,n=null,i=Rt){return new St(t,e,n,i)},t.historyInput=function(t,e,n){return new Kt(t,e,n)},t.historyInputJSON=function(t,e,n){return new Zt(t,e,n)},t.historyPanel=function(t){return new ee(t)}}(te||(te={}));var ne=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ie=window;class oe extends o.TableView{static fromComparedRuns(n,i){return ne(this,arguments,void 0,(function*(n,i,s={parentView:void 0,parentCall:void 0}){const r=((n,i,s={parentView:void 0,parentCall:void 0})=>{var r,l;const u=i,c=[...u.inputs,...u.outputs].map((t=>Dt(t))).reduce(((t,e)=>(t[e.name]?t[e.name].push(...e.config):t[e.name]=e.config,t)),{}),d=t=>{var e;if(t.propertyType===o.TYPE.DATA_FRAME){const e=c[t.name].map((e=>{var i;let s=null!==(i=t.caption)&&void 0!==i?i:t.name;const r=o.Column.fromType(o.TYPE.DATA_FRAME,s,n.length);r.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const a=p.columns.getUnusedName(`${r.name} (${e.type})`);return r.name=a,s=a,r.temp[g]=e,p.columns.add(r),r}));return e}{let i=null!==(e=t.caption)&&void 0!==e?e:t.name;const s=o.Column.fromType(t.propertyType,i,n.length);s.init((e=>{var i;return null!==(i=n[e].inputs[t.name])&&void 0!==i?i:n[e].outputs[t.name]}));const r=p.columns.getUnusedName(s.name);return s.name=r,i=r,p.columns.add(s),[s]}},p=o.DataFrame.create(n.length),h=[];return n.forEach((t=>{var e;let n=null!==(e=t.options.title)&&void 0!==e?e:`${t.func.name} - ${Nt(t)}`,i=2;for(;h.includes(n);)n=`${t.func.name} - ${Nt(t)})\n .toLocaleString('en-us', {month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric'})} - ${i}`,i++;h.push(n)})),p.columns.add(o.Column.fromStrings(w,h)),p.name=(null===(r=s.parentCall)||void 0===r?void 0:r.func.name)?`${null===(l=s.parentCall)||void 0===l?void 0:l.func.name} - comparison`:`${i.name} - comparison`,u.inputs.forEach((t=>d(t))),u.outputs.forEach((t=>d(t))),t.events.onCurrentObjectChanged.subscribe((({sender:n})=>{if(n instanceof o.Column&&n.type===o.TYPE.DATA_FRAME&&t.shell.tv&&t.shell.tv.temp.isComparison&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.temp[g].type)){t.shell.windows.showProperties=!0;const i=t=>{const e=t.get(0).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,0));for(let n=1;n<t.length;n++){const i=t.get(n).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=n.temp[g].look;setTimeout((()=>{switch(n.temp[g].type){case o.VIEWER.LINE_CHART:const r=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.line(Object.assign(Object.assign({},s),{split:I})).root}))));a()(r).css({width:"100%"}),t.shell.o=r;break;case o.VIEWER.SCATTER_PLOT:const l=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.scatter(Object.assign(Object.assign({},s),{color:I})).root}))));t.shell.o=l,a()(l).css({width:"100%"});break;case o.VIEWER.HISTOGRAM:const u=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.histogram(Object.assign(Object.assign({},s),{split:I})).root}))));t.shell.o=u,a()(u).css({width:"100%"});break;case o.VIEWER.BOX_PLOT:const c=e.waitBox((()=>Mt(void 0,void 0,void 0,(function*(){var t;const e=null!==(t=n.temp.unitedDf)&&void 0!==t?t:i(n);return n.temp.unitedDf=e,e.plot.box(Object.assign(Object.assign({},s),{category:I})).root}))));t.shell.o=c,a()(c).css({width:"100%"})}}))}})),p})(n,i,s),l=[...t.shell.views].find((t=>t.type===v||"scripts"===t.type||"functions"===t.type));return l&&(t.shell.v=l),new this(r,s)}))}constructor(e,n={}){super(ie.grok_TableView(e.dart,!1)),n.parentView&&(this.parentView=n.parentView),this.parentCall=n.parentCall||t.functions.getCurrentCall()}showAllColumns(){const t=this.dataFrame.columns.names();this.grid.columns.setVisible(t)}showChangingColumns(){const t=this.dataFrame.columns.names().filter((t=>o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)&&this.dataFrame.getCol(t).categories.length>1||!o.TYPES_SCALAR.has(this.dataFrame.getCol(t).type)));this.grid.columns.setVisible(t)}defaultCustomize(){var n;const i=e.iconFA("compress-alt",(()=>{this.showChangingColumns(),a()(s).show(),a()(i).hide()}),"Hide constant parameters"),s=e.iconFA("expand-arrows-alt",(()=>{this.showAllColumns(),a()(s).hide(),a()(i).show()}),"Show all parameters");a()(i).hide(),this.setRibbonPanels([...this.getRibbonPanels(),[i,s]]),this.showChangingColumns(),this.root.style.removeProperty("width"),this.root.firstChild.style.removeProperty("width"),this.root.firstChild.firstChild.style.removeProperty("width"),this.grid.props.rowHeight=180,this.grid.props.showAddNewRowIcon=!1,this.grid.props.allowEdit=!1,this.grid.columns.byName(w).width=70;for(let t=0;t<this.grid.columns.length;t++){const e=this.grid.columns.byIndex(t);(null===(n=e.column)||void 0===n?void 0:n.temp[g])&&(e.width=350,e.cellType="html")}const r=new o.LruCache;this.grid.onCellPrepare((t=>ne(this,void 0,void 0,(function*(){if(!t.isColHeader&&!t.isRowHeader){if(t.tableColumn.name===w){t.customText="";const n=t.cell.value.split(" - "),i=n.length>1?[n[0],e.element("br"),n[1]]:n;return t.element=e.div(i,{style:{"writing-mode":"vertical-rl","text-orientation":"mixed",margin:"auto"}}),void(t.element.parentElement.style.display="flex")}if(t.tableColumn&&t.tableColumn.temp[g]){const e=t.cell.value,n=t.tableColumn.temp[g],i=n.type,s=()=>ne(this,void 0,void 0,(function*(){const s=Object.values(m).includes(i)?o.Viewer.fromType(i,e):yield e.plot.fromType(i);return t.tableColumn.temp[g].look?s.setOptions(t.tableColumn.temp[g].look):(s.setOptions(n),t.tableColumn.temp[g]=s.getOptions()),s.root})),a=`${e.id}_${i}`;if(r.get(a))t.element=r.get(a);else{const e=yield s();r.set(a,e),t.element=e}t.element.style.width="100%",t.element.style.height="100%"}}}))));const l=e.box(e.div([],{style:{"min-height":"100px"}})),u=t.events.onCurrentViewChanged.subscribe((()=>{t.shell.v.id===this.id?t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25):t.shell.dockManager.close(l)})),c=this.grid.onCellClick.subscribe((n=>{var i;if(t.shell.v.id===this.id&&n.isColHeader&&(null===(i=n.tableColumn)||void 0===i?void 0:i.type)===o.TYPE.DATA_FRAME&&[o.VIEWER.LINE_CHART,o.VIEWER.SCATTER_PLOT,o.VIEWER.HISTOGRAM,o.VIEWER.BOX_PLOT].includes(n.tableColumn.temp[g].type)){t.shell.dockManager.findNode(l)||t.shell.dockManager.dock(l,"down",null,"Comparison chart",.25);const i=t=>{const e=o.toJs(t.get(0)).clone();e.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,0));for(let n=1;n<t.length;n++){const i=o.toJs(t.get(n)).clone();i.columns.addNew(I,o.TYPE.STRING).init(t.dataFrame.get(w,n));const s=[o.COLUMN_TYPE.INT,o.COLUMN_TYPE.FLOAT];for(let t=0;t<i.columns.length;t++){const n=i.columns.byIndex(t),r=e.columns.byIndex(t);n.type!==r.type&&s.includes(n.type)&&s.includes(r.type)&&(n.type!==o.COLUMN_TYPE.FLOAT&&i.columns.replace(n,n.convertTo(o.COLUMN_TYPE.FLOAT)),r.type!==o.COLUMN_TYPE.FLOAT&&e.columns.replace(r,r.convertTo(o.COLUMN_TYPE.FLOAT)))}e.append(i,!0)}return e},s=(t,e,i)=>{var s;switch(null===(s=n.tableColumn)||void 0===s?void 0:s.temp[g].type){case o.VIEWER.LINE_CHART:return i.plot.line(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.SCATTER_PLOT:return i.plot.scatter(Object.assign(Object.assign({},e),{color:I})).root;case o.VIEWER.HISTOGRAM:return i.plot.histogram(Object.assign(Object.assign({},e),{split:I})).root;case o.VIEWER.BOX_PLOT:return i.plot.box(Object.assign(Object.assign({},e),{category:I})).root}};e.setUpdateIndicator(l,!0),setTimeout((()=>{var t;if(!n.tableColumn.temp.unitedPlot){const o=n.tableColumn.temp[g].look,r=i(n.tableColumn);n.tableColumn.temp.unitedPlot=s(null===(t=n.tableColumn)||void 0===t?void 0:t.temp[g].type,o,r),e.setUpdateIndicator(l,!1)}e.empty(l),l.appendChild(n.tableColumn.temp.unitedPlot)}),10)}else t.shell.dockManager.close(l)}));this.subs.push(c,u)}}const se="_DG_CUSTOM_SERIALIZED_TOKEN_";function re(t,e){if(e&&e[se]&&e.value)switch(e[se]){case"DataFrame":return o.DataFrame.fromByteArray(new Uint8Array(e.value));case"ArrayBuffer":return new Uint8Array(e.value).buffer;case"Map":return new Map(e.value);case"Set":return new Set(e.value)}return e}const ae=[{name:"Null",predicate:function(t,e){return null==t&&null==e},checker:function(){}},{name:"Boolean",predicate:function(t,e){return"boolean"==typeof t&&"boolean"==typeof e},checker:ue},{name:"String",predicate:function(t,e){return"string"==typeof t&&"string"==typeof e},checker:ue},{name:"Integer",predicate:function(t,e){return Number.isInteger(t)&&Number.isInteger(e)},checker:ue},{name:"Float",predicate:function(t,e){return"number"==typeof t&&"number"==typeof e},checker:function(t,e,n){if(!(t===Number.POSITIVE_INFINITY&&e===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY&&e===Number.NEGATIVE_INFINITY||isNaN(t)&&isNaN(e)))return Math.abs(t-e)<n.options.floatTolerance?void 0:[{msg:`Expected ${e}, got ${t} (tolerance = ${n.options.floatTolerance})`}]}},{name:"Map",predicate:function(t,e){return t instanceof Map&&e instanceof Map},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Maps are of different size: actual map size is ${t.size} and expected map size is ${e.size}`};o.push(n)}for(const n of e.keys()){const o=t.get(n),s=e.get(n);i([String(n)],o,s)}return o}},{name:"Set",predicate:function(t,e){return t instanceof Set&&e instanceof Set},checker:function(t,e,n,i){const o=[];if(t.size!==e.size){const n={msg:`Sets are of different size: actual set size is ${t.size} and expected set size is ${e.size}`};o.push(n)}for(const n of e.values()){const e=t.has(n);i([String(n)],e,!0)}return o}},{name:"ArrayBuffer",predicate:function(t,e){return t instanceof ArrayBuffer&&e instanceof ArrayBuffer},checker:function(t,e,n,i){return ce(Array.from(new Uint8Array(t)),Array.from(new Uint8Array(e)),0,i)}},{name:"Array",predicate:function(t,e){return t instanceof Array&&e instanceof Array},checker:ce},{name:"DataFrame",predicate:function(t,e){return t instanceof o.DataFrame&&e instanceof o.DataFrame},checker:function(t,e,n,i){const o=[];if(t.rowCount!==e.rowCount){const n={msg:`Dataframes has different row count: actual row count is ${t.rowCount} and expected row count is ${e.rowCount}`};o.push(n)}for(const n of e.columns){const s=t.columns.byName(n.name);if(s)if(s.type===n.type)for(let t=0;t<e.rowCount;t++){const e=s.get(t),o=n.get(t);i([n.name,String(t)],e,o)}else{const t={msg:`Column ${n.name} type expected ${n.type} got ${s.type}`};o.push(t)}else{const t={msg:`Column ${n.name} not found`};o.push(t)}}return o}},{name:"Object",predicate:function(t,e){return"object"==typeof t&&"object"==typeof e},checker:function(t,e,n,i){for(const[n,o]of Object.entries(e))i([n],t[n],o);return[]}}];class le extends Error{}function ue(t,e){if(t!==e)return[{msg:`Expected ${e}, got ${t}`}]}function ce(t,e,n,i){const o=[];if(t.length!==e.length){const n={msg:`Arrays are of different length: actual array length is ${t.length} and expected array length is ${e.length}`};o.push(n)}for(let n=0;n<t.length;n++)i([String(n)],t[n],e[n]);return o}const de={floatTolerance:.001,maxErrorsReport:5,maxDepth:128,checkersSeq:ae,prefix:""};class pe{constructor(t={}){this.options=Object.assign(Object.assign({},de),t),this.state={errors:[],currentPath:[],options:this.options}}run(t,e){this.matchChecker(t,e),this.checkErrorsLimit(0)}checkDeep(t,e,n){const i=t.length;if(this.state.currentPath.push(...t),this.state.currentPath.length>this.options.maxDepth)throw new le(`Max depth ${this.options.maxDepth} is exceeded, potentially a circular structure`);this.matchChecker(e,n),this.state.currentPath.splice(-i)}matchChecker(t,e){let n=!1;for(const{predicate:i,checker:o}of this.options.checkersSeq)if(i(t,e)){n=!0;const i=o(t,e,this.state,this.checkDeep.bind(this));i&&i.map((t=>this.addError(t)));break}if(!n){const n={msg:`Type mismatch or no checker defined: expected ${e}, got ${t}`};this.addError(n)}}addError(t){var e,n;const i={path:[...null!==(e=this.state.currentPath)&&void 0!==e?e:[],...null!==(n=t.path)&&void 0!==n?n:[]],msg:t.msg};this.state.errors.push(i),this.checkErrorsLimit()}checkErrorsLimit(t=this.options.maxErrorsReport){if(this.state.errors.length>t){const t=this.makeReport();throw new le(t)}}makeReport(){const t=this.state.errors.map((t=>{var e;const n=(null!==(e=t.path)&&void 0!==e?e:[]).map((t=>`['${String(t)}']`)).join("."),i=n?`${n}: ${t.msg}`:t.msg;return this.options.prefix?`${this.options.prefix}: ${i}`:i})).slice(0,this.options.maxErrorsReport).join("\n");return t}}var he=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};function fe(e,n){return he(this,arguments,void 0,(function*(e,n,i={}){var o;yield function(t,e){return he(this,void 0,void 0,(function*(){if(!(yield t.isReady.pipe((0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(e))),(0,s.takeWhile)((t=>!t),!0),(0,s.last)()).toPromise()))throw new Error(`Waiting for view ${t.name} timeout`)}))}(n,null!==(o=i.initWaitTimeout)&&void 0!==o?o:2e4);const r=()=>he(this,void 0,void 0,(function*(){var e;if(i.parent){const n=null!==(e=i.parentWaitTimeout)&&void 0!==e?e:5e3,o=yield i.parent.isUpdating.pipe((0,s.map)((()=>i.parent.getRunningUpdates())),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(n))),(0,s.takeWhile)((t=>0!==t.length),!0),(0,s.last)()).toPromise();if(null==o?void 0:o.length){const e=`{options.prefix}: parent updates failed to complete in ${n}ms, updates: ${o.join(",")}`,s=new Error(e);throw i.interactive&&t.shell.error(String(s)),s}}}));yield r();for(const[t,o]of Object.entries(e.inputs)){const e=n.funcCall.inputParams[t].property.propertyType;i.updateMode?null==n.funcCall.inputs[t]&&(n.funcCall.inputs[t]=yield lt(e,o)):n.funcCall.inputs[t]=yield lt(e,o)}if(yield r(),yield(()=>he(this,void 0,void 0,(function*(){var e;if(n instanceof $n){const o=null!==(e=i.validatorsWaitTimeout)&&void 0!==e?e:5e3,r=yield n.pendingValidations.pipe((0,s.map)((t=>Object.keys(t))),(0,s.debounceTime)(100),(0,s.takeUntil)((0,c.of)(null).pipe((0,s.delay)(o))),(0,s.takeWhile)((()=>!n.isValid()),!0),(0,s.last)()).toPromise();if(null==r?void 0:r.length){const e=`{options.prefix}: validators failed to accept input in ${o}ms, inputs: ${r.join(",")}`,n=new Error(e);throw i.interactive&&t.shell.error(String(n)),n}}})))(),console.log(`running ${n.func.nqName}`),yield n.run(),!i.updateMode){console.log(`checking ${n.func.nqName} results`);try{!function(t,e,n){new pe(n).run(t,e)}(n.funcCall.outputs,e.outputs,i),!i.parent&&i.interactive&&t.shell.info(`${n.name} test passed`)}catch(e){throw i.interactive&&t.shell.error(String(e)),e}console.log(`${n.func.nqName} ok`)}}))}var me=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const ve=new URL(t.shell.startUri),ge="Run Data JSON",ye=()=>me(void 0,void 0,void 0,(function*(){const t=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,selfBrowserSurface:"include"}),e=new MediaRecorder(t),n=[];e.ondataavailable=t=>n.push(t.data),e.onstop=()=>{const e=new Blob(n,{type:n[0].type});t.getVideoTracks()[0].stop(),o.Utils.download(`Recording ${(new Date).toLocaleString("en-us",{month:"short",day:"numeric",hour:"numeric",minute:"numeric"})}.mkv`,e,n[0].type)},e.start()}));class be extends o.ViewBase{constructor(n,i={historyEnabled:!0,isTabbed:!1,skipInit:!1}){var s,r,a,l,u;super(),this.initValue=n,this.options=i,this._type="function",this.funcCallReplaced=new c.Subject,this.isReady=new c.BehaviorSubject(!1),this.exportConfig=null,this.getMocks=null,this.getTemplates=null,this.getHelp=null,this.reportBug=null,this.requestFeature=null,this.getAbout=null,this.historyBlock=null,this.isHistorical=new c.BehaviorSubject(!1),this.historyRoot=e.div(),this.consistencyState=new c.BehaviorSubject("consistent"),this.defaultExportFilename=(t,e)=>`${this.name} - ${(new Date).toLocaleString("en-US").replaceAll(/:|\//g,"-")}.${null!=e?e:this.exportConfig.supportedExtensions[t]}`,this.defaultSupportedExportExtensions=()=>({Excel:"xlsx"}),this.defaultSupportedExportFormats=()=>["Excel"],this.helpCache=null,this.box=!0,this.parentCall=t.functions.getCurrentCall(),n instanceof o.FuncCall&&(this.parentCall=n),this.parentView=null===(a=null===(r=null===(s=this.parentCall)||void 0===s?void 0:s.parentCall)||void 0===r?void 0:r.aux)||void 0===a?void 0:a.view,(null===(u=null===(l=this.parentCall)||void 0===l?void 0:l.func)||void 0===u?void 0:u.name)&&(this.basePath=`/${this.parentCall.func.name}`),i.skipInit||this.init()}onFuncCallReady(){return me(this,void 0,void 0,(function*(){if(yield dt.augmentCallWithFunc(this.funcCall,!1),!this.options.isTabbed){this.name&&"New view"!==this.name||(this.name=this.funcCall.func.friendlyName);try{this.func.package&&(yield this.getPackageData())}catch(t){console.log(t)}}this.build();const t=this.getStartId();if(t&&!this.options.isTabbed&&(e.setUpdateIndicator(this.root,!0),this.loadRun(t),e.setUpdateIndicator(this.root,!1),this.setAsLoaded()),this.isHistoryEnabled&&this.func){const t=this.options.isTabbed?this.isHistorical.subscribe((t=>{t||(this.funcCall.id=null)})):this.isHistorical.subscribe((t=>{var e,n;if(t){this.path=`?id=${this.funcCall.id}`;const t=Nt(this.funcCall);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=this.funcCall.options.title)&&void 0!==e?e:t}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=this.funcCall.options.title)&&void 0!==n?n:t}`}else this.path="",this.funcCall.id=null,this.name=`${this.name.substring(0,this.name.indexOf(" — ")>0?this.name.indexOf(" — "):void 0)}`}));this.subs.push(t)}}))}getStartId(){return t.shell.getVar("isLoaded")?void 0:ve.searchParams.get("id")}setAsLoaded(){return t.shell.setVar("isLoaded",!0)}get funcCall(){return this._funcCall}get func(){var t;return null===(t=this.funcCall)||void 0===t?void 0:t.func}get lastCall(){return this._lastCall}set lastCall(t){this._lastCall=t}get type(){return this._type}getPackageData(){return me(this,void 0,void 0,(function*(){var t,e;const n=this.func.package;if(!n)return;const i=null===(t=yield null==n?void 0:n.getProperties())||void 0===t?void 0:t.REPORT_BUG_URL;i&&!this.reportBug&&(this.reportBug=()=>me(this,void 0,void 0,(function*(){window.open(i,"_blank")})));const o=null===(e=yield null==n?void 0:n.getProperties())||void 0===e?void 0:e.REQUEST_FEATURE_URL;o&&!this.requestFeature&&(this.requestFeature=()=>me(this,void 0,void 0,(function*(){window.open(o,"_blank")})));const s=`${n.friendlyName}.\nLast updated on ${p()(n.updatedOn).format("YYYY MMM D, HH:mm")}`;this.getAbout||(this.getAbout=()=>me(this,void 0,void 0,(function*(){return s})))}))}linkFunccall(t){this._funcCall=t,this.funcCallReplaced.next(!0)}loadFuncCallById(){return me(this,void 0,void 0,(function*(){if(this.initValue instanceof o.FuncCall)return yield new Promise((t=>setTimeout(t,0))),void this.linkFunccall(this.initValue);e.setUpdateIndicator(this.root,!0);const n=this.getStartId();if(n&&!this.options.isTabbed)this.linkFunccall(yield dt.loadRun(n));else{const e=yield t.functions.eval(this.initValue);this.linkFunccall(e.prepare({}))}e.setUpdateIndicator(this.root,!1)}))}init(){return me(this,void 0,void 0,(function*(){yield this.loadFuncCallById(),yield this.onFuncCallReady(),this.isReady.next(!0)}))}build(){e.empty(this.root),this.root.appendChild(this.buildIO()),this.options.historyEnabled&&this.isHistoryEnabled&&this.buildHistoryBlock(),this.buildRibbonMenu(),this.buildRibbonPanels()}onComparisonLaunch(e){return me(this,void 0,void 0,(function*(){const n=this.comparatorFunc;if(n){const i=yield t.functions.eval(n),o=(yield i.prepare({params:{comparedRuns:e}}).call()).outputs.comparisonView;return void t.shell.addView(o)}const i=t.shell.v.parentCall,o=[...t.shell.views].find((t=>t.type===v)),s=yield oe.fromComparedRuns(e,this.func,{parentView:o,parentCall:i});t.shell.addView(s),s.defaultCustomize();const r=this.compareCustomizer;if(r){const e=yield t.functions.eval(r);yield e.prepare({params:{defaultView:s}}).call()}}))}onSaveClick(){return me(this,void 0,void 0,(function*(){yield this.saveRun(this.funcCall)}))}buildHistoryBlock(){const n=te.historyPanel(this.func);let i=!1;return this.subs.push(n.onCompactModeChanged.subscribe((e=>{const n=t.shell.dockManager.findNode(this.historyRoot);n&&(t.shell.dockManager.close(n),e?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3))})),n.onRunChosen.subscribe((t=>me(this,void 0,void 0,(function*(){e.setUpdateIndicator(this.root,!0),yield this.loadRun(t),e.setUpdateIndicator(this.root,!1)})))),n.onComparison.subscribe((t=>me(this,void 0,void 0,(function*(){Lt(n.root,!0);const e=yield Promise.all(t.map((t=>dt.loadRun(t))));yield this.onComparisonLaunch(e),Lt(n.root,!1)})))),n.afterRunEdited.subscribe((t=>{var e,n;if(t.id===this.funcCall.id&&t.options.title){this.path=`?id=${this.funcCall.id}`;const i=Nt(t);this.name.indexOf(" — ")<0?this.name=`${this.name} — ${null!==(e=t.options.title)&&void 0!==e?e:i}`:this.name=`${this.name.substring(0,this.name.indexOf(" — "))} — ${null!==(n=t.options.title)&&void 0!==n?n:i}`}})),t.events.onViewRemoving.subscribe((e=>{if(e.args.view==this){const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}})),t.events.onCurrentViewChanged.subscribe((()=>{var e;if(t.shell.v==this)i&&((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3));else{const e=t.shell.dockManager.findNode(this.historyRoot);e?(t.shell.dockManager.close(e),i=!0):i=!1}}))),e.empty(this.historyRoot),this.historyRoot.style.removeProperty("justify-content"),this.historyRoot.append(n.root),this.historyBlock=n,n.root}buildRibbonPanels(){const n=e.iconFA("history",(()=>{var e;t.shell.dockManager.findNode(this.historyRoot)||((null===(e=this.historyBlock)||void 0===e?void 0:e.compactMode)?t.shell.dockManager.dock(this.historyRoot,"right",null,"History",.3):t.shell.dockManager.dock(this.historyRoot,"down",null,"History",.3),this.historyRoot.parentElement.classList.add("ui-box"),this.historyRoot.classList.add("ui-box"))})),i=e.iconFA("save",(()=>me(this,void 0,void 0,(function*(){yield this.onSaveClick()}))),"Save current state"),o=e.comboPopup(e.iconFA("arrow-to-bottom"),this.getFormats(),this.exportRun.bind(this)),r=e.iconFA("edit",(()=>{this.historyBlock&&this.lastCall&&this.historyBlock.showEditDialog(this.historyBlock.history.get(this.funcCall.id))}),"Edit this run metadata"),l=this.isHistorical.subscribe((t=>{t?(e.setDisplay(o,!K(this.funcCall)),e.setDisplay(r,!0)):(a()(o).hide(),a()(r).hide())}));if(this.subs.push(l),e.tooltip.bind(o,(()=>"inconsistent"===this.consistencyState.value&&this.mandatoryConsistent?"Current run is inconsistent. Export feature is disabled.":null)),!this.options.isTabbed&&this.mandatoryConsistent){const t=this.consistencyState.pipe((0,s.distinctUntilChanged)()).subscribe((t=>{"inconsistent"===t?(a()(o).addClass("d4-disabled"),a()(o.lastChild).css("color","unset")):(a()(o).removeClass("d4-disabled"),a()(o.lastChild).removeProp("color"))}));this.subs.push(t)}const u=[[...!this.options.isTabbed&&this.isHistoryEnabled&&this.options.historyEnabled?[n]:[],...!this.options.isTabbed&&this.isHistoryEnabled?[i]:[],...!this.options.isTabbed&&this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0?[o]:[],...this.options.isTabbed?[]:[r]]];return this.setRibbonPanels(u),u}buildRibbonMenu(){if(this.ribbonMenu.clear(),!(this.exportConfig||this.reportBug||this.requestFeature||this.getHelp||this.getMocks||this.getTemplates))return;const t=this.ribbonMenu.group("Model");if(this.getMocks&&this.getMocks.length>0)if(1===this.getMocks.length)t.item("Input data mock",this.getMocks[0].action);else{const e=t.group("Input data mocks");this.getMocks.forEach((t=>{e.item(t.mockName,t.action)})),t.endGroup()}if(this.getTemplates&&this.getTemplates.length>0)if(1===this.getTemplates.length)t.item("Input data template",this.getTemplates[0].action);else{const e=t.group("Input data templates");this.getTemplates.forEach((t=>{e.item(t.name,t.action)})),t.endGroup()}this.isExportEnabled&&this.exportConfig&&this.exportConfig.supportedFormats.length>0&&t.group("Export").items(this.getFormats(),this.exportRun.bind(this)).endGroup(),this.reportBug&&t.item("Report a bug",(()=>this.reportBug())),this.requestFeature&&t.item("Request a feature",(()=>this.requestFeature())),this.getHelp&&t.item("Help",(()=>this.getHelp()));const n=t.group("Test runner");n.item("Execute Test JSON",(()=>this.importRunJsonDialog())),n.item("Update Test JSON",(()=>this.importRunJsonDialog(!0))),t.endGroup(),t.item("Record the screen",ye),this.getAbout&&t.item("About",(()=>me(this,void 0,void 0,(function*(){const t=yield this.getAbout();if(t){const n=e.dialog("Current version");t.split("\n").forEach((t=>n.add(e.label(t)))),n.onOK((()=>{})),n.getButton("CANCEL").style.display="none",n.show({center:!0})}}))))}exportRun(t){return me(this,void 0,void 0,(function*(){if(t!==ge)o.Utils.download(this.exportConfig.filename(t),yield this.exportConfig.export(t));else{const t=yield this.exportRunJson();t&&o.Utils.download(this.defaultExportFilename("","json"),t)}}))}getFormats(){var t,e;return[...null!==(e=null===(t=this.exportConfig)||void 0===t?void 0:t.supportedFormats)&&void 0!==e?e:[],ge]}onBeforeSaveRun(t){return me(this,void 0,void 0,(function*(){}))}onAfterSaveRun(t){return me(this,void 0,void 0,(function*(){}))}saveRun(e){return me(this,void 0,void 0,(function*(){let n=et(e);var i;yield this.onBeforeSaveRun(n),K(e)&&(n=yield(i=e,q(void 0,void 0,void 0,(function*(){const e=(yield t.functions.eval(i.func.nqName)).prepare([...i.inputs].reduce(((t,[e,n])=>(t[e]=n,t)),{}));return i.options.forEach((t=>e.options[t]=i.options[t])),e})))),n.id&&n.newId();const o=yield dt.saveRun(n),s=yield dt.loadRun(o.id);return this.options.historyEnabled&&this.isHistoryEnabled&&this.historyBlock&&this.historyBlock.addRun(s),this.linkFunccall(s),this.isHistorical.next(!0),yield this.onAfterSaveRun(o),o}))}onBeforeDeleteRun(t){return me(this,void 0,void 0,(function*(){}))}onAfterDeleteRun(t){return me(this,void 0,void 0,(function*(){}))}deleteRun(t){return me(this,void 0,void 0,(function*(){return yield this.onBeforeDeleteRun(t),yield dt.deleteRun(t),yield this.onAfterDeleteRun(t),t.id}))}onBeforeLoadRun(){return me(this,void 0,void 0,(function*(){}))}onAfterLoadRun(t){return me(this,void 0,void 0,(function*(){}))}loadRun(t){return me(this,void 0,void 0,(function*(){yield this.onBeforeLoadRun();const e=yield dt.loadRun(t);return this.lastCall=et(e),this.linkFunccall(e),this.isHistorical.next(!0),yield this.onAfterLoadRun(e),e}))}onBeforeRun(t){return me(this,void 0,void 0,(function*(){}))}onAfterRun(t){return me(this,void 0,void 0,(function*(){}))}run(){return me(this,void 0,void 0,(function*(){if(!this.funcCall)throw new Error("The correspoding function is not specified");yield this.onBeforeRun(this.funcCall);const e=o.TaskBarProgressIndicator.create("Calculating...");try{this.funcCall.newId(),yield this.funcCall.call(),yield this.onAfterRun(this.funcCall),this.lastCall=et(this.funcCall),this.options.isTabbed||this.runningOnInput||!this.isHistoryEnabled||(yield this.saveRun(this.funcCall))}catch(e){t.shell.error(e.toString())}finally{e.close()}}))}exportRunJson(){return me(this,void 0,void 0,(function*(){if(this._lastCall)return function(t,e=2){return JSON.stringify(t,((t,e)=>e instanceof o.DataFrame?{[se]:"DataFrame",value:Array.from(e.toByteArray())}:e instanceof ArrayBuffer?{[se]:"ArrayBuffer",value:Array.from(new Uint8Array(e))}:e instanceof Map?{[se]:"Map",value:Array.from(e)}:e instanceof Set?{[se]:"Set",value:Array.from(e)}:e),e)}(yield function(t,e){return q(this,void 0,void 0,(function*(){const n={};for(const[i,o]of Object.entries(t.inputs)){const{property:t}=e.funcCall.inputParams[i];n[i]=yield at(t,o,e)}return{inputs:n,outputs:t.outputs}}))}(this._lastCall,this),0)}))}importRunJsonDialog(){return me(this,arguments,void 0,(function*(t=!1){const n=new St("JSON file",null,null,"application/json"),i={modal:!0,fullScreen:!0,width:500,height:200,center:!0};if(!(yield new Promise(((t,o)=>{e.dialog({title:"Import Run JSON"}).add(e.div([e.inputs([n])])).onOK((()=>t(!0))).onCancel((()=>t(!1))).show(i)})))||!n.value)return;const o=(r=yield n.value.text(),JSON.parse(r,re));var r;t?(yield this.executeTest(o,!0),yield this.isHistorical.pipe((0,s.filter)((t=>t)),(0,s.take)(1),(0,s.delay)(0)).toPromise(),yield this.exportRun(ge)):yield this.executeTest(o)}))}executeTest(t){return me(this,arguments,void 0,(function*(t,e=!1){yield fe(t,this,{updateMode:e,interactive:!0})}))}get compareCustomizer(){var t;return null!==(t=this.func.options.compareCustomizer)&&void 0!==t?t:null}get comparatorFunc(){var t;return null!==(t=this.func.options.comparatorFunc)&&void 0!==t?t:null}get uploadFunc(){var t;return null!==(t=this.func.options.uploadFunc)&&void 0!==t?t:null}get runningOnInput(){return"true"===this.func.options.runOnInput}get runningOnStart(){return"true"===this.func.options.runOnOpen}get mainParams(){return this.func.options.mainParams?JSON.parse(this.func.options.mainParams):null}get mandatoryConsistent(){var t;return"true"===(null===(t=this.parentCall)||void 0===t?void 0:t.func.options.mandatoryConsistent)}get hasContextHelp(){return!!this.func.options.help}getContextHelp(){return me(this,void 0,void 0,(function*(){const e=this.func.options.help;if(!e)return null;if(this.helpCache)return this.helpCache;const n=`System:AppData/${e}`;if(yield t.dapi.files.exists(n)){const e=yield t.dapi.files.readAsText(n);return this.helpCache=e,e}const i=`${t.shell.user.name}.home/${e}`;if(yield t.dapi.files.exists(i)){const e=yield t.dapi.files.readAsText(i);return this.helpCache=e,e}return null}))}get features(){var t;return JSON.parse(null!==(t=this.func.options.features)&&void 0!==t?t:"{}")}getFeature(t,e){var n;return this.features instanceof Array?this.features.includes(t):this.features instanceof Object&&null!==(n=this.features[t])&&void 0!==n?n:e}get isExportEnabled(){return this.getFeature("export",!0)}get isHistoryEnabled(){return this.getFeature("history",!0)}get isSaEnabled(){return this.getFeature("sens-analysis",!1)}get hasUploadMode(){return this.getFeature("upload",!1)}get isFittingEnabled(){return this.getFeature("fitting",!1)}}var Ae=Uint8Array,Ce=Uint16Array,we=Uint32Array,Ie=new Ae([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Te=new Ae([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ee=(new Ae([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),function(t,e){for(var n=new Ce(31),i=0;i<31;++i)n[i]=e+=1<<t[i-1];var o=new we(n[30]);for(i=1;i<30;++i)for(var s=n[i];s<n[i+1];++s)o[s]=s-n[i]<<5|i;return[n,o]}),xe=Ee(Ie,2),Re=xe[0],Se=xe[1];Re[28]=258,Se[258]=28;for(var Oe=Ee(Te,0),Pe=(Oe[0],Oe[1],new Ce(32768)),Fe=0;Fe<32768;++Fe){var _e=(43690&Fe)>>>1|(21845&Fe)<<1;_e=(61680&(_e=(52428&_e)>>>2|(13107&_e)<<2))>>>4|(3855&_e)<<4,Pe[Fe]=((65280&_e)>>>8|(255&_e)<<8)>>>1}var ke=new Ae(288);for(Fe=0;Fe<144;++Fe)ke[Fe]=8;for(Fe=144;Fe<256;++Fe)ke[Fe]=9;for(Fe=256;Fe<280;++Fe)ke[Fe]=7;for(Fe=280;Fe<288;++Fe)ke[Fe]=8;var Me=new Ae(32);for(Fe=0;Fe<32;++Fe)Me[Fe]=5;var Be=new Ae(0),Le="undefined"!=typeof TextDecoder&&new TextDecoder;try{Le.decode(Be,{stream:!0})}catch(t){}"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout&&setTimeout;var De=n(933),Ne={};Ne.styleTagTransform=It(),Ne.setAttributes=bt(),Ne.insert=gt().bind(null,"head"),Ne.domAPI=mt(),Ne.insertStyleElement=Ct(),ht()(De.A,Ne),De.A&&De.A.locals&&De.A.locals;var Ve=n(362),je={};je.styleTagTransform=It(),je.setAttributes=bt(),je.insert=gt().bind(null,"head"),je.domAPI=mt(),je.insertStyleElement=Ct(),ht()(Ve.A,je),Ve.A&&Ve.A.locals&&Ve.A.locals;var $e,Ye;!function(t){t.INCORRECT_SIZE_TYPE="Size must be an integer.",t.SIZE_MUST_BE_POSITIVE="Size must be positive."}($e||($e={})),function(t){t[t.BATCH_SIZE=100]="BATCH_SIZE",t[t.MS_TO_SLEEP=10]="MS_TO_SLEEP"}(Ye||(Ye={}));const He=t=>new Promise(((e,n)=>setTimeout(e,t)));function Ue(t){if(!Number.isInteger(t))throw new Error($e.INCORRECT_SIZE_TYPE);if(t<1)throw new Error($e.SIZE_MUST_BE_POSITIVE)}function We(t){return e=this,n=void 0,s=function*(){const e=[],n=o.TaskBarProgressIndicator.create("Running sensitivity analysis...");n.cancelable=!0;let i=0;const s=t.length;for(let o=0;o<s&&(e.push(yield t[o].call()),1===o&&(n.update(100*o/s,"Running sensitivity analysis..."),yield He(10*Ye.MS_TO_SLEEP)),++i,!n.canceled);++o)i>=Ye.BATCH_SIZE&&(n.update(100*o/s,"Running sensitivity analysis..."),yield He(Ye.MS_TO_SLEEP),i=0);return n.close(),e},new((i=void 0)||(i=Promise))((function(t,o){function r(t){try{l(s.next(t))}catch(t){o(t)}}function a(t){try{l(s.throw(t))}catch(t){o(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((s=s.apply(e,n||[])).next())}));var e,n,i,s}class Ge{constructor(t=1,e=1){Ue(t),Ue(e),this.N=t,this.d=e,this.A=this.generateMatrix(t,e),this.B=this.generateMatrix(t,e),this.AB=this.createMixMatrax(this.A,this.B)}generateMatrix(t,e){const n=new Array(e);for(let i=0;i<e;++i){n[i]=new Float32Array(t);for(let e=0;e<t;++e)n[i][e]=Math.random()}return n}createMixMatrax(t,e){const n=this.d,i=new Array(n);for(let o=0;o<n;++o){i[o]=new Array(0);for(let s=0;s<n;++s)o!==s?i[o].push(t[s]):i[o].push(e[s])}return i}getRow(t,e){const n=new Float32Array(this.d);for(let i=0;i<this.d;++i)n[i]=t[i][e];return n}getRowOfMatrixA(t){return this.getRow(this.A,t)}getRowOfMatrixB(t){return this.getRow(this.B,t)}getRowOfMatrixAB(t,e){return this.getRow(this.AB[t],e)}getConcatenatedColumns(){const t=new Array(0),e=this.N,n=this.d;for(let i=0;i<n;++i){const o=new Float32Array(e*(n+2));o.set(this.A[i]),o.set(this.B[i],e);for(let t=0;t<n;++t)o.set(this.AB[t][i],2*e+e*t);t.push(o)}return t}}const ze="Unsupported output type.";function Je(e,n){const i=e.rowCount,s=n.value.row;if(null!==s)return e.columns.names().map((t=>({idx:s,columnName:t})));const r=e.col(n.value.colName);if(null===r)return t.shell.warning(`Output dataframe "${e.name}" doesn't contain the "${n.value.colName}" column. The last row is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));if(r.type!==o.COLUMN_TYPE.INT&&r.type!==o.COLUMN_TYPE.FLOAT)return t.shell.warning(`Non-supported type of the "${n.value.colName}" column: ${r.type}. Last row of the output dataframe "${e.name}" is analyzed.`),e.columns.names().map((t=>({idx:i-1,columnName:t})));const a=r.getRawData(),l=n.value.colValue;let u,c=0,d=Math.abs(a[0]-l);for(let t=1;t<i;++t)u=Math.abs(a[t]-l),u<d&&(d=u,c=t);return e.columns.names().map((t=>({idx:c,columnName:t})))}function qe(t,e){var n,i,s;if(t.length<1)throw new Error("Funccall array is empty.");const r=t.length,a=function(t,e){const n=[];for(const i of e)i.prop.propertyType==o.TYPE.DATA_FRAME?n.push({prop:i.prop,elements:Je(t.outputs[i.prop.name],i)}):n.push({prop:i.prop,elements:[]});return n}(t[0],e),l=function(t,e,n){var i;const s=[];for(const r of e){const e=r.prop,a=e.name;switch(e.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:s.push(o.Column.fromType(e.propertyType,a,n));break;case o.TYPE.DATA_FRAME:const l=t.outputs[a];if(r.elements)for(const t of r.elements)s.push(o.Column.fromType(null===(i=l.col(t.columnName))||void 0===i?void 0:i.type,t.columnName,n));break;default:throw new Error(ze)}}return o.DataFrame.fromColumns(s)}(t[0],a,r);for(let e=0;e<r;++e)for(const r of a){const a=r.prop,u=a.name,c=t[e];switch(a.propertyType){case o.TYPE.BIG_INT:case o.TYPE.INT:case o.TYPE.FLOAT:null===(n=l.col(u))||void 0===n||n.set(e,c.outputs[u]);break;case o.TYPE.DATA_FRAME:const t=c.outputs[u],a=t.rowCount-1;if(r.elements)for(const n of r.elements)null===(i=l.col(n.columnName))||void 0===i||i.set(e,null===(s=t.col(n.columnName))||void 0===s?void 0:s.get(-1!==n.idx?n.idx:a));break;default:throw new Error(ze)}}return l}function Ke(t,e){const n=function(t,e){return e.forEach((e=>{t.forEach((t=>{t.name===e.name&&(t.name=`${t.name} (input)`,e.name=`${e.name} (output)`)}))})),t.concat(e)}(t,e),i=n.length;if(0===i)return o.DataFrame.create();const s=o.DataFrame.fromColumns([n[0]]);for(let t=1;t<i;++t)n[t].name=s.columns.getUnusedName(n[t].name),s.columns.add(n[t]);return s}class Ze{constructor(t,e,n,i,s){Ue(s),this.samplesCount=s,this.fixedInputs=e,this.func=t;const r=function(t,e){const n=e.length,i=function(t,e){return new Ge(t,e).getConcatenatedColumns()}(t,n);return[...Array(n).keys()].map((t=>function(t,e){var n;const i=e.length,s=o.Column.fromType(t.prop.propertyType,null!==(n=t.prop.caption)&&void 0!==n?n:t.prop.name,i),r=s.getRawData(),a=t.max-t.min;for(let n=0;n<i;++n)r[n]=t.min+a*e[n];return s}(e[t],i[t])))}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.runsCount=s*(this.dimension+2),this.funcCalls=[];for(let n=0;n<this.runsCount;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}getSobolIndeces(t){const e=this.dimension,n=this.samplesCount,i=new Float32Array(e),s=new Float32Array(e),r=t.getRawData(),a=2*n;let l=0,u=0;for(let t=0;t<a;++t)l+=r[t],u+=r[t]*r[t];const c=l/a,d=u/a-c*c;if(0===d)i.fill(0),s.fill(0);else for(let t=0;t<e;++t){let e=0,o=0,a=0;for(let i=0;i<n;++i)a=r[(2+t)*n+i]-r[i],e+=r[n+i]*a,o+=a*a;i[t]=e/(n*d),s[t]=o/(2*n*d)}return{firstOrder:o.Column.fromFloat32Array(t.name,i),totalOrder:o.Column.fromFloat32Array(t.name,s)}}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield We(this.funcCalls);const t=this.variedInputs.map((t=>t.column)),e=qe(this.funcCalls,this.outputsOfInterest).columns.toList(),n=Ke(t,e);n.name=`Sensitivity Analysis of ${this.func.friendlyName}`;const i=e.map((t=>this.getSobolIndeces(t))),s=o.Column.fromStrings("input",t.map((t=>t.name))),r=[s],a=[s];for(const t of i)r.push(t.firstOrder),a.push(t.totalOrder);const l=o.DataFrame.fromColumns(r);l.name="First order Sobol' indices";const u=o.DataFrame.fromColumns(a);return u.name="Total order Sobol' indices",{funcEvalResults:n,funcCalls:this.funcCalls,firstOrderSobolIndices:l,totalOrderSobolIndices:u}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}class Xe{constructor(t,e,n,i,s){Ue(s),this.func=t;const r=function(t,e){var n;const i=[];for(const s of e){const e=o.Column.fromType(s.prop.propertyType,null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name,t),r=e.getRawData(),a=s.max-s.min;for(let e=0;e<t;++e)r[e]=s.min+a*Math.random();i.push(e)}return i}(s,n);this.dimension=n.length,this.variedInputs=[...Array(this.dimension).keys()].map((t=>({prop:n[t].prop,min:n[t].min,max:n[t].max,column:r[t]}))),this.funcCalls=[];for(let n=0;n<s;++n){const i={};for(const t of e)i[t.name]=t.value;for(const t of this.variedInputs)i[t.prop.name]=t.column.get(n);this.funcCalls.push(t.prepare(i))}this.outputsOfInterest=i}perform(){return t=this,e=void 0,i=function*(){this.funcCalls=yield We(this.funcCalls);const t=Ke(this.variedInputs.map((t=>t.column)),qe(this.funcCalls,this.outputsOfInterest).columns.toList());return t.name=`Sensitivity Analysis of ${this.func.friendlyName}`,{funcEvalResults:t,funcCalls:this.funcCalls}},new((n=void 0)||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}));var t,e,n,i}}var Qe,tn,en=n(993),nn={};nn.styleTagTransform=It(),nn.setAttributes=bt(),nn.insert=gt().bind(null,"head"),nn.domAPI=mt(),nn.insertStyleElement=Ct(),ht()(en.A,nn),en.A&&en.A.locals&&en.A.locals,function(t){t[t.COR_PLOT=.5]="COR_PLOT",t[t.PC_PLOT=.6]="PC_PLOT",t[t.GRAPH=.6]="GRAPH",t[t.BAR_CHART=.2]="BAR_CHART"}(Qe||(Qe={})),function(t){t.METHOD="`Method`",t.SAMPLES="`Samples`"}(tn||(tn={}));const on=`# Sensitivity Analysis\n\nSensitivity Analysis runs the computation multiple times with varying inputs, \nand analyzes the relationship between inputs and outputs.\n\nUse one of the following methods:\n\n* [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method) explores a function \nat randomly taken points\n\n* [Sobol](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis)\ndecomposes output variance into fractions, which can be attributed to inputs\n\n* **Grid** studies a function at the points of a grid with the specified step\n\n## Monte Carlo\n\nOnce you've chosen it in ${tn.METHOD}\n\n* Set in ${tn.SAMPLES} the number of random points \n\n* Use switchers to specify varied inputs and outputs to be analyzed\n\n* Press **Run** or <i class="fas fa-play"></i> on the top panel. You will get \n\n * [Correlation plot](https://datagrok.ai/help/visualize/viewers/correlation-plot) for exploring\ncorrelations between varied inputs and the specified outputs\n\n * [PC plot](https://datagrok.ai/help/visualize/viewers/pc-plot) visualizing multivariate data\nand providing variations of the selected inputs & outputs\n\n * [Line chart](https://datagrok.ai/help/visualize/viewers/line-chart) or \n[Scatterplot](https://datagrok.ai/help/visualize/viewers/scatter-plot) (dependently on the varied\ninputs count) showing a behavior of each output separately\n\n * [Grid](https://datagrok.ai/help/visualize/viewers/grid) containing inputs and outputs values \nof each function evaluation\n\n* Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[Sensitivity Analysis](https://datagrok.ai/help/compute/#sensitivity-analysis)\n\n## Sobol\n\nThis method performs \n[variance-based sensitivity analysis](https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis). \nIt provides the same visualizations \nas **Monte Carlo** and [bar charts](https://datagrok.ai/help/visualize/viewers/bar-chart) showing \nSobol' indices:\n\n* First-order indices indicate the contribution to the output variance of varying each input alone\n\n* Total-order indices measure the contribution to the output variance of each input,\n including all variance caused by its interactions with any other inputs\n \n ## Grid\n \n This method provides the same visualization as the previous ones. Unlike them, it evaluates a function \n at the points of uniform grid within the specified ranges.`;var sn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const rn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME],an=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.BOOL,o.TYPE.DATA_FRAME];var ln,un;!function(t){t.GRID_ANALYSIS="Grid",t.RANDOM_ANALYSIS="Monte Carlo",t.SOBOL_ANALYSIS="Sobol"}(ln||(ln={})),function(t){t.LAST_ROW="Last row",t.FIRST_ROW="First row",t.ALL_COLUMNS="",t.BY_COL_VAL="By value in column"}(un||(un={}));const cn=()=>e.div([],"sa-switch-input");class dn{static fromEmpty(e){return sn(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield oe.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(t,n,i={parentView:void 0,parentCall:void 0,configFunc:void 0}){this.func=t,this.options=i,this.generateInputFields=t=>{const n={analysisType:{input:e.choiceInput("Method",ln.RANDOM_ANALYSIS,[ln.RANDOM_ANALYSIS,ln.SOBOL_ANALYSIS,ln.GRID_ANALYSIS],(t=>{n.analysisType.value.next(t),this.updateRunWidgetsState(),this.setAnalysisInputTooltip(),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip())})),value:new c.BehaviorSubject(ln.RANDOM_ANALYSIS)},samplesCount:{input:e.intInput("Samples",10,(t=>{n.samplesCount.value=t,this.updateRunWidgetsState()})),value:10}};n.analysisType.input.root.insertBefore(cn(),n.analysisType.input.captionLabel),n.samplesCount.input.root.insertBefore(cn(),n.samplesCount.input.captionLabel);const i=(t,e)=>void 0===t.options[e]?Bt(t):Number(t.options[e]),s=(t,n,i=!0)=>{const o=e.switchInput(" ",t,n);return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch to mark input as immutable":"Switch to mark input as mutable":o.value?"Switch to mark output as not requiring analysis":"Switch to mark output as requiring analysis")),o},r=t.inputs.reduce(((t,r)=>{const l=i(r,"default");switch(r.propertyType){case o.TYPE.INT:case o.TYPE.BIG_INT:case o.TYPE.FLOAT:const u=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),d=s(!1,(t=>{f.isChanging.next(t),this.updateRunWidgetsState()})),p={type:r.propertyType,prop:r,const:{input:(()=>{var t;const n=e.intInput(null!==(t=r.caption)&&void 0!==t?t:r.name,Bt(r),(t=>f.const.value=t));return n.root.insertBefore(d.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:Bt(r)},min:{input:(()=>{var t;const n=e.floatInput(`${null!==(t=r.caption)&&void 0!==t?t:r.name} min`,i(r,"min"),(t=>f.min.value=t));return n.root.insertBefore(u.root,n.captionLabel),n.addPostfix(r.options.units),n})(),value:i(r,"min")},max:{input:(()=>{var t;const n=e.floatInput(`${null!==(t=r.caption)&&void 0!==t?t:r.name} max`,i(r,"max"),(t=>f.max.value=t));return n.addPostfix(r.options.units),n})(),value:i(r,"max")},lvl:{input:e.intInput("Samples",3,(t=>{f.lvl.value=t,this.updateRunWidgetsState()})),value:3},isChanging:new c.BehaviorSubject(!1)};[p.max.input,p.lvl.input].forEach((t=>{t.root.insertBefore(cn(),t.captionLabel),a()(t.root).removeProp("display")}));const h=[p.lvl.input];t[r.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input,...h]});const f=t[r.name];f.isChanging.subscribe((t=>{u.notify=!1,u.value=t,u.notify=!0,d.notify=!1,d.value=t,d.notify=!0})),(0,c.combineLatest)([p.isChanging,n.analysisType.value]).subscribe((([t,e])=>{t?(f.constForm.forEach((t=>a()(t.root).hide())),f.saForm.forEach((t=>a()(t.root).css("display","flex"))),h.forEach((t=>e===ln.GRID_ANALYSIS?a()(t.root).css("display","flex"):a()(t.root).hide()))):(f.constForm.forEach((t=>a()(t.root).css("display","flex"))),f.saForm.forEach((t=>a()(t.root).hide())))}));break;case o.TYPE.BOOL:const m=s(!1,(t=>{g.isChanging.next(t),this.updateRunWidgetsState()})),v={type:r.propertyType,prop:r,const:{input:(()=>{var t,n;const i=e.boolInput(`${null!==(t=r.caption)&&void 0!==t?t:r.name}`,null!==(n=Bt(r))&&void 0!==n&&n,(t=>g.const.value=t));return i.root.insertBefore(m.root,i.captionLabel),i})(),value:l},isChanging:new c.BehaviorSubject(!1),lvl:1};t[r.name]=Object.assign(Object.assign({},v),{constForm:[v.const.input],saForm:[]});const g=t[r.name];g.isChanging.subscribe((t=>{g.lvl=t?2:1}));break;default:const y=cn(),b={input:(()=>{const t=e.input.forProperty(r,void 0,{onValueChanged:t=>b.value=t.value});return t.root.insertBefore(y,t.captionLabel),t.addPostfix(r.options.units),t})(),value:Bt(r)};t[r.name]={const:b,constForm:[b.input],saForm:[],type:r.propertyType,prop:r,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),l=t.outputs.reduce(((t,n)=>{const i={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name;let a;n.propertyType===o.TYPE.DATA_FRAME?(a=e.choiceInput(r,un.LAST_ROW,[un.LAST_ROW,un.FIRST_ROW,un.BY_COL_VAL],(t=>{i.value.returning=t,i.analysisInputs.forEach((e=>{e.root.hidden=t!==un.BY_COL_VAL})),a.setTooltip(this.getOutputTooltip(r,t))})),a.setTooltip(this.getOutputTooltip(r,un.LAST_ROW))):(a=e.input.forProperty(n),a.setTooltip("Scalar")),a.addCaption(r);const l=an.includes(n.propertyType)?s(!0,(t=>{i.isInterest.next(t),i.analysisInputs.forEach((t=>{t.root.hidden=i.value.returning!==un.BY_COL_VAL})),this.updateRunWidgetsState(),n.propertyType===o.TYPE.DATA_FRAME&&a.setTooltip(t?this.getOutputTooltip(r,un.LAST_ROW):"Dataframe")}),!1).root:cn();return a.root.insertBefore(l,a.captionLabel),a})(),analysisInputs:n.propertyType===o.TYPE.DATA_FRAME?[(()=>{var t;const o=e.stringInput("Column",un.ALL_COLUMNS,(t=>{i.value.colName=t}));return o.root.insertBefore(cn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Name of column of the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe`),o})(),(()=>{var t;const o=e.floatInput("Value",0,(t=>{i.value.colValue=t}));return o.root.insertBefore(cn(),o.captionLabel),o.root.hidden=!0,o.setTooltip(`Value specifying the '${null!==(t=n.caption)&&void 0!==t?t:n.name}' dataframe row`),o})()]:[],value:{returning:un.LAST_ROW,colName:un.ALL_COLUMNS,colValue:0},isInterest:new c.BehaviorSubject(!0)};return a()(i.input.input).css("visibility","hidden"),i.prop.propertyType===o.TYPE.DATA_FRAME&&i.isInterest.subscribe((t=>{i.analysisInputs.forEach((e=>t?a()(e.root).show():a()(e.root).hide())),a()(i.input.input).css("visibility",t?"visible":"hidden")})),t[n.name]=i,t}),{});return{analysisInputs:n,inputs:r,outputs:l}},this.openedViewers=[],this.gridSubscription=null,this.store=this.generateInputFields(this.func),this.runButton=e.bigButton("Run",(()=>sn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon=e.iconFA("play",(()=>sn(this,void 0,void 0,(function*(){return yield this.runAnalysis()})))),this.runIcon.style.color="var(--green-2)",this.runIcon.classList.add("fas"),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute.md#sensitivity-analysis","_blank")}),"Open help in a new tab");const s=this.buildFormWithBtn();this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled,this.addTooltips(),this.comparisonView=n,this.comparisonView.dockManager.dock(s,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Sensitivity Analysis`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1;const r=this.comparisonView.getRibbonPanels();r.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(r),this.comparisonView.helpUrl="https://datagrok.ai/help/compute.md#sensitivity-analysis",this.tableDockNode=this.comparisonView.dockManager.findNode(this.comparisonView.grid.root);const l=e.markdown(on);l.style.padding="10px",l.style.overflow="auto",this.helpMdNode=this.comparisonView.dockManager.dock(l,o.DOCK_TYPE.FILL,this.tableDockNode,"About")}closeOpenedViewers(){for(const t of this.openedViewers)t.close();this.openedViewers.splice(0),this.helpMdNode&&(this.helpMdNode.detachFromParent(),this.helpMdNode.container.destroy(),this.helpMdNode=void 0),this.gridSubscription&&(this.gridSubscription.unsubscribe(),this.gridSubscription=null)}getFuncCallCount(t,e){let n=0;switch(t.analysisType.value.value){case ln.GRID_ANALYSIS:let i=1;const s=t=>t.type===o.TYPE.INT||t.type===o.TYPE.BIG_INT||t.type===o.TYPE.FLOAT;for(const t of Object.values(e))t.isChanging.value&&(i*=s(t)?t.lvl.value:t.lvl,++n);return 0===n?0:i;case ln.RANDOM_ANALYSIS:return t.samplesCount.value;case ln.SOBOL_ANALYSIS:for(const t of Object.keys(e))e[t].isChanging.value&&++n;return 0===n?0:(n+2)*t.samplesCount.value;default:return 0}}getFuncCallCountAsString(){if(!this.canEvaluationBeRun())return"0";const t=this.getFuncCallCount(this.store.analysisInputs,this.store.inputs);return t<1e3?String(t):t<1e6?String(Math.ceil(t/10)/100)+"k":t<1e9?String(Math.ceil(t/1e4)/100)+"m":String(Math.ceil(t/1e7)/100)+"b"}updateRunWidgetsState(){this.runButton.textContent=`Run (${this.getFuncCallCountAsString()})`,this.runButton.disabled=!this.canEvaluationBeRun(),this.runIcon.hidden=this.runButton.disabled}buildFormWithBtn(){let t="Misc";const n=Object.values(this.store.inputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(...i.constForm.map((t=>t.root)),...i.saForm.map((t=>t.root))),n}),e.div([this.store.analysisInputs.analysisType.input,this.store.analysisInputs.samplesCount.input],{style:{"overflow-y":"scroll",width:"100%"}}));a()(n).addClass("ui-form");const i=e.h2("Outputs");n.appendChild(i),t="Misc";const o=Object.values(this.store.outputs).reduce(((n,i)=>{const o=i.prop;return o.category!==t&&(n.append(e.h2(o.category)),t=o.category),n.append(i.input.root,...i.analysisInputs.map((t=>t.root))),n}),n);this.store.analysisInputs.analysisType.value.subscribe((t=>{t===ln.GRID_ANALYSIS?a()(this.store.analysisInputs.samplesCount.input.root).hide():(a()(i).show(),a()(o).show(),a()(this.store.analysisInputs.samplesCount.input.root).show())}));let s=!1;for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value){s=!0;break}s||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0),this.updateRunWidgetsState();const r=e.buttonsInput([this.runButton]);return n.appendChild(r),a()(n).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),n}setAnalysisInputTooltip(){let t;switch(this.store.analysisInputs.analysisType.value.value){case ln.GRID_ANALYSIS:t="Grid analysis: the function is evaluated with respect to the selected inputs varying within the specified ranges";break;case ln.RANDOM_ANALYSIS:t="Monte Carlo simulation: the function is evaluated with respect to random variation of the selected inputs within the specified ranges";break;case ln.SOBOL_ANALYSIS:t="Variance-based sensitivity analysis: the Sobol' indices are computed";break;default:t="Unknown method!"}this.store.analysisInputs.analysisType.input.setTooltip(t)}getOutputTooltip(t,e){switch(e){case un.FIRST_ROW:return`To analyze first row of the '${t}' dataframe`;case un.LAST_ROW:return`To analyze last row of the '${t}' dataframe`;case un.BY_COL_VAL:return`To analyze "${t}"'s row defined by custom value in column`;default:return""}}samplesCountTooltip(){switch(this.store.analysisInputs.analysisType.value.value){case ln.RANDOM_ANALYSIS:return"Input sets count";case ln.SOBOL_ANALYSIS:return"Sample size for the Sobol' indices computation";default:return"Unknown method!"}}addTooltips(){var t;this.setAnalysisInputTooltip(),e.tooltip.bind(this.runButton,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),e.tooltip.bind(this.runIcon,(()=>`Run sensitivity analysis: the function is evaluated ${this.getFuncCallCount(this.store.analysisInputs,this.store.inputs)} times`)),this.store.analysisInputs.samplesCount.input.setTooltip(this.samplesCountTooltip());for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e].prop.propertyType;if(n===o.TYPE.BOOL||n===o.TYPE.STRING)continue;const i=this.store.inputs[e],s=null!==(t=i.prop.caption)&&void 0!==t?t:i.prop.name;i.const.input.setTooltip(`'${s}' value`),i.min.input.setTooltip(`Min value of '${s}'`),i.max.input.setTooltip(`Max value of '${s}'`),i.lvl.input.setTooltip(`Number of samples along the axis '${s}'`)}}isAnyInputSelected(){for(const t of Object.keys(this.store.inputs))if(this.store.inputs[t].isChanging.value)return!0;return!1}isAnyOutputSelected(){for(const t of Object.keys(this.store.outputs))if(this.store.outputs[t].isInterest.value)return!0;return!1}canEvaluationBeRun(){return this.isAnyInputSelected()&&this.isAnyOutputSelected()}runAnalysis(){return sn(this,void 0,void 0,(function*(){if(this.canEvaluationBeRun())switch(this.store.analysisInputs.analysisType.value.value){case ln.GRID_ANALYSIS:yield this.runGridAnalysis();break;case ln.RANDOM_ANALYSIS:yield this.runRandomAnalysis();break;case ln.SOBOL_ANALYSIS:yield this.runSobolAnalysis()}}))}getFixedInputColumns(t){return Object.values(this.store.inputs).filter((t=>!rn.includes(t.type)||!t.isChanging.value)).map((e=>{var n;return o.Column.fromList(e.type,null!==(n=e.prop.caption)&&void 0!==n?n:e.prop.name,Array(t).fill(e.const.value))}))}runSobolAnalysis(){return sn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new Ze(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform();this.closeOpenedViewers();const l=r.funcEvalResults,u=r.funcCalls,c=r.firstOrderSobolIndices,d=r.totalOrderSobolIndices,p=c.columns.names();this.comparisonView.dataFrame=l;const h=l.columns.names(),f=this.getFixedInputColumns(l.rowCount);for(const t of f)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([h[0]]),this.comparisonView.grid.columns.setVisible(h),this.comparisonView.grid.props.rowHeight=25;const m=o.Viewer.correlationPlot(l,{xColumnNames:h,yColumnNames:h}),v=this.comparisonView.dockManager.dock(m,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Qe.COR_PLOT);this.openedViewers.push(m);const g=o.Viewer.pcPlot(l,{columnNames:h});this.comparisonView.dockManager.dock(g,o.DOCK_TYPE.DOWN,v,"",Qe.PC_PLOT),this.openedViewers.push(g);const y=this.getOutputNameForScatterPlot(h,l,n.variedInputs.length),b=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(h)):o.Viewer.scatterPlot(l,this.getScatterOpt(h,y));this.openedViewers.push(b),this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Qe.GRAPH);const A=o.Viewer.barChart(c,this.getBarChartOpt(c.name,p[0],y)),C=this.comparisonView.dockManager.dock(A,o.DOCK_TYPE.RIGHT,void 0,"",Qe.BAR_CHART),w=o.Viewer.barChart(d,this.getBarChartOpt(d.name,p[0],y));this.comparisonView.dockManager.dock(w,o.DOCK_TYPE.DOWN,C),this.openedViewers=this.openedViewers.concat([A,w]),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!rn.includes(this.store.inputs[t].type)||!this.store.inputs[t].isChanging.value))}getVariedInputs(){return Object.keys(this.store.inputs).filter((t=>!!rn.includes(this.store.inputs[t].type)&&this.store.inputs[t].isChanging.value))}runRandomAnalysis(){return sn(this,void 0,void 0,(function*(){const n={func:this.func,fixedInputs:this.getFixedInputs().map((t=>({name:t,value:this.store.inputs[t].const.value}))),variedInputs:this.getVariedInputs().map((t=>{const e=this.store.inputs[t];return{prop:e.prop,min:e.min.value,max:e.max.value}})),samplesCount:this.store.analysisInputs.samplesCount.value||1},i=this.getOutputsOfInterest(),s=new Xe(n.func,n.fixedInputs,n.variedInputs,i,n.samplesCount),r=yield s.perform(),l=r.funcEvalResults,u=r.funcCalls;this.closeOpenedViewers(),this.comparisonView.dataFrame=l;const c=l.columns.names(),d=this.getFixedInputColumns(l.rowCount);for(const t of d)t.name=l.columns.getUnusedName(`${t.name} (fixed)`),l.columns.add(t);this.comparisonView.grid.columns.setVisible([c[0]]),this.comparisonView.grid.columns.setVisible(c),this.comparisonView.grid.props.rowHeight=25;const p=o.Viewer.correlationPlot(l,{xColumnNames:c,yColumnNames:c}),h=this.comparisonView.dockManager.dock(p,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Qe.COR_PLOT);this.openedViewers.push(p);const f=o.Viewer.pcPlot(l,{columnNames:c});this.comparisonView.dockManager.dock(f,o.DOCK_TYPE.DOWN,h,"",Qe.PC_PLOT),this.openedViewers.push(f);const m=this.getOutputNameForScatterPlot(c,l,n.variedInputs.length),v=1===n.variedInputs.length?o.Viewer.lineChart(l,this.getLineChartOpt(c)):o.Viewer.scatterPlot(l,this.getScatterOpt(c,m));this.openedViewers.push(v),this.comparisonView.dockManager.dock(v,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Qe.GRAPH),this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root}))}))}runGridAnalysis(){return sn(this,void 0,void 0,(function*(){var n,i;const s=Object.keys(this.store.inputs).reduce(((t,e)=>{switch(this.store.inputs[e].type){case o.TYPE.INT:case o.TYPE.BIG_INT:const n=this.store.inputs[e],i=(n.max.value-n.min.value)/(n.lvl.value-1);t[e]=n.isChanging.value?Array.from({length:n.lvl.value},((t,e)=>Math.round(n.min.value+e*i))):[n.const.value];break;case o.TYPE.FLOAT:const s=this.store.inputs[e],r=(s.max.value-s.min.value)/(s.lvl.value-1);t[e]=s.isChanging.value?Array.from({length:s.lvl.value},((t,e)=>s.min.value+e*r)):[s.const.value];break;case o.TYPE.BOOL:const a=this.store.inputs[e];t[e]=a.isChanging.value?[a.const.value,!a.const.value]:[a.const.value];break;default:const l=this.store.inputs[e];t[e]=[l.const.value]}return t}),{});let r=Object.values(s)[0].map((t=>[t]));for(let t=1;t<Object.values(s).length;t++){const e=Object.values(s)[t],n=[];for(const t of r)for(const i of e)n.push([...t,i]);r=n}const l=r.map((t=>this.func.prepare(this.func.inputs.map(((t,e)=>({name:t.name,idx:e}))).reduce(((e,{name:n,idx:i})=>(e[n]=t[i],e)),{})))),u=yield We(l);this.closeOpenedViewers();const c=[],d=u.length,p=this.getFixedInputColumns(d);for(const t of Object.keys(this.store.inputs)){const e=this.store.inputs[t],i=e.prop;e.isChanging.value&&c.push(o.Column.fromType(i.propertyType,null!==(n=i.caption)&&void 0!==n?n:i.name,d))}const h=[...c],f=h.length,m=o.DataFrame.fromColumns([h[0]]);for(let t=1;t<f;++t)h[t].name=m.columns.getUnusedName(h[t].name),m.columns.add(h[t]);for(let t=0;t<d;++t)for(const e of Object.keys(this.store.inputs)){const n=this.store.inputs[e],o=n.prop;n.isChanging.value&&m.set(null!==(i=o.caption)&&void 0!==i?i:o.name,t,u[t].inputs[e])}const v=this.getOutputsOfInterest(),g=qe(u,v).columns;for(const t of g)h.forEach((e=>{e.name===t.name&&(e.name=`${e.name} (input)`,t.name=`${t.name} (output)`)})),t.name=m.columns.getUnusedName(t.name),m.columns.add(t);const y=m.columns.names();for(const t of p)t.name=m.columns.getUnusedName(`${t.name} (fixed)`),m.columns.add(t);this.comparisonView.dataFrame=m,this.gridSubscription=this.comparisonView.grid.onCellClick.subscribe((n=>{var i;const s=u[null!==(i=n.tableRowIndex)&&void 0!==i?i:0],r=[...s.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),l=o.HtmlTable.create(r,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,s.outputs[t.property.name],t.property.options.units]})).root,c=[...s.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,r=s.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,r);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d,p;r.length>0?(p=1,d=Object.assign({"Output scalars":[l]},c)):(p=0,d=Object.assign({},c));const h=e.accordion();a()(h.root).css({width:"100%"}),Object.entries(d).map((t=>{h.addPane(t[0],(()=>e.divV(t[1])))})),h.panes[p].expanded=!0,t.shell.o=h.root})),this.comparisonView.grid.columns.setVisible([y[0]]),this.comparisonView.grid.columns.setVisible(y),this.comparisonView.grid.props.rowHeight=25;const b=o.Viewer.correlationPlot(m,{xColumnNames:y,yColumnNames:y}),A=this.comparisonView.dockManager.dock(b,o.DOCK_TYPE.LEFT,this.tableDockNode,"",Qe.COR_PLOT);this.openedViewers.push(b);const C=o.Viewer.pcPlot(m,{columnNames:y});this.comparisonView.dockManager.dock(C,o.DOCK_TYPE.DOWN,A,"",Qe.PC_PLOT),this.openedViewers.push(C);const w=this.getOutputNameForScatterPlot(y,m,c.length),I=1===c.length?o.Viewer.lineChart(m,this.getLineChartOpt(y)):o.Viewer.scatterPlot(m,this.getScatterOpt(y,w));this.openedViewers.push(I),this.comparisonView.dockManager.dock(I,o.DOCK_TYPE.DOWN,this.tableDockNode,"",Qe.GRAPH)}))}getOutputNameForScatterPlot(t,e,n){var i,o,s,r;for(let a=n;a<t.length;++a)if((null!==(o=null===(i=e.col(t[a]))||void 0===i?void 0:i.min)&&void 0!==o?o:0)<(null!==(r=null===(s=e.col(t[a]))||void 0===s?void 0:s.max)&&void 0!==r?r:0))return t[a];return t[n]}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];if(n.isInterest.value){let e;switch(n.value.returning){case un.LAST_ROW:e=-1;break;case un.FIRST_ROW:e=0;break;default:e=null}t.push({prop:n.prop,value:{row:e,colName:n.value.colName,colValue:n.value.colValue}})}}return t}getScatterOpt(t,e){return{xColumnName:t[0],yColumnName:t[1],colorColumnName:e,sizeColumnName:e,markerMaxSize:12,jitterSize:5}}getLineChartOpt(t){return{xColumnName:t[0],yColumnNames:t.slice(1,Math.min(t.length,8)),markerSize:1,markerType:o.MARKER_TYPE.GRADIENT,multiAxis:!0}}getBarChartOpt(t,e,n){return{description:t,splitColumnName:e,valueColumnName:n,valueAggrType:o.AGG.AVG,showTitle:!1,showCategorySelector:!1,showStackSelector:!1,showValueAxis:!1}}}var pn;!function(t){t.NELDER_MEAD="Nelder-Mead",t.GRAD_DESC="Gradient descent"}(pn||(pn={}));const hn=new Map([[pn.NELDER_MEAD,"The Nelder-Mead method"],[pn.GRAD_DESC,"The gradient descent method"]]);var fn;!function(t){t.MAD="MAD",t.RMSE="RMSE"}(fn||(fn={}));const mn=new Map([[fn.MAD,"Maximum absolute deviation"],[fn.RMSE,"Root mean square error"]]);var vn,gn,yn,bn;!function(t){t[t.LOSS_COL_WIDTH=60]="LOSS_COL_WIDTH",t[t.ROW_HEIGHT=180]="ROW_HEIGHT",t[t.LOSS_GRAPH_WIDTH=360]="LOSS_GRAPH_WIDTH",t[t.GOF_VIEWER_WIDTH=240]="GOF_VIEWER_WIDTH"}(vn||(vn={})),function(t){t.ITER="Iteration",t.LOSS="Loss",t.LOSS_GRAPH="Fitting profile",t.TARGET="Target",t.FIT="Fit",t.METHOD="method",t.VALUE="Value",t.OBJECTIVE="Target",t.SAMPLES="samples",t.ID="id",t.OBTAINED="Simulation",t.LOSS_LOW="loss",t.SIMILARITY="similarity"}(gn||(gn={})),function(t){t.GOAL="`Goal`",t.FIT="`Fit`",t.MIN="`min`",t.MAX="`max`",t.TARGET="`Target`",t.METHOD="`method`",t.CONTEXT="`Context Panel (F4)`",t.SAMPLES="`samples`",t.LOSS="`loss`",t.SIMILARITY="`similarity`"}(yn||(yn={})),function(t){t[t.SIMILARITY_MIN=0]="SIMILARITY_MIN",t[t.SIMILARITY_DEFAULT=.01]="SIMILARITY_DEFAULT",t[t.SAMPLES=10]="SAMPLES"}(bn||(bn={}));const An=`# Fitting\n\nUse fitting to solve an inverse problem: find input conditions leading to specified output constraints. \nIt computes inputs minimizing deviation measured by [loss function](https://en.wikipedia.org/wiki/Loss_function).\n\n1. In the ${yn.FIT} block, use switchers to specify inputs to be found:\n * Set ${yn.MIN} and ${yn.MAX} values for each selected item. They define the variation range\n * Set values of all other inputs\n\n2. Set output constraints in the ${yn.TARGET} block:\n * Use switchers to specify target outputs\n * Set target value for each selected item\n\n3. Choose ${yn.METHOD}. Press <i class="grok-icon fal fa-cog"></i> to specify its settings.\n\n4. Specify the loss function type (in the ${yn.LOSS} field).\n\n5. Enter the number of points to be found (in the ${yn.SAMPLES} field).\n\n6. Set the maximum scaled deviation between similar fitted points (in the ${yn.SIMILARITY} field).\n\n7. Press the "Run" icon <i class="fas fa-play"></i> on the top panel to perform fitting. You will get a\n[grid](https://datagrok.ai/help/visualize/viewers/grid) containing \n\n * loss function values\n * fitted inputs\n * viewers visualizing the goodness of fit:\n * [line chart](https://datagrok.ai/help/visualize/viewers/line-chart) showing the loss function minimization\n\n8. Open ${yn.CONTEXT}. You will get the function run corresponding to the selected grid row.\n\n9. Press <i class="grok-icon fal fa-question"></i> on the top panel to learn more about \n[parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization).\n\n# Learn more\n\n* [Parameters optimization](https://datagrok.ai/help/compute/#input-parameter-optimization)\n* [Nelder-Mead method](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method)`;class Cn extends Error{constructor(t){super(t)}}function wn(t){return new Promise(((e,n)=>setTimeout(e,t)))}function In(t,e){const n=t.getRawData(),i=e.getRawData(),o=e.length,s=Math.min(t.length,o),r=new Uint32Array(s);let a=0,l=0,u=0;for(let t=0;t<s;++t){for(;;){if(l=Math.abs(i[a]-n[t]),++a,!(a<o)){--a;break}if(u=Math.abs(i[a]-n[t]),u>l){--a;break}l=u}r[t]=a}return r}function Tn(t,e,n,i){const o=e.col(t),s=n.col(t);if(null===o)throw new Cn(`no "${t}" column in the target dataframe "${e.name}"`);if(null===s)throw new Cn(`no "${t}" column in the output dataframe "${n.name}"`);const r=In(o,s),a=e.columns,l=a.length,u=new Float32Array((l-1)*r.length);let c=0;for(const e of a)if(e.name!==t){const t=n.col(e.name);if(null===t)throw new Cn(`no "${e.name}" column in the output dataframe "${n.name}"`);const o=t.getRawData(),s=e.getRawData();if(i){const t=e.stats.max-e.stats.min,n=t>0?t:1;r.forEach(((t,e)=>{u[c]=(o[t]-s[e])/n,++c}))}else r.forEach(((t,e)=>{u[c]=o[t]-s[e],++c}))}return u}var En=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const xn=new Map([["tolerance",{default:1e-6,min:1e-20,max:.1}],["maxIter",{default:50,min:1,max:1e4}],["nonZeroParam",{default:1e-4,min:1e-20,max:.1}],["initialScale",{default:.02,min:1e-20,max:.1}],["scaleReflaction",{default:1,min:1,max:2}],["scaleExpansion",{default:2,min:1,max:2}],["scaleContraction",{default:-.5,min:-.5,max:0}]]),Rn=new Map([["tolerance","tolerance"],["maxIter","max iterations"],["nonZeroParam","non-zero param"],["initialScale","initial scale"],["scaleReflaction","scale reflection"],["scaleExpansion","scale expansion"],["scaleContraction","scale contraction"]]);function Sn(t,e,n,i){for(let o=0;o<e;o++){let s=0;for(let t=0;t<e+1;t++)t!=n&&(s+=i[t][o]);t[o]=s/e}}function On(t,e,n,i,o,s,r,a){for(let l=0;l<s;l++)e[l]=t[l],e[l]+=o*(t[l]-i[n][l]),e[l]<r[l]?e[l]=r[l]:e[l]>a[l]&&(e[l]=a[l])}const Pn=function(t,e,n,i,o){return En(this,void 0,void 0,(function*(){const s=n.get("tolerance"),r=n.get("maxIter"),a=n.get("scaleReflaction"),l=n.get("scaleExpansion"),u=n.get("scaleContraction"),c=e.length+1,d=e.length,[p,h]=yield function(t,e,n,i,o){return En(this,void 0,void 0,(function*(){const s=n.length+1,r=n.length,a=e.get("nonZeroParam"),l=e.get("initialScale"),u=new Array(s),c=new Array(s);for(let e=0;e<s;e++){u[e]=new Float32Array(r);for(let t=0;t<r;t++)u[e][t]=n[t],0!=e&&e-1===t&&(0==n[t]?u[e][t]=a:u[e][t]+=l*n[e-1],u[e][t]<i[t]?u[e][t]=i[t]:u[e][t]>o[t]&&(u[e][t]=o[t]));c[e]=yield t(u[e])}return[u,c]}))}(t,n,e,i,o),f=new Array(c);for(let t=0;t<c;t++)f[t]=t;const m=f.length-1;let v=0,g=0,y=0,b=0;const A=new Float32Array(d),C=new Float32Array(d),w=new Float32Array(d),I=new Float32Array(d),T=new Array(r);if(c>1){for(;f.sort(((t,e)=>h[t]-h[e])),!(v>r);){if(0==v&&(g=h[0],y=2*h[f[0]]),T[v]=g,++v,g=h[f[0]],y-g>s)b=0;else if(++b,b>2*c)break;y=g,Sn(A,d,f[m],p),On(A,C,f[m],p,a,d,i,o);const e=yield t(C);if(e<h[f[m]]){On(A,w,f[m],p,l,d,i,o);const n=yield t(w);if(n<e){h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=w[t];continue}h[f[m]]=e;for(let t=0;t<d;t++)p[f[m]][t]=C[t];continue}On(A,I,f[m],p,u,d,i,o);const n=yield t(I);if(!(n<h[f[m]]))break;h[f[m]]=n;for(let t=0;t<d;t++)p[f[m]][t]=I[t]}for(let t=v;t<r;t++)T[t]=h[f[0]]}return{point:p[f[0]],cost:h[f[0]],iterCosts:T,iterCount:v-1}}))};function Fn(t,e,n){const i=e-n,o=new Array(t);for(let e=0;e<t;e++){const t=Math.random();o[e]=n+t*i}return o}function _n(t,e,n,i){return s=this,r=arguments,l=function*(t,e,n,i,s=1){const r=function(t,e,n){const i=e.length,o=new Array(t);for(let e=0;e<t;e++)o[e]=new Float32Array(i);for(let s=0;s<i;s++)if(e[s]===n[s])for(let n=0;n<t;n++)o[n][s]=e[s];else{const i=Fn(t,e[s],n[s]);for(let e=0;e<t;e++)o[e][s]=i[e]}return o}(s,n,e),a=[],l=[],u=[];let c=0,d=null;const p=o.TaskBarProgressIndicator.create("Fitting...");let h;for(h=0;h<s;++h)try{if(a.push(yield Pn(t,r[h],i,e,n)),p.update(100*(h+1)/s,"Fitting..."),yield wn(10),p.canceled)break}catch(t){if(p.close(),t instanceof Cn)throw new Error(`Inconsistent dataframes: ${t.message}`);++c,l.push(t instanceof Error?t.message:"Platform issue"),u.push(r[h])}if(p.close(),c>0){const t=n.length,e=new Array(t);for(let n=0;n<t;++n)e[n]=new Float32Array(c);u.forEach(((t,n)=>t.forEach(((t,i)=>e[i][n]=t)))),d=o.DataFrame.fromColumns(e.map(((t,e)=>o.Column.fromFloat32Array(`arg${e}`,t)))),d.columns.add(o.Column.fromStrings("Issue",l))}return{extremums:a,fails:d}},new((a=void 0)||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())}));var s,r,a,l}var kn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};const Mn=[o.TYPE.INT,o.TYPE.BIG_INT,o.TYPE.FLOAT,o.TYPE.DATA_FRAME],Bn=()=>e.div([],"sa-switch-input");class Ln{static fromEmpty(e){return kn(this,arguments,void 0,(function*(e,n={parentView:void 0,parentCall:void 0}){const i=[...t.shell.views].find((t=>t.type===v)),o=yield oe.fromComparedRuns([],e,{parentView:i,parentCall:n.parentCall});t.shell.addView(o),new this(e,o,n)}))}constructor(n,i,s={parentView:void 0,parentCall:void 0,configFunc:void 0}){if(this.func=n,this.options=s,this.generateInputFields=t=>{const n=(t,e)=>void 0===t.options[e]?t.defaultValue:Number(t.options[e]),i=(t,n,i=!0)=>{const o=e.switchInput(" ",t,n);return a()(o.root).addClass("sa-switch-input"),a()(o.captionLabel).hide(),e.tooltip.bind(o.root,(()=>i?o.value?"Switch OFF fitting the input":"Switch ON fitting the input":o.value?"Mark the output as not a target":"Mark the output as a target")),o},s=t.inputs.reduce(((t,s)=>{var r;const l=n(s,"default");if(s.propertyType===o.TYPE.FLOAT){const o=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),u=i(!1,(t=>{h.isChanging.next(t),this.updateApplicabilityState()})),d=null!==(r=s.caption)&&void 0!==r?r:s.name,p={type:s.propertyType,prop:s,const:{input:(()=>{const t=e.floatInput(d,l,(t=>{h.const.value=t,this.updateApplicabilityState()}));return t.root.insertBefore(u.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Value of '${d}'`),t.nullable=!1,t})(),value:l},min:{input:(()=>{const t=e.floatInput(`${d} (min)`,n(s,"min"),(t=>{h.min.value=t,this.updateApplicabilityState()}));return t.addValidator((t=>Number(t)>p.max.value?"Greater than max":null)),t.root.insertBefore(o.root,t.captionLabel),t.addPostfix(s.options.units),t.setTooltip(`Min value '${d}'`),t.nullable=!1,t})(),value:n(s,"min")},max:{input:(()=>{const t=e.floatInput(`${d} (max)`,n(s,"max"),(t=>{h.max.value=t,this.updateApplicabilityState()}));return t.addValidator((t=>Number(t)<p.min.value?"Smaller than min":null)),t.addPostfix(s.options.units),t.setTooltip(`Max value of '${d}'`),t.nullable=!1,t})(),value:n(s,"max")},isChanging:new c.BehaviorSubject(!1)};[p.max.input].forEach((t=>{t.root.insertBefore(Bn(),t.captionLabel),a()(t.root).removeProp("display")})),t[s.name]=Object.assign(Object.assign({},p),{constForm:[p.const.input],saForm:[p.min.input,p.max.input]});const h=t[s.name];h.isChanging.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,u.notify=!1,u.value=t,u.notify=!0})),(0,c.combineLatest)([p.isChanging]).subscribe((([t])=>{t?(h.constForm.forEach((t=>a()(t.root).hide())),h.saForm.forEach((t=>a()(t.root).css("display","flex")))):(h.constForm.forEach((t=>a()(t.root).css("display","flex"))),h.saForm.forEach((t=>a()(t.root).hide())))}))}else{const n=Bn(),i={input:(()=>{var t;const o=e.input.forProperty(s);return o.caption=null!==(t=s.caption)&&void 0!==t?t:s.name,o.onInput((()=>{i.value=o.value,this.updateApplicabilityState()})),o.root.insertBefore(n,o.captionLabel),o.addPostfix(s.options.units),o.nullable=!1,o})(),value:l};i.input.value=l,t[s.name]={const:i,constForm:[i.input],saForm:[],type:s.propertyType,prop:s,isChanging:new c.BehaviorSubject(!1)}}return t}),{}),r=t.outputs.filter((t=>Mn.includes(t.propertyType))).reduce(((t,n)=>{const s={prop:n,input:(()=>{var t;const r=null!==(t=n.caption)&&void 0!==t?t:n.name,a=e.input.forProperty(n);a.addCaption(r),a.value=0,a.setTooltip(this.toSetSwitched?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.input.hidden=!this.toSetSwitched,a.nullable=!1,e.tooltip.bind(a.captionLabel,n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),a.onChanged((()=>{if(s.target=a.value,n.propertyType===o.TYPE.DATA_FRAME)if(s.target){const t=[];for(const e of a.value.columns)e.type!==o.COLUMN_TYPE.FLOAT&&e.type!==o.COLUMN_TYPE.INT||t.push(e.name);s.colNameInput.items=t,s.colNameInput.value=t[0]}else s.colNameInput.items=[null],s.colNameInput.value=null;this.updateApplicabilityState()})),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!this.toSetSwitched);const l=i(this.toSetSwitched,(t=>{s.isInterest.next(t),this.updateApplicabilityState(),a.input.hidden=!t,a.setTooltip(t?"Target value":n.propertyType===o.TYPE.DATA_FRAME?"Output dataframe":"Output scalar"),n.propertyType===o.TYPE.DATA_FRAME&&(a.root.lastElementChild.hidden=!t,s.colNameInput.root.hidden=!t)}),!1).root;return a.root.insertBefore(l,a.captionLabel),a})(),colNameInput:(()=>{const t=e.choiceInput("argument",null,[null],(t=>s.colName=t));return t.setTooltip("Column with argument values"),t.root.insertBefore(Bn(),t.captionLabel),t.root.hidden=n.propertyType!==o.TYPE.DATA_FRAME||!this.toSetSwitched,this.toSetSwitched=!1,t.nullable=!1,t})(),isInterest:new c.BehaviorSubject(this.toSetSwitched),target:n.propertyType!==o.TYPE.DATA_FRAME?0:null,colName:""};return t[n.name]=s,t}),{});return{inputs:s,outputs:r}},this.readyToRun=!1,this.runIcon=e.iconFA("play",(()=>kn(this,void 0,void 0,(function*(){this.readyToRun&&(yield this.runOptimization())})))),this.helpIcon=e.iconFA("question",(()=>{window.open("https://datagrok.ai/help/compute/#input-parameter-optimization","_blank")}),"Open help in a new tab"),this.showFailsBtn=e.button("Issues",(()=>{if(this.method!==pn.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);this.showNelderMeadFails()}),"Show issues"),this.gridClickSubscription=null,this.gridCellChangeSubscription=null,this.failsDF=null,this.toSetSwitched=!0,this.samplesCount=bn.SAMPLES,this.samplesCountInput=e.input.forProperty(o.Property.fromOptions({name:gn.SAMPLES,inputType:"Int",defaultValue:this.samplesCount,min:1,max:1e3})),this.loss=fn.RMSE,this.lossInput=e.choiceInput(gn.LOSS_LOW,this.loss,[fn.MAD,fn.RMSE],(()=>{this.loss=this.lossInput.value,this.lossInput.setTooltip(mn.get(this.loss))})),this.similarity=bn.SIMILARITY_DEFAULT,this.similarityInput=e.input.forProperty(o.Property.fromOptions({name:gn.SIMILARITY,inputType:"Float",defaultValue:this.similarity,min:0})),this.helpDN=void 0,this.method=pn.NELDER_MEAD,this.methodInput=e.choiceInput(gn.METHOD,this.method,[pn.NELDER_MEAD],(()=>{this.method=this.methodInput.value,this.showHideSettingInputs(),this.methodInput.setTooltip(hn.get(this.method))})),this.nelderMeadSettings=new Map,this.gradDescentSettings={iterCount:10,learningRate:1e-4},this.settingsInputs=new Map,this.store=this.generateInputFields(this.func),this.fittingSettingsIcon=e.iconFA("cog",(()=>{const t=this.fittingSettingsDiv.hidden;this.fittingSettingsDiv.hidden=!t}),"Modify fitting settings"),this.fittingSettingsDiv=e.divV([]),!this.isOptimizationApplicable(n))return t.shell.warning("Fitting is not applicable: the function has no scalar outputs."),void i.close();const r=this.buildForm();this.comparisonView=i,this.comparisonView.dockManager.dock(r,o.DOCK_TYPE.LEFT,null,`${this.func.name} - Fitting`,.25),this.comparisonView.grid.columns.byName("Run name").visible=!1,xn.forEach(((t,e)=>this.nelderMeadSettings.set(e,t.default)));const l=this.comparisonView.getRibbonPanels();l.push([this.helpIcon,this.runIcon]),this.comparisonView.setRibbonPanels(l),this.fittingSettingsDiv.hidden=!0,this.comparisonView.name=this.comparisonView.name.replace("comparison","fitting"),this.comparisonView.helpUrl="https://datagrok.ai/help/compute/#input-parameter-optimization";const u=e.markdown(An);u.style.padding="10px",u.style.overflow="auto",this.helpDN=this.comparisonView.dockManager.dock(u,o.DOCK_TYPE.FILL,this.comparisonView.dockManager.findNode(this.comparisonView.grid.root),"About"),this.methodInput.setTooltip(hn.get(this.method)),e.tooltip.bind(this.methodInput.captionLabel,"Method for minimizing the loss function"),this.lossInput.setTooltip(mn.get(this.loss)),e.tooltip.bind(this.lossInput.captionLabel,"Loss function type"),this.showFailsBtn.style.padding="0px",this.samplesCountInput.addCaption(gn.SAMPLES),this.samplesCountInput.onChanged((()=>{this.samplesCount=this.samplesCountInput.value,this.updateApplicabilityState()})),this.samplesCountInput.setTooltip("Number of points to be found"),this.similarityInput.onChanged((()=>{this.similarity=this.similarityInput.value,this.updateApplicabilityState()})),this.similarityInput.addCaption(gn.SIMILARITY),this.similarityInput.setTooltip("The higher the value, the fewer points will be found"),e.tooltip.bind(this.similarityInput.captionLabel,"Max scaled deviation between similar fitted points"),this.updateRunIconStyle(),this.updateRunIconDisabledTooltip("Select inputs for fitting"),this.runIcon.classList.add("fas")}isOptimizationApplicable(t){for(const n of t.outputs)if((e=n).propertyType===o.TYPE.INT||e.propertyType===o.TYPE.FLOAT||e.propertyType===o.TYPE.DATA_FRAME)return!0;var e;return!1}generateNelderMeadSettingsInputs(){const t=[];xn.forEach(((n,i)=>{const s=e.input.forProperty(o.Property.fromOptions({name:Rn.get(i),inputType:"maxIter"!==i?"Float":"Int",defaultValue:n.default,min:n.min,max:n.max}));s.addCaption(Rn.get(i)),s.nullable=!1,s.onChanged((()=>{this.nelderMeadSettings.set(i,s.value),this.updateApplicabilityState()})),t.push(s)})),this.settingsInputs.set(pn.NELDER_MEAD,t)}areNelderMeadSettingsCorrect(){for(const[t,e]of this.nelderMeadSettings)if(null==e||e>xn.get(t).max||e<xn.get(t).min)return this.updateRunIconDisabledTooltip(`Invalid "${t}": check method settings`),!1;return!0}generateGradDescentSettingsInputs(){const t=e.input.forProperty(o.Property.fromOptions({name:"iterations",inputType:"Int",defaultValue:this.gradDescentSettings.iterCount,min:1,max:1e4}));t.onChanged((()=>this.gradDescentSettings.iterCount=t.value));const n=e.input.forProperty(o.Property.fromOptions({name:"Learning rate",inputType:"Float",defaultValue:this.gradDescentSettings.learningRate,min:1e-6,max:1e3}));n.onChanged((()=>this.gradDescentSettings.learningRate=n.value)),this.settingsInputs.set(pn.GRAD_DESC,[t,n])}areGradDescentSettingsCorrect(){return!1}areMethodSettingsCorrect(){switch(this.method){case pn.NELDER_MEAD:return this.areNelderMeadSettingsCorrect();case pn.GRAD_DESC:return this.areGradDescentSettingsCorrect();default:return!0}}generateSettingInputs(){this.generateNelderMeadSettingsInputs(),this.generateGradDescentSettingsInputs()}showHideSettingInputs(){this.settingsInputs.forEach(((t,e)=>t.forEach((t=>t.root.hidden=e!==this.method))))}buildForm(){const t=e.h1(gn.FIT);e.tooltip.bind(t,"Select inputs to be fitted");const n=new Map([["Misc",[]]]);Object.values(this.store.inputs).forEach((t=>{const e=t.prop.category,i=[...t.constForm.map((t=>t.root)),...t.saForm.map((t=>t.root))];n.has(e)?n.get(e).push(...i):n.set(e,i)}));const i=e.div([t],{style:{"overflow-y":"scroll",width:"100%"}});n.size>1?(n.forEach(((t,n)=>{"Misc"!==n&&(i.append(e.h3(n)),i.append(...t))})),n.get("Misc").length>0&&(i.append(e.h3("Misc")),i.append(...n.get("Misc")))):i.append(...n.get("Misc"));const o=e.h1(gn.TARGET);e.tooltip.bind(o,"Select target outputs"),i.appendChild(o);let s="Misc";Object.values(this.store.outputs).reduce(((t,n)=>{const i=n.prop;return i.category!==s&&(t.append(e.h3(i.category)),s=i.category),t.append(n.input.root),t.append(n.colNameInput.root),t}),i);let r=!1;for(const t of Object.keys(this.store.outputs))if(!0===this.store.outputs[t].isInterest.value){r=!0;break}r||this.store.outputs[Object.keys(this.store.outputs)[0]].isInterest.next(!0);const l=e.h1("Using");e.tooltip.bind(l,"Specify fitting method"),i.appendChild(l),this.methodInput.root.insertBefore(this.fittingSettingsIcon,this.methodInput.captionLabel),this.fittingSettingsIcon.style.minWidth="50px",i.appendChild(this.methodInput.root);const u=e.h2("with settings");return e.tooltip.bind(u,(()=>`Settings of the ${this.method} method`)),this.fittingSettingsDiv.appendChild(u),this.generateSettingInputs(),this.showHideSettingInputs(),i.appendChild(this.fittingSettingsDiv),this.settingsInputs.forEach((t=>t.forEach((t=>{t.root.insertBefore(Bn(),t.captionLabel),this.fittingSettingsDiv.append(t.root)})))),[this.lossInput,this.samplesCountInput,this.similarityInput].forEach((t=>{t.root.insertBefore(Bn(),t.captionLabel),t.nullable=!1,i.appendChild(t.root)})),a()(i).addClass("ui-form"),this.updateApplicabilityState(),a()(i).css({"padding-left":"12px","overflow-y":"scroll","padding-right":"4px"}),i}updateRunIconDisabledTooltip(t){e.tooltip.bind(this.runIcon,(()=>{const n=e.label(t);return n.style.color="#FF0000",n}))}updateApplicabilityState(){this.readyToRun=this.canFittingBeRun(),this.updateRunIconStyle()}updateRunIconStyle(){this.readyToRun?(this.runIcon.style.color="var(--green-2)",e.tooltip.bind(this.runIcon,"Run fitting")):this.runIcon.style.color="var(--grey-3)"}areInputsReady(){var t;let e,n=!1,i=!0;for(const o of Object.keys(this.store.inputs)){const s=this.store.inputs[o],r=null!==(t=s.prop.caption)&&void 0!==t?t:s.prop.name;if(!0===s.isChanging.value){n=!0;const t=s.min.input,o=s.max.input,a=t.value,l=o.value;e=null!=a&&void 0!==l&&void 0!==l,e?a>l?(e=!1,this.updateRunIconDisabledTooltip(`Invalid min & max of "${r}"`),t.input.classList.add("d4-invalid"),o.input.classList.add("d4-invalid")):(t.input.classList.remove("d4-invalid"),o.input.classList.remove("d4-invalid")):this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}else{e=null!=s.const.input.value,e||this.updateRunIconDisabledTooltip(`Incomplete "${r}"`),i=i&&e}}return n||this.updateRunIconDisabledTooltip("No parameters for fitting selected"),n&&i}areOutputsReady(){let t,e=!1,n=!0;for(const i of Object.keys(this.store.outputs)){const s=this.store.outputs[i];if(!0===s.isInterest.value){e=!0;t=null!=s.input.value,s.prop.propertyType===o.TYPE.DATA_FRAME&&(t=t&&null!==s.colNameInput.value&&""!==s.colName),t||this.updateRunIconDisabledTooltip(`Incomplete the "${s.input.caption}" target`),n=n&&t}}return e||this.updateRunIconDisabledTooltip("No targets selected"),e&&n}isSamplesCountValid(){return this.samplesCount>0||(this.updateRunIconDisabledTooltip(`Invalid "${gn.SAMPLES}"`),!1)}isSimilarityValid(){return this.similarity>=bn.SIMILARITY_MIN||(this.updateRunIconDisabledTooltip(`Invalid "${gn.SIMILARITY}"`),!1)}canFittingBeRun(){return this.areInputsReady()&&this.areOutputsReady()&&this.isSamplesCountValid()&&this.areMethodSettingsCorrect()&&this.isSimilarityValid()}getFixedInputs(){return Object.keys(this.store.inputs).filter((t=>!this.store.inputs[t].isChanging.value))}getFittedInputs(){return Object.keys(this.store.inputs).filter((t=>this.store.inputs[t].type===o.TYPE.FLOAT&&this.store.inputs[t].isChanging.value))}runOptimization(){return kn(this,void 0,void 0,(function*(){try{if(!this.canFittingBeRun())return;if(this.samplesCount<1)return;if(this.similarity<bn.SIMILARITY_MIN)return;this.failsDF=null;const n={},i=this.getFixedInputs();i.forEach((t=>n[t]=this.store.inputs[t].const.value));const s=this.getFittedInputs(),r=s.length,l=[],u=new Float32Array(r),c=new Float32Array(r),d=new Array(r);s.forEach(((t,e)=>{var n;const i=this.store.inputs[t];u[e]=i.min.value,c[e]=i.max.value,l.push(t),d[e]=null!==(n=i.prop.caption)&&void 0!==n?n:i.prop.name}));const p=this.getOutputsOfInterest();if(p.length<1)return void t.shell.error("No output is selected for optimization.");const h=p.map((t=>t.prop.propertyType)).filter((t=>t===o.TYPE.DATA_FRAME)).length>1,f=t=>kn(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n);return yield e.call()})),m=t=>kn(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0,r=0,a=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?(a=t.target,s+=Math.pow((a-i.getParamValue(t.prop.name))/(0!==a?a:1),2),++r):Tn(t.colName,t.target,i.getParamValue(t.prop.name),!0).forEach((t=>{s+=Math.pow(t,2),++r}))})),Math.sqrt(s/r)})),v=t=>kn(this,void 0,void 0,(function*(){t.forEach(((t,e)=>n[l[e]]=t));const e=this.func.prepare(n),i=yield e.call();let s=0;return p.forEach((t=>{t.prop.propertyType!==o.TYPE.DATA_FRAME?s=Math.max(s,Math.abs(t.target-i.getParamValue(t.prop.name))):Tn(t.colName,t.target,i.getParamValue(t.prop.name),!1).forEach((t=>s=Math.max(s,Math.abs(t))))})),s}));let g,y,b;if(this.loss===fn.MAD?(g=v,y="maximum absolute devation"):(g=m,y="root mean square error"),this.method!==pn.NELDER_MEAD)throw new Error(`Not implemented the '${this.method}' method`);b=yield _n(g,u,c,this.nelderMeadSettings,this.samplesCount);const A=b.extremums,C=A.length;if(C<this.samplesCount){this.failsDF=b.fails;const t=this.failsDF.columns;d.forEach(((e,n)=>t.byIndex(n).name=t.getUnusedName(e))),i.forEach((e=>{var n,i;const s=this.store.inputs[e];s.prop.propertyType!==o.TYPE.DATA_FRAME&&t.add(o.Column.fromList(s.prop.propertyType,t.getUnusedName(null!==(n=s.prop.caption)&&void 0!==n?n:s.prop.name),new Array(null===(i=this.failsDF)||void 0===i?void 0:i.rowCount).fill(s.const.value)))}))}const w=[],I=this.similarity;A.forEach((t=>{let e=!0;w.forEach((n=>e&&(e=function(t,e,n,i){const o=t.length;if(o!==e.length||o!==n.length||o!==i.length)throw new Error("Inconsistent found points");return t.reduce(((t,o,s)=>{const r=i[s]-n[s];return r>0?Math.max(t,Math.abs(o-e[s])/r):t}),0)}(n.point,t.point,u,c)>I))),e&&w.push(t)}));const T=w.length;if(C<this.samplesCount){if(C<1)return void t.shell.warning(e.divV([e.label(`Failed to find ${this.samplesCount} point${this.samplesCount>1?"s":""}`),e.div([this.showFailsBtn])]));t.shell.info(e.divV([e.label(`Found ${T} point${T>1?"s":""}`),e.div([this.showFailsBtn])]))}else t.shell.info(`Found ${T} point${T>1?"s":""}`);this.clearPrev(),w.sort(((t,e)=>t.cost-e.cost));const E=new Float32Array(T),x=this.comparisonView.grid,R=new Array(T),S=new Array(T),O=new Array(T),P=new Map([[gn.LOSS,`The final loss obtained: ${y}`]]);let F=!0;const _=[];w.forEach(((t,e)=>kn(this,void 0,void 0,(function*(){E[e]=t.cost;const n=this.getLossGraph(t);O[e]=n;const i=new Map,s=yield f(t.point);S[e]=s,p.forEach((t=>{this.getOutputGof(t.prop,t.target,s,t.colName,h).forEach((t=>i.set(t.caption,t.root)))})),R[e]=i,F&&(i.forEach(((t,e)=>{var n;P.set(e,"Goodness of fit"),null===(n=this.comparisonView.table)||void 0===n||n.columns.addNew(e,o.COLUMN_TYPE.STRING);const i=this.comparisonView.grid.columns.byName(e);i.cellType="html",i.width=vn.GOF_VIEWER_WIDTH,_.push(e)})),F=!1)}))));const k=o.DataFrame.fromColumns([o.Column.fromFloat32Array(gn.LOSS,E)]);this.comparisonView.dataFrame=k;const M=k.columns;d.forEach(((t,e,n)=>{t=M.getUnusedName(t),n[e]=t;const i=new Float32Array(T);for(let t=0;t<T;++t)i[t]=w[t].point[e];M.add(o.Column.fromFloat32Array(t,i)),P.set(t,`Obtained values of '${t}'`)})),x.props.rowHeight=vn.ROW_HEIGHT,x.props.showAddNewRowIcon=!1,x.props.allowEdit=!1;const B=M.getUnusedName(`${this.loss} by iterations`);P.set(B,`Minimizing ${y}`),M.addNew(B,o.COLUMN_TYPE.STRING);const L=x.columns.byName(B);L.cellType="html",L.width=vn.LOSS_GRAPH_WIDTH;let D=!0;x.onCellPrepare((t=>kn(this,void 0,void 0,(function*(){D&&(x.columns.setOrder(M.names().filter((t=>t!==B)).concat([B])),D=!1),t.isColHeader||t.isRowHeader||(t.isTableCell&&t.gridColumn.name===B&&null!==t.cell.value&&(t.style.element=O[t.gridRow]),_.forEach((n=>{var i;t.isTableCell&&t.gridColumn.name===n&&null!==t.cell.value&&void 0!==R[t.gridRow]&&(t.style.element=null!==(i=R[t.gridRow].get(n))&&void 0!==i?i:e.label(""))})))})))),x.columns.byName(gn.LOSS).format="scientific",x.columns.byName(gn.LOSS).width=vn.LOSS_COL_WIDTH,x.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,s=P.get(o);return e.tooltip.show(null!=s?s:"",n,i),!0}})),k.currentCell=k.cell(0,gn.LOSS);const N=n=>kn(this,void 0,void 0,(function*(){var i;if(null==n)return;const s=null!==(i=n.tableRowIndex)&&void 0!==i?i:0,r=S[s],l=[...r.outputParams.values()].filter((t=>o.TYPES_SCALAR.has(t.property.propertyType))),u=o.HtmlTable.create(l,(t=>{var e;return[null!==(e=t.property.caption)&&void 0!==e?e:t.property.name,r.outputs[t.property.name],t.property.options.units]})).root,c=[...r.outputParams.values()].filter((t=>t.property.propertyType===o.TYPE.DATA_FRAME)).reduce(((t,e)=>{var n;const i=Dt(e.property).config,s=r.outputs[e.name],l=null!==(n=e.property.caption)&&void 0!==n?n:e.property.name;return i.map((e=>{const n=e.type,i=o.Viewer.fromType(n,s);i.setOptions(e),a()(i.root).css({width:"100%"}),t[l]?t[l].push(i.root):t[l]=[i.root]})),t}),{});let d;d=l.length>0?Object.assign({"Output scalars":[u]},c):Object.assign({},c);const p=e.accordion();if(a()(p.root).css({width:"100%"}),Object.entries(d).map((t=>{p.addPane(t[0],(()=>e.divV(t[1])))})),p.panes.length-1<0)throw new Error("Function has no outputs");p.panes[p.panes.length-1].expanded=!0,t.shell.o=p.root}));this.gridClickSubscription=x.onCellClick.subscribe(N),this.gridCellChangeSubscription=x.onCurrentCellChanged.subscribe(N)}catch(e){t.shell.error(e instanceof Error?e.message:"The platform issue")}}))}getOutputsOfInterest(){const t=[];for(const e of Object.keys(this.store.outputs)){const n=this.store.outputs[e];n.isInterest.value&&t.push(n)}return t}getLossGraph(t){return o.Viewer.lineChart(o.DataFrame.fromColumns([o.Column.fromList(o.COLUMN_TYPE.INT,gn.ITER,[...Array(t.iterCount).keys()].map((t=>t+1))),o.Column.fromList(o.COLUMN_TYPE.FLOAT,gn.LOSS,t.iterCosts.slice(0,t.iterCount))]),{showYAxis:!0,showXAxis:!0,showXSelector:!0,showYSelector:!0,lineColoringType:"custom",lineColor:15274e3,markerColor:15274e3}).root}getOutputGof(t,e,n,i,s){var r;const a=t.propertyType,l=t.name,u=null!==(r=t.caption)&&void 0!==r?r:l;switch(a){case o.TYPE.FLOAT:case o.TYPE.INT:case o.TYPE.BIG_INT:return[{caption:u,root:o.Viewer.barChart(o.DataFrame.fromColumns([o.Column.fromStrings(u,["obtained","target"]),o.Column.fromList(a,gn.VALUE,[n.getParamValue(l),e])]),{valueColumnName:gn.VALUE,splitColumnName:u,valueAggrType:o.AGG.AVG,showValueSelector:!1,showCategorySelector:!1,showStackSelector:!1,showEmptyBars:!0}).root}];case o.TYPE.DATA_FRAME:const r=[],c=n.getParamValue(l),d=e,p=c.col(i),h=d.col(i),f=Dt(t).config;if(null===p||null===h)throw new Error("Creating viewer fails: incorrect argument column name");const m=p.getRawData(),v=In(h,p),g=v.length,y=Array(g);v.forEach(((t,e)=>y[e]=m[t]));let b,A,C=null;return f.filter((t=>t.type===o.VIEWER.LINE_CHART)).forEach((t=>{const e=t.segmentColumnName;if(e){const t=Array(g);v.forEach(((n,i)=>t[i]=c.col(e).get(n))),C=o.Column.fromStrings(e,t)}})),d.columns.names().forEach((t=>{if(t!==i){if(A=c.col(t),null===A)throw new Error(`Creating viewer fails: no '${t}' column in the output dataframe`);b=A.getRawData();const e=Array(g);if(v.forEach(((t,n)=>e[n]=b[t])),A=d.col(t),null===A)throw new Error(`Creating viewer fails: no '${t}' column in the target dataframe`);b=A.getRawData();const n=Array(g);v.forEach(((t,e)=>n[e]=b[e]));const i={multiAxis:!0,yGlobalScale:!0},a=o.DataFrame.fromColumns([h,o.Column.fromList(A.type,gn.OBTAINED,e),o.Column.fromList(A.type,gn.TARGET,n)]);C&&(a.columns.add(C),i.segmentColumnName=C.name),r.push({caption:s?`${u}: [${t}]`:`[${t}]`,root:o.Viewer.lineChart(a,i).root})}})),r;default:throw new Error("Unsupported output type")}}clearPrev(){void 0!==this.helpDN&&(this.comparisonView.dockManager.close(this.helpDN),this.helpDN=void 0),this.gridClickSubscription&&(this.gridClickSubscription.unsubscribe(),this.gridClickSubscription=null),this.gridCellChangeSubscription&&(this.gridCellChangeSubscription.unsubscribe(),this.gridCellChangeSubscription=null)}showNelderMeadFails(){if(null===this.failsDF)return;const n=t.shell.addTableView(this.failsDF);n.addViewer(o.Viewer.form(o.DataFrame.fromColumns(Object.entries(this.nelderMeadSettings).map((t=>{var e;return o.Column.fromFloat32Array(null!==(e=Rn.get(t[0]))&&void 0!==e?e:t[0],new Float32Array([t[1]]))})))),{description:"The Nelder-Mead method settings",showNavigation:!1});const i=this.getFittedInputs().length,s=new Map;this.failsDF.columns.names().forEach(((t,e)=>{e<i?s.set(t,`Initial value of "${t}" used in the Nelder-Mead method`):e>i?s.set(t,`Value of "${t}" (fixed input)`):s.set(t,"Error message raised")})),n.grid.onCellTooltip((function(t,n,i){if(t.isColHeader&&t.tableColumn){const o=t.tableColumn.name,r=s.get(o);return e.tooltip.show(null!=r?r:"",n,i),!0}}))}}var Dn,Nn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};!function(t){t.INPUTS="inputs",t.OUTPUTS="outputs"}(Dn||(Dn={}));const Vn={[Dn.INPUTS]:"inputParams",[Dn.OUTPUTS]:"outputParams"},jn=()=>e.divText("[No data to display]",{style:{"text-align":"center","align-content":"center",width:"100%",height:"100%"}});class $n extends be{static fromFuncCall(t,e={historyEnabled:!0,isTabbed:!1}){return new this(t,e)}constructor(t,n={historyEnabled:!0,isTabbed:!1}){super(t,n),this.options=n,this.validationRequests=new c.Subject,this.validationUpdates=new c.Subject,this.runRequests=new c.Subject,this.isRunning=new c.BehaviorSubject(!1),this.isUploadMode=new c.BehaviorSubject(!1),this.inputsOverride={},this.inputsMap={},this.validators={},this.validationState={},this.externalValidatorsUpdates=new c.Subject,this.externalValidatorsState={},this.pendingValidations=this.validationUpdates.pipe((0,s.startWith)(null),(0,s.map)((()=>this.validationState))),this._isOutputOutdated=new c.BehaviorSubject(!0),this.isOutputOutdated=this._isOutputOutdated.pipe((0,s.distinctUntilChanged)()),this.blockRuns=new c.BehaviorSubject(!1),this.prevOpenedTab=null,this.beforeInputPropertyRender=new c.Subject,this.afterInputPropertyRender=new c.Subject,this.afterOutputPropertyRender=new c.Subject,this.afterOutputSacalarTableRender=new c.Subject,this.formButtons=e.div(),this.additionalBtns=[],this.navBtns=[],this.tabsElem=e.tabControl(),this.dfToViewerMapping={},this.focusedInput=null,this.foldedCategoryInputs={},this.sheetNamesCache={},this.richFunctionExport=t=>Nn(this,void 0,void 0,(function*(){if("Excel"===t)try{const e=this.lastCall;if(!e)throw new Error("Function was not called");if(!this.exportConfig.supportedFormats.includes(t))throw new Error(`Format "${t}" is not supported.`);if(!this.func)throw new Error("The correspoding function is not specified");yield o.Utils.loadJsCss(["/js/common/exceljs.min.js"]);const n=window.ExcelJS,i="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",s=new n.Workbook,r=t=>o.TYPES_SCALAR.has(t),a=t=>t.propertyType===o.TYPE.DATA_FRAME,l=this.func.inputs.filter((t=>a(t))),u=this.func.inputs.filter((t=>r(t.propertyType))),c=this.func.outputs.filter((t=>a(t))),d=this.func.outputs.filter((t=>r(t.propertyType)));if(l.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.inputs[t.name];st(o,r)})),u.length){const t=s.addWorksheet("Input scalars");it(t,u.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.inputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}if(c.forEach((t=>{var n;const i=t.options.caption||t.name,o=null!==(n=s.worksheets.find((t=>t.name===this.getSheetName(i,s))))&&void 0!==n?n:s.addWorksheet(this.getSheetName(i,s)),r=e.outputs[t.name];st(o,r)})),d.length){const t=s.addWorksheet("Output scalars");it(t,d.map((t=>{var n,i,o;return{caption:null!==(n=t.options.caption)&&void 0!==n?n:t.name,value:null!==(i=e.outputs[t.name])&&void 0!==i?i:"",units:null!==(o=t.options.units)&&void 0!==o?o:""}})))}const p=this.tabsElem;for(const t of this.inputTabsLabels)for(const n of this.categoryToDfParamMap.inputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.inputs[n.name];for(const[t,e]of i.entries())yield rt(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}for(const t of this.outputTabsLabels)for(const n of this.categoryToDfParamMap.outputs[t].filter((t=>a(t)))){const i=this.dfToViewerMapping[n.name].filter((t=>t.type!==o.VIEWER.GRID)).filter((t=>Object.values(m).includes(t.type)));if(0===i.length)continue;p.currentPane=p.getPane(t),yield new Promise((t=>setTimeout(t,100)));const r=n.options.caption||n.name,a=e.outputs[n.name];for(const[t,e]of i.entries())if(e.type===o.VIEWER.STATISTICS){const e=a.columns.length,n=o.DataFrame.fromColumns([o.Column.string("Name",e).init((t=>a.columns.byIndex(t).name)),o.Column.int("Values",e).init((t=>a.columns.byIndex(t).stats.valueCount)),o.Column.int("Nulls",e).init((t=>a.columns.byIndex(t).stats.missingValueCount)),o.Column.float("Min",e).init((t=>a.columns.byIndex(t).stats.min)),o.Column.float("Max",e).init((t=>a.columns.byIndex(t).stats.max)),o.Column.float("Avg",e).init((t=>a.columns.byIndex(t).stats.avg)),o.Column.float("Stdev",e).init((t=>a.columns.byIndex(t).stats.stdev))]);st(s.getWorksheet(this.getSheetName(r,s)),n,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}else yield rt(s,s.getWorksheet(this.getSheetName(r,s)),e.root,a.columns.length+2,t>0?Math.ceil(i[t-1].root.clientHeight/20)+1:0)}const h=yield s.xlsx.writeBuffer();return new Blob([h],{type:i})}catch(t){console.log(t)}if("DataUrl images"===t){const t={},e=t=>t.propertyType===o.TYPE.DATA_FRAME,n=this.tabsElem;yield o.Utils.loadJsCss(["/js/common/html2canvas.min.js"]);const i=window.html2canvas;for(const s of this.tabsLabels.filter((t=>this.inputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.inputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}for(const s of this.tabsLabels.filter((t=>this.outputTabsLabels.includes(t))))for(const r of this.categoryToDfParamMap.outputs[s].filter((t=>e(t)))){const e=this.dfToViewerMapping[r.name].filter((t=>t.type!==o.VIEWER.GRID&&t.type!==o.VIEWER.STATISTICS)).filter((t=>Object.values(m).includes(t.type)));if(0!==e.length){n.currentPane=n.getPane(s),yield new Promise((t=>setTimeout(t,100)));for(const[n,o]of e.entries()){const e=(yield i(o.root,{logging:!1})).toDataURL();t[r.name]||(t[r.name]={}),t[r.name][n]={dataUrl:e,width:o.root.clientWidth,height:o.root.clientHeight}}}}return new Blob([JSON.stringify(t)],{type:"text/plain"})}throw new Error("Format is not supported")})),this.exportConfig={supportedExtensions:this.richFunctionViewExportExtensions(),supportedFormats:this.richFunctionViewSupportedFormats(),export:this.richFunctionExport,filename:this.defaultExportFilename}}onFuncCallReady(){const n=Object.create(null,{onFuncCallReady:{get:()=>super.onFuncCallReady}});return Nn(this,void 0,void 0,(function*(){yield this.loadInputsOverrides(),yield this.loadInputsValidators(),yield n.onFuncCallReady.call(this);const i=this.funcCallReplaced.subscribe((()=>this.validationRequests.next({isRevalidation:!1})));this.subs.push(i);const o=this.validationRequests.pipe((0,s.groupBy)((t=>t.field)),(0,s.mergeMap)((t=>t.pipe((0,s.tap)((t=>this.setValidationPending(t.field))),(0,s.switchMap)((t=>{const e=new AbortController,n=e.signal;let i=!1;return new c.Observable((o=>{const s=(0,c.from)(this.runValidation(Object.assign({},t),n)).subscribe((t=>{i=!0,o.next(t)}));return()=>{i||e.abort(),s.unsubscribe()}})).pipe((0,s.tap)((e=>{this.setValidationResults(e),this.runRevalidations(t,e),this.validationUpdates.next(null)})),(0,s.mapTo)(t))})))))).subscribe((t=>{t.field&&this.runningOnInput&&this.isRunnable()&&this.doRun()}));this.subs.push(o);const r=this.externalValidatorsUpdates.subscribe((t=>{this.updateInputValidationReuslts(t)}));this.subs.push(r);const a=(0,c.combineLatest)([this.runRequests.pipe((0,s.switchMap)((()=>(0,c.of)(!1).pipe((0,s.delay)(500),(0,s.startWith)(!0))))),this.validationUpdates.pipe((0,s.debounceTime)(0))]).pipe((0,s.filter)((([t])=>t&&this.isRunnable()))).subscribe((()=>this.doRun()));this.subs.push(a);const l=this.options.isTabbed?null:yield this.loadLastInputs();if(l)t.shell.info(e.div([e.divText("Do you want to load last inputs?"),e.divH([e.bigButton("Load",(()=>{for(const[t,e]of Object.entries(l)){const n=this.getInput(t);n.notify=!1,n.value=e,n.notify=!0}t.shell.info(e.divText("Change the loaded inputs to run computations"))}))])]));else{const t=new AbortController,e=yield this.runValidation({isRevalidation:!1},t.signal);this.setValidationResults(e),this.runRevalidations({isRevalidation:!1},e),this.validationUpdates.next(null),this.runningOnStart&&this.isRunnable()&&(yield this.doRun())}}))}onBeforeRun(){return this.tabsElem.currentPane&&(this.prevOpenedTab=this.inputTabsLabels.includes(this.tabsElem.currentPane.name)?null:this.tabsElem.currentPane),Promise.resolve()}onAfterRun(){if(this.showOutput(),this.tabsElem.panes.forEach((t=>{a()(t.header).show()})),this.prevOpenedTab)return this.tabsElem.currentPane=this.prevOpenedTab,Promise.resolve();const t=this.tabsElem.panes.find((t=>this.outputTabsLabels.includes(t.name)));return t&&(this.tabsElem.currentPane=t),Promise.resolve()}getRunButton(t="Run"){var n;const i=e.bigButton(null!==(n=this.func.options.runLabel)&&void 0!==n?n:t,(()=>Nn(this,void 0,void 0,(function*(){return yield this.doRun()})))),o=(0,c.merge)(this.validationUpdates,this.externalValidatorsUpdates,this.isRunning,this.blockRuns).subscribe((()=>{const t=this.isRunnable();i.disabled=!t}));return this.subs.push(o),i}loadInputsOverrides(){return Nn(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>Nn(this,void 0,void 0,(function*(){if(e.property.options.input){const n=(yield t.functions.eval(e.property.options.input)).prepare({params:JSON.parse(e.property.options.inputOptions||"{}")});yield n.call(),this.inputsOverride[e.name]=n.outputs.input}})))))}))}loadInputsValidators(){return Nn(this,void 0,void 0,(function*(){const e=[...this.funcCall.inputParams.values()];yield Promise.all(e.map((e=>Nn(this,void 0,void 0,(function*(){if(e.property.options.validatorFunc){const n=(yield t.functions.eval(e.property.options.validatorFunc)).prepare({params:JSON.parse(e.property.options.validatorFuncOptions||"{}")});yield n.call(),this.validators[e.name]=n.outputs.validator}})))))}))}keepOutput(){var t;return"true"===(null===(t=this.func)||void 0===t?void 0:t.options.keepOutput)}getSaveButton(t="Save"){const n=e.bigButton(t,(()=>Nn(this,void 0,void 0,(function*(){return yield this.saveExperimentalRun(this.funcCall)}))),"Save uploaded data"),i=this.isUploadMode.subscribe((t=>{this.buildRibbonPanels(),t?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}getStandardButtons(){const t=this.getRunButton(),n=e.div([t]);e.tooltip.bind(n,(()=>t.disabled?this.isRunning.value?"Computations are in progress":this.getValidationMessage():""));const i=this.getSaveButton();return[...this.isHistoryEnabled&&!this.options.isTabbed?[i]:[],...this.runningOnInput?[]:[n]]}buildFormButtons(){var t;const n=this.getStandardButtons(),i=e.buttonsInput();return a()(i.firstChild).css({display:"none"}),null===(t=i.lastChild)||void 0===t||t.replaceWith(e.div([...this.navBtns,...this.additionalBtns,...n],"ui-input-editor")),a()(i).addClass("rfv-buttons"),a()(i).css({"max-width":"100%"}),this.formButtons.replaceWith(i),this.formButtons=i,i}setAdditionalButtons(t){this.additionalBtns=t,this.buildFormButtons()}setNavigationButtons(t){this.navBtns=t}buildIO(){const{inputBlock:t,inputForm:n,outputForm:i,controlsWrapper:o}=this.buildInputBlock(),s=[...Array.from(n.childNodes),...this.isUploadMode.value?[Array.from(i.childNodes)]:[]];e.tools.handleResize(t,(()=>{a()(t).width()<300?(a()(n).addClass("ui-form-condensed"),a()(i).addClass("ui-form-condensed"),a()(o).addClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100px")))):(a()(n).removeClass("ui-form-condensed"),a()(i).removeClass("ui-form-condensed"),a()(o).removeClass("ui-form-condensed"),s.forEach((t=>a()(t).css("min-width","100%"))))}));const r=this.buildOutputBlock();r.style.height="100%",r.style.width="100%",this.hideOutput();const l=e.splitH([t,e.panel([r],{style:{"padding-top":"0px"}})],null,!0);return l.style.padding="0 12px",t.style.maxWidth="360px",l}buildInputBlock(){const t=this.renderInputForm(),n=this.renderOutputForm();this.buildFormButtons();const i=e.div(this.formButtons,"ui-form ui-form-wide");a()(i).css({"padding-left":"0px","padding-bottom":"0px","padding-right":"6px","max-width":"100%","min-height":"50px"});const o=e.switchInput("",this.isUploadMode.value,(t=>this.isUploadMode.next(t))),s=this.isUploadMode.subscribe((t=>{o.notify=!1,o.value=t,o.notify=!0,t?a()(n).show():a()(n).hide()}));return this.subs.push(s),{inputBlock:e.divV([t,...this.hasUploadMode&&!this.uploadFunc?[e.divH([e.h2("Experimental data"),o.root],{style:{"flex-grow":"0"}}),n]:[],i],"ui-box rfv-form"),inputForm:t,outputForm:n,controlsWrapper:i}}processCustomDataUpload(){return Nn(this,void 0,void 0,(function*(){const n=()=>{const t=o.Dialog.create({title:"Select to compare"}),n=new Wt(p.length>0?p:[...this.historyBlock.history.values()],{fallbackText:"No historical runs found",showActions:!(p.length>0),showBatchActions:!(p.length>0)}),i=new Wt(d,{fallbackText:"No runs uploaded",showActions:!1,showBatchActions:!1});t.add(e.divV([e.divV([e.label("Uploaded runs"),e.element("div","splitbar-horizontal"),i.root],{style:{height:"50%","overflow-y":"hidden"}}),e.divV([e.label(p.length>0?"Simulated":"History",{style:{padding:"0px 10px 0px 9px"}}),e.element("div","splitbar-horizontal"),n.root],{style:{height:"50%","overflow-y":"hidden"}})],{style:{"justify-content":"space-between",gap:"10px","overflow-y":"scroll",height:"100%"}})),a()(t.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const s="Compare selected";return 0===p.length?t.addButton(s,(()=>Nn(this,void 0,void 0,(function*(){const e=yield Promise.all([...n.selected].map((t=>dt.loadRun(t.id))));this.onComparisonLaunch([...e,...i.selected.values()]),t.close()})))):t.addButton(s,(()=>Nn(this,void 0,void 0,(function*(){this.onComparisonLaunch([...n.selected.values(),...i.selected.values()]),t.close()})))),t.getButton(s).disabled=!0,this.subs.push((0,c.merge)(n.onSelectedChanged,i.onSelectedChanged).subscribe((()=>{n.selected.size+i.selected.size>1?t.getButton(s).disabled=!1:t.getButton(s).disabled=!0}))),this.isHistorical.value&&t.addButton(g,(()=>Nn(this,void 0,void 0,(function*(){this.onComparisonLaunch([this.funcCall,...i.selected.values()]),t.close()})))),a()(t.getButton("CANCEL")).hide(),t},i=yield t.functions.eval(this.uploadFunc),r=yield i.prepare({params:{func:this.func}}).call(),l=r.outputs.uploadWidget,u=r.outputs.uploadFuncCall;let d=[],p=[];const h=o.Dialog.create({title:"Upload"});a()(h.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const m=o.Dialog.create({title:"Review uploaded runs"});a()(m.root.querySelector(".d4-dialog-contents")).removeClass("ui-form");const v="Save to history",g="Compare w/ current";h.add(l.root),h.addButton(v,(()=>Nn(this,void 0,void 0,(function*(){return Lt(h.root,!0),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(C):t.options.immutable_tags=[C]})),Promise.all(d.map((t=>Nn(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);return dt.saveRun(e)}))))).then((t=>Promise.all(t.map((t=>dt.loadRun(t.id)))))).then((t=>{t.forEach((t=>this.historyBlock.addRun(t)))})).catch((e=>{t.shell.error(e)})).finally((()=>{Lt(h.root,!1),h.close();const t=new Wt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});m.add(t),m.show({modal:!0,fullScreen:!0})}))})))),h.addButton("Next",(()=>{h.close(),d.forEach((t=>{t.options.immutable_tags?t.options.immutable_tags.push(C):t.options.immutable_tags=[C]}));const t=new Wt(d,{fallbackText:"No runs uploaded",showActions:!0,showBatchActions:!0});m.add(t.root),m.show({modal:!0,fullScreen:!0})})),a()(h.getButton("CANCEL")).hide(),h.getButton(v).disabled=!0,h.getButton("Next").disabled=!0,a()(m.getButton("CANCEL")).hide(),m.addButton("Simulate w/ same inputs",(()=>{Lt(h.root,!0),Promise.all(d.map((t=>this.func.prepare((t=>{const e=t.clone(),n=f()(t.outputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.outputs[e.name]));for(const i of n)e.outputs[i.name]=t.outputs[i.name].clone();const i=f()(t.inputParams.values()).filter((e=>e.property.propertyType===o.TYPE.DATA_FRAME&&!!t.inputs[e.name]));for(const n of i)e.inputs[n.name]=t.inputs[n.name].clone();return e})(t).inputs).call()))).then((t=>{p=t,m.close(),n().show({modal:!0,fullScreen:!0})})).catch((e=>{t.shell.error(e)})).finally((()=>{Lt(h.root,!1)}))})),m.addButton("Compare w/ history",(()=>{m.close(),n().show({modal:!0,fullScreen:!0})}));const y=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===u.id))).subscribe((()=>{d=u.outputs.uploadedCalls,h.getButton(v).disabled=!1,h.getButton("Next").disabled=!1})),b=h.onClose.subscribe((()=>{this.isUploadMode.next(!1)}));h.subs.push(b,y),h.show({modal:!0,center:!0,resizable:!0})}))}onSaveClick(){return Nn(this,void 0,void 0,(function*(){this.isUploadMode.value?yield this.saveExperimentalRun(this.funcCall):yield this.saveRun(this.funcCall)}))}buildRibbonPanels(){super.buildRibbonPanels();const n=e.iconFA("play",(()=>Nn(this,void 0,void 0,(function*(){return yield this.doRun()}))),"Run computations");n.classList.add("fas");const i=e.iconFA("arrow-to-top",(()=>Nn(this,void 0,void 0,(function*(){this.uploadFunc?yield this.processCustomDataUpload():(this.isUploadMode.next(!this.isUploadMode.value),i.classList.toggle("d4-current"))}))),"Upload experimental data");i.classList.add("d4-toggle-button",...this.isUploadMode.value?["d4-current"]:[]);const o=e.iconFA("analytics",(()=>Nn(this,void 0,void 0,(function*(){return yield this.onSALaunch()}))),"Run sensitivity analysis"),s=e.iconFA("chart-line",(()=>Nn(this,void 0,void 0,(function*(){return yield this.onFittingLaunch()}))),"Fit inputs"),r=e.iconFA("info",(()=>Nn(this,void 0,void 0,(function*(){this.hasContextHelp&&(t.shell.windows.help.visible=!0,yield new Promise((t=>setTimeout(t,100))),t.shell.windows.help.showHelp(e.markdown(yield this.getContextHelp())))})))),a=[[...super.buildRibbonPanels().flat(),...this.runningOnInput||this.options.isTabbed?[]:[n],...this.hasUploadMode?[i]:[],...this.isSaEnabled?[o]:[],...this.isFittingEnabled?[s]:[],...this.hasContextHelp?[r]:[]]];return this.setRibbonPanels(a),a}showOutput(){e.setDisplay(this.tabsElem.root,!0),this._isOutputOutdated.next(!1)}buildOutputBlock(){this.tabsElem.root.style.width="100%",this.tabsLabels.forEach((n=>{const[i,r]=this.categoryToDfParamMap.outputs[n]?[this.categoryToDfParamMap.outputs[n],!1]:[this.categoryToDfParamMap.inputs[n],!0],l=i.filter((t=>t.propertyType===o.TYPE.DATA_FRAME||t.propertyType===o.TYPE.GRAPHICS)),u=i.filter((t=>t.propertyType!==o.TYPE.DATA_FRAME&&t.propertyType!==o.TYPE.GRAPHICS)),d=l.map((t=>nt(t).config));let p="";const h=l.reduce(((n,i,l)=>{var u,c;this.dfToViewerMapping[i.name]=[];const h=d[l].map(((n,s)=>Nn(this,void 0,void 0,(function*(){var s,r,a,l;const u=null!==(l=null!==(r=null===(s=this.funcCall.outputs[i.name])||void 0===s?void 0:s.value)&&void 0!==r?r:null===(a=this.funcCall.inputParams[i.name])||void 0===a?void 0:a.value)&&void 0!==l?l:t.data.demo.demog(0),c=n.type,d=Object.values(m).includes(c)?o.Viewer.fromType(c,u):yield u.plot.fromType(c);d.setOptions(n),this.dfToViewerMapping[i.name].push(d),this.afterOutputPropertyRender.next({prop:i,output:d});const p=jn();return 0===u.rowCount&&"demog 0"===u.name&&(e.setDisplay(d.root,!1),e.setDisplay(p,!0)),{viewer:d,stub:p}})))).map(((t,n)=>t.then((({viewer:t,stub:o})=>{const r=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe((()=>Nn(this,void 0,void 0,(function*(){var s;const r=null!==(s=this.funcCall.outputParams[i.name])&&void 0!==s?s:this.funcCall.inputParams[i.name];if(r.value){if(e.setDisplay(t.root,!0),e.setDisplay(o,!1),Object.values(m).includes(t.type))t.dataFrame=r.value;else{const e=yield r.value.plot.fromType(t.type);t.root.replaceWith(e.root),t=e}Object.keys(d[l][n]).includes("color")&&t.setOptions({color:d[l][n].color}),this.afterOutputPropertyRender.next({prop:i,output:t})}else e.setDisplay(t.root,!1),e.setDisplay(o,!0)}))));return this.subs.push(r),{loadedViewer:t,stub:o}})))),f=p!==(null!==(u=i.options.caption)&&void 0!==u?u:i.name)?null!==(c=i.options.caption)&&void 0!==c?c:i.name:" ";if(p=f,r){const t=this.funcCallReplaced.pipe((0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged}))).subscribe((()=>{this.showOutput(),this.inputTabsLabels.forEach((t=>{a()(this.tabsElem.getPane(t).header).show()}))}));this.subs.push(t)}const v=h.map(((t,n)=>{const i=d[l][n].block,o=e.wait((()=>Nn(this,void 0,void 0,(function*(){const n=yield t;return a()(n.loadedViewer.root).css({height:"100%",width:"100%"}),e.divV([n.loadedViewer.root,n.stub],{style:{width:"100%"}})}))));return a()(o).css({"min-height":"300px","flex-grow":"1"}),e.divV([e.h2(0===n?f:" ",{style:{"white-space":"pre"}}),o],{style:Object.assign({},i?{width:`${i}%`,"max-width":`${i}%`,"max-height":"100%"}:{"flex-grow":"1"})})}));if(i.propertyType===o.TYPE.GRAPHICS){const t=i.options.block,o=jn();o.classList.add("grok-scripting-image-container");const r=e.divV([e.h2(f,{style:{"white-space":"pre"}}),o],{style:Object.assign({},t?{width:`${t}%`,"max-width":`${t}%`,"max-height":"100%"}:{"flex-grow":"1"})}),a=()=>{var t;const e=null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name];e.value?(o.style.backgroundImage=`url("data:image/png;base64,${e.value}")`,o.textContent=""):(o.style.removeProperty("background-image"),o.textContent="[No data to display]")},l=this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.switchMap)((()=>{var t;return(null!==(t=this.funcCall.outputParams[i.name])&&void 0!==t?t:this.funcCall.inputParams[i.name]).onChanged.pipe((0,s.startWith)(null))})),(0,s.skip)(1)).subscribe(a);this.subs.push(l),n.append(r)}return n.append(...v),n}),e.divH([],{style:{"flex-wrap":"wrap","flex-grow":"1","max-height":"100%"}})),f=()=>{const t=o.HtmlTable.create(u,(t=>{var e;const n=t.options.precision,i=n&&t.propertyType===o.TYPE.FLOAT&&this.funcCall.outputs[t.name]?this.funcCall.outputs[t.name].toPrecision(n):this.funcCall.outputs[t.name],s=t.options.units?` [${t.options.units}]`:"";return[`${null!==(e=t.caption)&&void 0!==e?e:t.name}${s}`,null!=i?i:"[No value]"]})).root;return a()(t).addClass("rfv-scalar-table"),this.afterOutputSacalarTableRender.next(t),t};let v=f();const g=(0,c.merge)(this.funcCallReplaced,this.isRunning.pipe((0,s.filter)((t=>!1===t)),(0,s.skip)(1))).subscribe((()=>{const t=f();v.replaceWith(t),v=t,a()(this.tabsElem.getPane(n).header).show()}));this.subs.push(g),this.tabsElem.addPane(n,(()=>e.divV([...l.length?[h]:[],...u.length?[v]:[]])))}));const n=e.box();return n.append(this.tabsElem.root),n}onAfterLoadRun(t){return Nn(this,void 0,void 0,(function*(){this.showOutput()}))}get tabsLabels(){return[...this.inputTabsLabels,...this.outputTabsLabels]}get outputTabsLabels(){return Object.keys(this.categoryToDfParamMap.outputs)}get inputTabsLabels(){return Object.keys(this.categoryToDfParamMap.inputs)}get categoryToDfParamMap(){const t={inputs:{},outputs:{}};return this.func.inputs.filter((t=>t.propertyType===o.TYPE.DATA_FRAME&&0!==nt(t).config.length)).forEach((e=>{const n="Misc"===e.category?"Input":e.category;t.inputs[n]?t.inputs[n].push(e):t.inputs[n]=[e]})),this.func.outputs.forEach((e=>{const n="Misc"===e.category?"Output":e.category;e.propertyType===o.TYPE.DATA_FRAME&&0===nt(e).config.length||(t.outputs[n]?t.outputs[n].push(e):t.outputs[n]=[e])})),t}get inputsStorage(){return`RFV_LastInputs_${this.funcCall.func.name}`}saveLastInputs(){return Nn(this,void 0,void 0,(function*(){try{const e=yield f()(this.funcCall.inputParams.values()).reduce(((e,n)=>Nn(this,void 0,void 0,(function*(){const i=n.property.propertyType!==o.TYPE.DATA_FRAME?this.funcCall.inputs[n.name]:yield t.dapi.tables.uploadDataFrame(this.funcCall.inputs[n.name]);return Object.assign(Object.assign({},yield e),{[n.name]:JSON.stringify(i)})}))),Promise.resolve({}));return yield t.dapi.userDataStorage.put(this.inputsStorage,e)}catch(e){t.shell.error(e.toString())}}))}loadLastInputs(){return Nn(this,void 0,void 0,(function*(){try{const e=yield t.dapi.userDataStorage.get(this.inputsStorage);return 0===Object.keys(e).length?null:yield f()(this.funcCall.inputParams.values()).reduce(((n,i)=>Nn(this,void 0,void 0,(function*(){const s=i.property.propertyType!==o.TYPE.DATA_FRAME?JSON.parse(e[i.name]):yield t.dapi.tables.getTable(JSON.parse(e[i.name]));return Object.assign(Object.assign({},yield n),{[i.name]:s})}))),Promise.resolve({}))}catch(e){t.shell.error(e.toString())}}))}deleteLastInputs(){return Nn(this,void 0,void 0,(function*(){try{return yield t.dapi.userDataStorage.put(this.inputsStorage,{})}catch(e){t.shell.error(e.toString())}}))}doRun(){return Nn(this,void 0,void 0,(function*(){this.isRunning.next(!0);try{this.options.isTabbed||(yield this.saveLastInputs()),yield this.run(),this.options.isTabbed||(yield this.deleteLastInputs())}catch(e){t.shell.error(e.toString()),console.log(e)}finally{this.isRunning.next(!1),this.validationRequests.next({isRevalidation:!1,isNewOutput:!0})}}))}setExternalValidationResults(t,e){this.externalValidatorsState[t]=e,this.externalValidatorsUpdates.next(t)}saveInputLockState(t,e,n){"restricted"===n&&(this.funcCall.options[y]=Object.assign(Object.assign({},this.funcCall.options[y]),{[t]:e})),n&&(this.funcCall.options[b]=Object.assign(Object.assign({},this.funcCall.options[b]),{[t]:n})),this.updateConsistencyState()}getInputLockState(t){var e;return null===(e=this.funcCall.options[b])||void 0===e?void 0:e[t]}updateConsistencyState(){const t=Object.values(this.funcCall.options[b]).some((t=>"inconsistent"===t));this.consistencyState.next(t?"inconsistent":"consistent")}getInput(t){return this.inputsMap[t]}setInput(t,e,n){const i=this.getInput(t);if(!i)throw new Error(`No input named ${t}`);if(this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME&&"restricted"===n)throw new Error(`Param ${t} is dataframe. Restricted state is not supported for them.`);n||(n=this.funcCall.inputParams[t].property.propertyType===o.TYPE.DATA_FRAME?"disabled":"restricted"),this.funcCall.inputs[t]=e,this.setInputLockState(i,t,e,n)}getParamChanges(t){const e=this.funcCall.inputParams[t]?"inputParams":"outputParams";return this.funcCallReplaced.pipe((0,s.startWith)(null),(0,s.filter)((()=>!!this.funcCall)),(0,s.switchMap)((()=>this.funcCall[e][t].onChanged.pipe((0,s.startWith)(null)))),(0,s.map)((()=>this.funcCall[e][t].value)))}getParamValue(t){var e,n;const i=(null===(e=this.funcCall)||void 0===e?void 0:e.inputParams[t])?"inputParams":"outputParams";return null===(n=this.funcCall)||void 0===n?void 0:n[i][t].value}setInputLockState(t,e,n,i){i&&this.saveInputLockState(e,n,i),j(t)&&("disabled"===i&&t.setDisabled(),"restricted"===i&&t.setRestricted(),"restricted unlocked"===i&&t.setRestrictedUnlocked(),"inconsistent"===i&&t.setInconsistent(),"user input"===i&&t.setUserInput())}getRestrictedValue(t){var e;return null===(e=this.funcCall.options[y])||void 0===e?void 0:e[t]}renderOutputForm(){return this.renderIOForm(Dn.OUTPUTS)}onSALaunch(){return Nn(this,void 0,void 0,(function*(){yield dn.fromEmpty(this.func)}))}onFittingLaunch(){return Nn(this,void 0,void 0,(function*(){yield Ln.fromEmpty(this.func)}))}renderInputForm(){return this.renderIOForm(Dn.INPUTS)}renderIOForm(t){const n=e.divH([],"ui-form ui-form-wide");a()(n).css({"flex-wrap":"wrap","flex-grow":"0","padding-right":"12px","padding-top":"0px","padding-left":"0px","max-width":"100%",gap:"4px"});let i="Misc";const o=this.funcCall[Vn[t]].values();return f()(o).filter((t=>!!t)).forEach((e=>{const o=e.property;this.beforeInputPropertyRender.next(o);const s=this.getInputForVal(e);s?(this.inputsMap[e.property.name]=s,t===Dn.INPUTS&&(this.syncInput(e,s,t),this.checkForMapping(e,s),this.runningOnInput||this.disableInputsOnRun(e.property.name,s),this.bindOnHotkey(s)),this.renderCategory(n,e.property.category,i),this.renderInput(n,e,s),this.afterInputPropertyRender.next({prop:o,input:s}),i=o.category):i=o.category})),Object.keys(this.foldedCategoryInputs).forEach((t=>this.foldedCategoryInputs[t].forEach((t=>a()(t.input.root).hide())))),n.classList.remove("ui-panel"),n}saveFocusedElement(t){this.focusedInput=t}restoreFocusedElement(){var t;null===(t=this.focusedInput)||void 0===t||t.focus()}disableInputsOnRun(t,e){const n=this.isRunning.subscribe((n=>{"user input"!==this.getInputLockState(t)&&this.getInputLockState(t)||(n?(tt(e)&&a()(e.input).is(":focus")&&this.saveFocusedElement(e.input),e.enabled=!1):(e.enabled=!0,tt(e)&&this.restoreFocusedElement()))}));this.subs.push(n)}checkForMapping(t,e){if(!e.hasOwnProperty("_chosenRun"))return;const n=t.property.options.funccallMapping;if(!n)return;const i=JSON.parse(n),o=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>this.funcCall.inputParams[t.property.name].onChanged))).subscribe((()=>{Object.entries(i).forEach((([t,n])=>this.setInput(t,e.chosenRun?(t=>{var n,i,o,s,r,a;return null!==(a=null!==(s=null!==(i=null===(n=e.chosenRun)||void 0===n?void 0:n.inputs[t])&&void 0!==i?i:null===(o=e.chosenRun)||void 0===o?void 0:o.outputs[t])&&void 0!==s?s:null===(r=e.chosenRun)||void 0===r?void 0:r.options[t])&&void 0!==a?a:null})(n):Bt(this.funcCall.inputParams[t].property),e.chosenRun?"restricted":"user input")))}));this.subs.push(o)}getInputForVal(t){var n,i;const s=t.property;if(this.inputsOverride[t.property.name])return this.inputsOverride[t.property.name];if(s.propertyType===o.TYPE.STRING&&s.options.choices&&!s.options.propagateChoice)return e.choiceInput(null!==(n=s.caption)&&void 0!==n?n:s.name,Bt(s),JSON.parse(s.options.choices));switch(s.propertyType){case"file":return te.fileInput(null!==(i=s.caption)&&void 0!==i?i:s.name,null,null,null);case o.TYPE.FLOAT:const t=e.input.forProperty(s),n=s.options.format;return n&&(t.format=n),t;default:return e.input.forProperty(s)}}bindOnHotkey(t){tt(t)&&(t.input.onkeydown=t=>Nn(this,void 0,void 0,(function*(){"Enter"==t.key&&this.runRequests.next()})))}get foldedCategories(){var t;return JSON.parse(null!==(t=this.func.options.foldedCategories)&&void 0!==t?t:"[]")}getCategoryWarningIcon(t){const n=e.iconFA("exclamation-circle",null,"This category has inconsistent inputs");a()(n).css({color:"var(--orange-2)","padding-left":"5px"}).hide();const i=this.funcCallReplaced.subscribe((()=>{this.foldedCategoryInputs[t].some((t=>"inconsistent"===this.getInputLockState(t.paramName)&&t.input.value!==this.getRestrictedValue(t.paramName)))?a()(n).show():a()(n).hide()}));return this.subs.push(i),n}renderCategory(t,n,i){if(n!==i)if(this.foldedCategories.includes(n)){const i=this.getCategoryWarningIcon(n),o=e.iconFA("chevron-right",(()=>{var t;a()(s).show(),a()(o).hide(),a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).css({display:""})))}),"Open category");a()(o).css("padding-right","5px");const s=e.iconFA("chevron-down",(()=>{var t;a()(s).hide(),a()(o).show(),this.foldedCategoryInputs[n].some((t=>"inconsistent"===this.getInputLockState(t.paramName)))?a()(i).show():a()(i).hide(),(null!==(t=this.foldedCategoryInputs[n])&&void 0!==t?t:[]).forEach((t=>a()(t.input.root).hide()))}),"Close category");a()(s).css("padding-right","5px"),t.append(e.h2([o,s,e.h2(n,{style:{display:"inline"}}),i],{style:{width:"100%"}})),a()(s).hide()}else t.append(e.h2(n,{style:{width:"100%"}}))}renderInput(t,n,i){var o;const s=n.property;this.foldedCategories.includes(s.category)&&(this.foldedCategoryInputs[s.category]=[...null!==(o=this.foldedCategoryInputs[s.category])&&void 0!==o?o:[],{paramName:n.property.name,input:i}]),this.injectLockIcons(n,i),(t=>{if(j(t))return;const e=t;e.setDisabled=function(){t.enabled=!1,a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input")},e.setRestricted=function(){t.enabled=!1,tt(t)&&(t.input.disabled=!1),a()(t.root).addClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setRestrictedUnlocked=function(){t.enabled=!0,a()(t.root).addClass("rfv-restricted-unlocked-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-inconsistent-input")},e.setInconsistent=function(){t.enabled=!0,a()(t.root).addClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")},e.setUserInput=function(){t.enabled=!0,a()(t.root).removeClass("rfv-inconsistent-input"),a()(t.root).removeClass("rfv-restricted-input"),a()(t.root).removeClass("rfv-restricted-unlocked-input")}})(i),tt(i)&&(((t,e)=>{var n;const i=t.property;a()(e.root).css({width:`calc(${null!==(n=i.options.block)&&void 0!==n?n:"100"}% - ${i.options.block?"2":"0"}px)`,"box-sizing":"border-box"})})(n,i),this.bindTooltips(n,i),(t=>{const n=e.element("i");t.addOptions(n),t.setValidation=function(i){for(;n.firstChild&&n.removeChild(n.firstChild););const[o,s]=function(t){let n,i;return(null==t?void 0:t.pending)&&(i=e.iconFA("spinner",(()=>{z(t,i,n)}))),(null==t?void 0:t.errors)&&t.errors.length?(i=e.iconFA("exclamation-circle",(()=>{z(t,i,n)})),i.style.color="var(--red-3)"):(null==t?void 0:t.warnings)&&t.warnings.length?(i=e.iconFA("exclamation-circle",(()=>{z(t,i,n)})),i.style.color="var(--orange-2)"):(null==t?void 0:t.notifications)&&t.notifications.length&&(i=e.iconFA("info-circle",(()=>{z(t,i,n)})),i.style.color="var(--blue-1)"),i&&(i.classList.remove("fal"),i.classList.add("far"),n=function(t){const n=e.div([],"d4-tooltip");return function(t){t.popover="auto",t.style.fontStyle="normal",t.style.pointerEvents="all"}(n),t.appendChild(n),n}(i)),[i,n]}(i);o&&s&&(n.appendChild(o),n.appendChild(s)),t.input.classList.remove("d4-invalid"),t.input.classList.remove("d4-partially-invalid"),(null==i?void 0:i.errors)&&i.errors.length||(null==i?void 0:i.warnings)&&i.warnings.length||(null==i?void 0:i.notifications)&&i.notifications.length||(null==i?void 0:i.pending)?a()(n).css("display","flex"):a()(n).hide(),(null==i?void 0:i.errors)&&i.errors.length?t.input.classList.add("d4-invalid"):(null==i?void 0:i.warnings)&&i.warnings.length&&t.input.classList.add("d4-partially-invalid")}})(i)),t.append(i.root)}bindTooltips(t,n){const i=t.property.name,o=()=>{var n,o;const s=`${null!==(o=null!==(n=t.property.description)&&void 0!==n?n:t.property.caption)&&void 0!==o?o:t.property.name}.`,r=(()=>"disabled"===this.getInputLockState(i)?"Input is disabled to prevent inconsistency.":"inconsistent"===this.getInputLockState(i)?"The entered value is inconsistent to the computed value.":"restricted"===this.getInputLockState(i)?"The value is dependent and computed automatically. Click to edit":null)();return s||r?e.divV([...s?[e.divText(s)]:[],...r?[e.divText(r)]:[]],{style:{"max-width":"300px"}}):null};e.tooltip.bind(n.captionLabel,o),e.tooltip.bind(n.input,o)}injectLockIcons(t,n){const i=t.property.name;n.root.addEventListener("click",(()=>{"restricted"===this.getInputLockState(i)&&this.setInputLockState(n,t.name,t.value,"restricted unlocked")}));const s=e.iconFA("lock");a()(s).addClass("rfv-icon-lock"),a()(s).css({color:"var(--grey-2)"});const r=e.iconFA("lock-open");a()(r).addClass("rfv-icon-unlock"),a()(r).css({color:"var(--grey-2)"});const l=e.iconFA("undo",(e=>{this.setInput(t.name,this.getRestrictedValue(i),"restricted"),e.stopPropagation()}),"Reset value to computed value");a()(l).addClass("rfv-icon-undo"),a()(l).css({color:"var(--blue-2)"});const u=e.iconFA("exclamation-circle",null);e.tooltip.bind(u,(()=>`Current value is incosistent. Computed value was ${o.TYPES_SCALAR.has(t.property.propertyType)?this.getRestrictedValue(i):"different"}`)),a()(u).addClass("rfv-icon-warning"),a()(u).css({color:"var(--orange-2)"});const c=n;c.placeLockStateIcons||(c.placeLockStateIcons=function(t,e,i,o){tt(n)&&(n.addOptions(t),n.addOptions(e),n.addOptions(i),n.addOptions(o))}),c.placeLockStateIcons(s,r,l,u)}syncInput(t,e,n){const i=t.name;let r=!1;const a=this.funcCallReplaced.pipe((0,s.startWith)(!0)).subscribe((()=>{var t,o;const s=this.funcCall[Vn[n]][i],r=null!==(o=null!==(t=this.funcCall[n][i])&&void 0!==t?t:Bt(s.property))&&void 0!==o?o:null;e.notify=!1,e.value=r,e.notify=!0,this.funcCall[n][i]=r,this.setInputLockState(e,i,r,this.getInputLockState(i))}));this.subs.push(a);const l=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[Vn[n]][i];return t.onChanged.pipe((0,s.mapTo)(t))}))).subscribe((t=>{const i=this.funcCall[n][t.name];if(r||(e.notify=!1,e.value=i,e.notify=!0),n===Dn.INPUTS){this.isHistorical.next(!1),this.hideOutput(),this.validationRequests.next({field:t.name,isRevalidation:!1});const n=this.getInputLockState(t.name);"restricted unlocked"!==n&&"inconsistent"!==n||this.setInputLockState(e,t.name,i,i===this.getRestrictedValue(t.name)?"restricted unlocked":"inconsistent")}}));this.subs.push(l);const u=this.funcCallReplaced.pipe((0,s.startWith)(!0),(0,s.switchMap)((()=>{const t=this.funcCall[Vn[n]][i];return t.onChanged.pipe((0,s.mapTo)(t),(0,s.startWith)(t))})),(0,s.filter)((t=>t.property.propertyType===o.TYPE.DATA_FRAME&&t.value)),(0,s.switchMap)((t=>t.value.onDataChanged.pipe((0,s.mapTo)(t))))).subscribe((t=>{this.validationRequests.next({field:t.name,isRevalidation:!1})}));this.subs.push(u);const d=(p=e.onInput.bind(e),new c.Observable((t=>{const e=p((e=>{t.next(e)}));return()=>e.unsubscribe()}))).pipe((0,s.debounceTime)(250)).subscribe((()=>{try{r=!0,this.funcCall[n][t.name]=e.value}finally{r=!1}}));var p;this.subs.push(d)}isRunnable(){return!this.isRunning.value&&!this.blockRuns.value&&this.isValid()}isValid(){for(const[t,e]of Object.entries(this.validationState))if(!Y(e))return!1;for(const[t,e]of Object.entries(this.externalValidatorsState))if(!Y(e))return!1;return!0}getValidationState(){return this.validationState}getValidationMessage(){const t=[];for(const[e,n]of Object.entries(this.validationState))Y(n)||t.push(`${e}: ${U(n)}`);return t.join("\n")}runValidation(t,e){return Nn(this,void 0,void 0,(function*(){const n=t.field,i=this.getValidatedNames(n),o=yield Promise.all(i.map((n=>Nn(this,void 0,void 0,(function*(){const i=this.funcCall.inputs[n],o=yield(u=i,this._funcCall,this.lastCall,t.isNewOutput,t.isRevalidation,s=void 0,r=void 0,a=void 0,l=function*(){if(null==u)return W({errors:["Missing value"]})},new(a||(a=Promise))((function(t,e){function n(t){try{o(l.next(t))}catch(t){e(t)}}function i(t){try{o(l.throw(t))}catch(t){e(t)}}function o(e){var o;e.done?t(e.value):(o=e.value,o instanceof a?o:new a((function(t){t(o)}))).then(n,i)}o((l=l.apply(s,r||[])).next())})));var s,r,a,l,u;let c;const d=this.validators[n];return d&&(c=yield d(i,{param:n,funcCall:this._funcCall,lastCall:this.lastCall,signal:e,isNewOutput:!!t.isNewOutput,isRevalidation:t.isRevalidation,context:t.context,view:this})),[n,G(...this.funcCall.inputParams[n].property.options.nullable?[]:[o],c)]})))));return Object.fromEntries(o)}))}setValidationPending(t){const e=this.getValidatedNames(t);for(const t of e){this.validationState[t]={pending:!0};const e=this.inputsMap[t];V(e)&&e.setValidation({pending:!0})}this.validationUpdates.next(null)}setValidationResults(t){for(const[e,n]of Object.entries(t))this.validationState[e]=n,this.updateInputValidationReuslts(e)}updateInputValidationReuslts(t){const e=G(this.validationState[t],this.externalValidatorsState[t]),n=this.inputsMap[t];V(n)&&n.setValidation(e)}runRevalidations(t,e){if(!t.isRevalidation)for(const[,t]of Object.entries(e))if(null==t?void 0:t.revalidate)for(const e of t.revalidate)this.validationRequests.next({field:e,context:t.context,isRevalidation:!0})}getValidatedNames(t){return t?[t]:[...this.funcCall.inputs.keys()]}getValidExpRun(e){return Nn(this,void 0,void 0,(function*(){const n=yield(yield t.functions.eval("Sin")).prepare({x:1}).call();e.dart.r2=n.dart.r2;const i=e.options.immutable_tags||[];return e.options.immutable_tags=i.includes(C)?i:[...i,C],e.newId(),e}))}saveExperimentalRun(t){return Nn(this,void 0,void 0,(function*(){const e=yield this.getValidExpRun(t);yield this.saveRun(e)}))}hideOutput(){if(this._isOutputOutdated.next(!0),this.keepOutput())return;this.outputTabsLabels.forEach((t=>a()(this.tabsElem.getPane(t).header).hide()));const t=this.tabsElem.panes.find((t=>this.inputTabsLabels.includes(t.name)));t?this.tabsElem.currentPane=t:a()(this.tabsElem.root).hide()}getSheetName(t,e){if(this.sheetNamesCache[t])return this.sheetNamesCache[t];let n=`${t}`;n.length>31&&(n=`${n.slice(0,31)}`);let i=1;for(;e.worksheets.some((t=>t.name===n));){let e=`${t}`;e.length>31-`-${i}`.length&&(e=`${t.slice(0,31-`-${i}`.length)}`),n=`${e}-${i}`,i++}return this.sheetNamesCache[t]=n,n}richFunctionViewSupportedFormats(){return["Excel","DataUrl images"]}richFunctionViewExportExtensions(){return{Excel:"xlsx","DataUrl images":"txt"}}}n(693),Error;var Yn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};function Hn(e){return()=>Yn(this,void 0,void 0,(function*(){try{const n=yield t.dapi.groups.filter(`friendlyName="${e}"`).list();if(0===n.length)throw new Error("group with specified name is not found");if(n.length>1)throw new Error("found more than one group with specified name");const i=n[0];fetch(`${window.location.origin}/api/groups/${i.id}/requests/${t.shell.user.group.id}`,{method:"POST"})}catch(e){t.shell.error(e.toString())}}))}class Un extends o.ObjectHandler{get type(){return"Model"}getById(e){return Yn(this,void 0,void 0,(function*(){return yield t.dapi.functions.find(e)}))}refresh(t){return Yn(this,void 0,void 0,(function*(){return yield this.getById(t.id)}))}static openHelp(n){return Yn(this,void 0,void 0,(function*(){if(null!=n.options.readme){t.shell.windows.showHelp=!0,yield new Promise((t=>setTimeout(t,100)));const i=`System:AppData/${n.package.name}/${n.options.readme}`;t.dapi.files.readAsText(i).then((n=>{t.shell.windows.help.showHelp(e.markdown(n))}))}}))}static openModel(t){t.prepare().edit()}static openModelFromFunccall(t){t.edit()}isApplicable(t){const e=o.toJs(t);return e instanceof o.Func&&e.hasTag("model")}constructor(){super(),this.userGroups=new c.BehaviorSubject(void 0)}getLanguageIcon(t){return"grok"==t?e.iconSvg("project"):e.iconImage("script",`/images/entities/${t}.png`)}renderMarkup(n){const i=e.divH([],{style:{"justify-content":"space-between",width:"100%"}});return setTimeout((()=>Yn(this,void 0,void 0,(function*(){const o=yield this.awaitUserGroups(),s=JSON.parse(n.options.mandatoryUserGroups?`${n.options.mandatoryUserGroups}`:"[]").filter((t=>!o.map((t=>t.friendlyName)).includes(t.name))),r=s.length>0,a=e.iconFA("exclamation-triangle",null);a.classList.remove("grok-icon");const l=()=>{const t=e.iconFA("times");return t.style.marginRight="6px",t.classList.remove("grok-icon"),t},u=e.div(e.divV([e.label("You should be a member of the following group(s):",{style:{marginLeft:"0px"}}),...s.map((t=>e.divV([e.span([l(),t.name],{style:{"font-weight":600}}),...t.help?[e.span([t.help],{style:{marginLeft:"16px"}})]:[],e.link("Request group membership",Hn(t.name),void 0,{style:{marginLeft:"16px"}})])))],{style:{gap:"10px"}})),c=e.span([this.renderIcon(n),e.label(n.friendlyName)]);var d;i.onclick=()=>{t.shell.windows.help.visible&&Un.openHelp(n)},r?c.classList.add("d4-disabled"):i.ondblclick=()=>{Un.openModel(n)},r&&(function(t){t.popover="auto",t.style.cursor="default",t.style.padding="10px",t.style.background="#fdffe5",t.style.border="1px solid #E4E6CE",t.style.borderRadius="2px",t.style.boxShadow="0 0 5px #E4E6CE",t.style.maxWidth="500px",t.style.color="var(--gray-6)"}(d=u),document.body.append(d),i.addEventListener("click",(()=>{!function(t,e){!function(t,e){const n=t.getBoundingClientRect().toJSON();e.style.inset="unset",e.style.top=n.y+"px",e.style.left=n.x+20+"px"}(t,e),e.showPopover()}(a,u)}))),i.append(c),r&&i.append(e.span([a]))})))),i}renderIcon(t){if(null!=t.options.icon&&(t.options.icon.startsWith("http://")||t.options.icon.startsWith("https://")))return e.iconImage("model-icon",t.options.icon);if(t instanceof o.Script)return this.getLanguageIcon(t.language);let n=(t=o.Func.find({package:t.package.name,name:t.name})[0]).package.getIconUrl();if(null!=t.options.icon){const e=n.split("/");e.pop(),e.push(t.options.icon),n=e.join("/")}return e.iconImage(t.package.name,n)}renderPreview(e){const n=Object.create(null,{renderPreview:{get:()=>super.renderPreview}});return Yn(this,void 0,void 0,(function*(){var i;const s=null!==(i=e.options.editor)&&void 0!==i?i:"Compute:RichFunctionViewEditor",r=yield t.functions.find(s);if(null!==r&&r instanceof o.Func){const t=r.prepare({call:e.prepare()});yield t.call(!1,void 0,{processed:!0});const n=t.getOutputParamValue();if(n instanceof o.View)return n}return n.renderPreview.call(this,e)}))}renderProperties(t){const n=e.accordion("ComputeModel");n.context=t;const i=e.div([e.span([this.renderIcon(t),e.label(t.friendlyName),e.contextActions(t),e.star(t.id)])]);return n.addTitle(i),null!=t.description&&i.appendChild(e.div([e.markdown(t.description)],"model-catalog-description")),i.appendChild(e.tags(t)),null!=t.options["dev.status"]&&i.appendChild(e.tableFromMap({Status:t.options["dev.status"]})),n.end(),n.root}renderTooltip(t){const n=e.span([this.renderIcon(t),e.label(t.friendlyName)]);return n.classList.add("d4-link-label"),e.bind(t,e.divV([e.h2(n),e.divV([e.divText(t.description,"ui-description")],{style:{lineHeight:"150%"}})]))}renderCard(t){const n=this.renderMarkup(t);return n.classList.add("d4-link-label"),e.bind(t,e.h2(n))}init(){this.registerParamFunc("Help",(t=>{Un.openHelp(o.toJs(t))})),setTimeout((()=>Yn(this,void 0,void 0,(function*(){const t=yield(yield fetch(`${window.location.origin}/api/groups/all_parents`)).json();this.userGroups.next(t)}))))}awaitUserGroups(){return Yn(this,void 0,void 0,(function*(){return this.userGroups.pipe((0,s.filter)((t=>!!t)),(0,s.map)((t=>t)),(0,s.take)(1)).toPromise()}))}}var Wn=n(847),Gn={};Gn.styleTagTransform=It(),Gn.setAttributes=bt(),Gn.insert=gt().bind(null,"head"),Gn.domAPI=mt(),Gn.insertStyleElement=Ct(),ht()(Wn.A,Gn),Wn.A&&Wn.A.locals&&Wn.A.locals;class zn extends o.CustomCardView{static findOrCreateCatalogView(t,e,n){var i;return null!==(i=this.findModelCatalogView(e))&&void 0!==i?i:this.createModelCatalogView(t,e,n)}static createModelCatalogView(t,e,n){const i=o.Func.find({package:n.name,name:e})[0].prepare(),s=new this(t,e);return s.parentCall=i,s}static findModelCatalogView(e){return f()(t.shell.views).find((t=>{var n;return(null===(n=t.parentCall)||void 0===n?void 0:n.func.name)==e}))}bindModel(t){var e;t.aux.showOnTaskBar=!1;const n=this.parentCall;null!=n&&(n.aux.view=null!==(e=zn.findModelCatalogView(this.funcName))&&void 0!==e?e:this,t.parentCall=n)}constructor(e,n){if(super({dataSource:t.dapi.functions,permanentFilter:"#model"}),this.funcName=n,this.isHelpOpen=!1,this.root.classList.add("model-catalog-view"),this.meta=new Un,this.name=e,this.permanentFilter="#model",this.renderMode=o.RENDER_MODE.BRIEF,this.objectType="Func",this.categoryFilters={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process",tag:"Tags"},this.filters={All:"",Favorites:"starredBy = @current","Used by me":"usedBy = @current"},this.hierarchy=["options.department","options.HL_process","options.process"],this.hierarchyProperties={"options.department":"Department","options.HL_process":"HL_process","options.process":"Process"},this.showTree=!0,this.initRibbon(),this.initMenu(),t.shell.windows.showProperties=!1,t.shell.windows.showHelp=this.isHelpOpen,!zn.findModelCatalogView(this.funcName)){const e=t.functions.onBeforeRunAction.subscribe((t=>{var e,n;t.func.hasTag("model")?this.bindModel(t):(null===(n=null===(e=t.inputs)||void 0===e?void 0:e.call)||void 0===n?void 0:n.func)instanceof o.Func&&t.inputs.call.func.hasTag("model")&&this.bindModel(t.inputs.call)})),n=t.events.onCurrentViewChanged.subscribe((()=>{return e=this,n=void 0,o=function*(){t.shell.v===this&&(t.shell.windows.showHelp=this.isHelpOpen)},new((i=void 0)||(i=Promise))((function(t,s){function r(t){try{l(o.next(t))}catch(t){s(t)}}function a(t){try{l(o.throw(t))}catch(t){s(t)}}function l(e){var n;e.done?t(e.value):(n=e.value,n instanceof i?n:new i((function(t){t(n)}))).then(r,a)}l((o=o.apply(e,n||[])).next())}));var e,n,i,o}));this.subs.push(e,n)}}initRibbon(){}initMenu(){this.ribbonMenu.group("Help").item("Compute Engine",(()=>window.open("https://github.com/datagrok-ai/public/tree/master/packages/Compute","_blank"))).item("Developing Models",(()=>window.open("https://datagrok.ai/help/compute/scripting","_blank"))).endGroup()}}var Jn=function(t,e,n,i){return new(n||(n=Promise))((function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,a)}l((i=i.apply(t,e||[])).next())}))};let qn=!1;const Kn=new o.Package;function Zn(t){Un.openModelFromFunccall(t)}function Xn(){return new u}function Qn(t){return $n.fromFuncCall(t,{historyEnabled:!0,isTabbed:!1})}function ti(t){return $n.fromFuncCall(t,{historyEnabled:!1,isTabbed:!0})}function ei(n){return Jn(this,void 0,void 0,(function*(){let i={};n.inputs.forEach((t=>i[t.name]=null));let s=`\ncurl --location --request POST '${t.settings.apiUrl}/v1/func/${n.nqName}/run' \\\n--header 'Authorization: ${ni("auth")}' \\\n--header 'Content-Type: application/json' \\\n--data-raw '${JSON.stringify(i)}'`,r=`\nvar myHeaders = new Headers();\nmyHeaders.append("Authorization", "${ni("auth")}");\nmyHeaders.append("Content-Type", "application/json");\n\nvar raw = JSON.stringify(${JSON.stringify(i)});\n\nvar requestOptions = {\n method: 'POST',\n headers: myHeaders,\n body: raw,\n redirect: 'follow'\n};\n\nfetch("${t.settings.apiUrl}/v1/func/${n.nqName}/run", requestOptions)\n .then(response => response.text())\n .then(result => console.log(result))\n .catch(error => console.log('error', error));`,a=e.tabControl({CURL:e.div([e.divText(s)]),JS:e.div([e.divText(r)])});return o.Widget.fromRoot(a.root)}))}function ni(t){let e=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0}function ii(t){return Jn(this,void 0,void 0,(function*(){return yield new Promise((t=>setTimeout(t,1e3))),[yield t.prepare({ambTemp:22,initTemp:100,desiredTemp:30,area:.06,heatCap:4200,heatTransferCoeff:8.3,simTime:21600}).call()]}))}function oi(n){return Jn(this,void 0,void 0,(function*(){const i=(yield t.functions.eval("Compute:CustomDataUploader")).prepare({func:n.func}),r=e.bigButton("Click me to get mock calls",(()=>i.call())),a=o.Widget.fromRoot(e.panel([e.divV([e.label("This part of dialog comes from my custom data uploader"),e.divH([r],{style:{"justify-content":"center"}})])])),l=t.functions.onBeforeRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!0)})),u=t.functions.onAfterRunAction.pipe((0,s.filter)((t=>t.id===i.id))).subscribe((()=>{e.setUpdateIndicator(r,!1)}));return a.subs.push(l,u),{uploadWidget:a,uploadFuncCall:i}}))}function si(t){t.defaultView.scatterPlot({xColumnName:"Initial temperature",yColumnName:"Time to cool"})}function ri(){qn||(o.ObjectHandler.list().find((t=>"Model"===t.type))||o.ObjectHandler.register(new Un),t.events.onAccordionConstructed.subscribe((t=>{const n=t.context;null!=n&&"script"==n.type&&(t.getPane("REST")||t.addPane("REST",(()=>e.wait((()=>Jn(this,void 0,void 0,(function*(){return(yield ei(n)).root})))))))})),qn=!0)}let ai=!1;function li(){const e=t.shell.startUri.indexOf("?"),n=t.shell.startUri.substring(8,e>0?e:void 0).split("/");if(!ai&&n.includes("Compute")){const e=zn.findOrCreateCatalogView("Model Catalog","modelCatalog",Kn);return t.shell.addView(e),ai=!0,void(n.length>3&&t.dapi.functions.filter(`shortName = "${n[3]}" and #model`).list().then((t=>{1==t.length&&Un.openModel(t[0])})))}const i=window.location.href.indexOf("?"),o=window.location.href.substring(8,i>0?i:void 0).split("/");if(o.includes("browse")){const e=zn.findModelCatalogView("modelCatalog");return e&&(t.shell.v=e),zn.createModelCatalogView("Model Catalog","modelCatalog",Kn)}if(o.includes("apps")){const e=zn.findModelCatalogView("modelCatalog");if(e)t.shell.v=e;else{const e=zn.createModelCatalogView("Model Catalog","modelCatalog",Kn);t.shell.addView(e)}}}function ci(t){const{reasonableMin:e,reasonableMax:n}=t;return t=>W({warnings:t<e||t>n?[`Minimum reasonable time is ${e}. Maximum reasonable time is ${n}`]:void 0,errors:t<0?["Time should be strictly positive"]:void 0})}function di(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp,i=e.funcCall.inputs.initTemp;return W({errors:[...t<n?[H(`Desired temperature cannot be less than ambient temperature (${n}). \n`,[{actionName:"Set desired equal to ambient",action:()=>e.funcCall.inputs.desiredTemp=n}])]:[],...t>i?[`Desired temperature cannot be higher than initial temperature (${i})`]:[]]})}}function pi(t){return(t,e)=>{const n=e.funcCall.inputs.ambTemp;return W({errors:[...t<n?[`Initial temperature cannot be less than ambient temperature (${n}).`]:[]]})}}function hi(t){return(t,e)=>{const n=e.funcCall.inputs.initTemp;return W({errors:[...t>n?[`Ambient temperature cannot be higher than initial temperature (${n})`]:[]]})}}function fi(t){return(t,e)=>W({errors:[...t<=0?["Heat capacity must be greater than zero."]:[]],notifications:[H("Heat capacity is only dependent on the object material.",[{actionName:"Google it",action:()=>{window.open("http://google.com")}}])]})}function mi(t){const n=e.stringInput("Custom input","");return n.root.style.backgroundColor="aqua",n.input.style.backgroundColor="aqua",n}function vi(t){return te.historyInputJSON("Previous run","ObjectCooling")}})(),compute=i})();
|
|
2
2
|
//# sourceMappingURL=package.js.map
|